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);
402 uint256 hash = tx.GetHash();
403 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
404 CWalletTx& wtx = (*mi).second;
406 BOOST_FOREACH(const CTxOut& txout, tx.vout)
410 wtx.MarkUnspent(&txout - &tx.vout[0]);
412 NotifyTransactionChanged(this, hash, CT_UPDATED);
420 void CWallet::MarkDirty()
424 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
425 item.second.MarkDirty();
429 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
431 uint256 hash = wtxIn.GetHash();
434 // Inserts only if not already there, returns tx inserted or tx found
435 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
436 CWalletTx& wtx = (*ret.first).second;
437 wtx.BindWallet(this);
438 bool fInsertedNew = ret.second;
441 wtx.nTimeReceived = GetAdjustedTime();
442 wtx.nOrderPos = IncOrderPosNext();
444 wtx.nTimeSmart = wtx.nTimeReceived;
445 if (wtxIn.hashBlock != 0)
447 if (mapBlockIndex.count(wtxIn.hashBlock))
449 unsigned int latestNow = wtx.nTimeReceived;
450 unsigned int latestEntry = 0;
452 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
453 int64 latestTolerated = latestNow + 300;
454 std::list<CAccountingEntry> acentries;
455 TxItems txOrdered = OrderedTxItems(acentries);
456 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
458 CWalletTx *const pwtx = (*it).second.first;
461 CAccountingEntry *const pacentry = (*it).second.second;
465 nSmartTime = pwtx->nTimeSmart;
467 nSmartTime = pwtx->nTimeReceived;
470 nSmartTime = pacentry->nTime;
471 if (nSmartTime <= latestTolerated)
473 latestEntry = nSmartTime;
474 if (nSmartTime > latestNow)
475 latestNow = nSmartTime;
481 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
482 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
485 printf("AddToWallet() : found %s in block %s not in index\n",
486 wtxIn.GetHash().ToString().substr(0,10).c_str(),
487 wtxIn.hashBlock.ToString().c_str());
491 bool fUpdated = false;
495 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
497 wtx.hashBlock = wtxIn.hashBlock;
500 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
502 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
503 wtx.nIndex = wtxIn.nIndex;
506 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
508 wtx.fFromMe = wtxIn.fFromMe;
511 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
515 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
518 if (fInsertedNew || fUpdated)
519 if (!wtx.WriteToDisk())
522 // If default receiving address gets used, replace it with a new one
523 CScript scriptDefaultKey;
524 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
525 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
527 if (txout.scriptPubKey == scriptDefaultKey)
529 CPubKey newDefaultKey;
530 if (GetKeyFromPool(newDefaultKey, false))
532 SetDefaultKey(newDefaultKey);
533 SetAddressBookName(vchDefaultKey.GetID(), "");
538 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
539 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
541 // Notify UI of new or updated transaction
542 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
544 // notify an external script when a wallet transaction comes in or is updated
545 std::string strCmd = GetArg("-walletnotify", "");
547 if ( !strCmd.empty())
549 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
550 boost::thread t(runCommand, strCmd); // thread runs free
557 // Add a transaction to the wallet, or update it.
558 // pblock is optional, but should be provided if the transaction is known to be in a block.
559 // If fUpdate is true, existing transactions will be updated.
560 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
562 uint256 hash = tx.GetHash();
565 bool fExisted = mapWallet.count(hash);
566 if (fExisted && !fUpdate) return false;
567 if (fExisted || IsMine(tx) || IsFromMe(tx))
569 CWalletTx wtx(this,tx);
570 // Get merkle branch if transaction was found in a block
572 wtx.SetMerkleBranch(pblock);
573 return AddToWallet(wtx);
576 WalletUpdateSpent(tx);
581 bool CWallet::EraseFromWallet(uint256 hash)
587 if (mapWallet.erase(hash))
588 CWalletDB(strWalletFile).EraseTx(hash);
594 isminetype CWallet::IsMine(const CTxIn &txin) const
598 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
599 if (mi != mapWallet.end())
601 const CWalletTx& prev = (*mi).second;
602 if (txin.prevout.n < prev.vout.size())
603 return IsMine(prev.vout[txin.prevout.n]);
609 int64 CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
613 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
614 if (mi != mapWallet.end())
616 const CWalletTx& prev = (*mi).second;
617 if (txin.prevout.n < prev.vout.size())
618 if (IsMine(prev.vout[txin.prevout.n]) & filter)
619 return prev.vout[txin.prevout.n].nValue;
625 bool CWallet::IsChange(const CTxOut& txout) const
627 // TODO: fix handling of 'change' outputs. The assumption is that any
628 // payment to a script that is ours, but isn't in the address book
629 // is change. That assumption is likely to break when we implement multisignature
630 // wallets that return change back into a multi-signature-protected address;
631 // a better way of identifying which outputs are 'the send' and which are
632 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
633 // which output, if any, was change).
634 if (::IsMine(*this, txout.scriptPubKey))
636 CTxDestination address;
637 if (!ExtractDestination(txout.scriptPubKey, address))
641 if (!mapAddressBook.count(address))
647 int64 CWalletTx::GetTxTime() const
649 int64 n = nTimeSmart;
650 return n ? n : nTimeReceived;
653 int CWalletTx::GetRequestCount() const
655 // Returns -1 if it wasn't being tracked
658 LOCK(pwallet->cs_wallet);
659 if (IsCoinBase() || IsCoinStake())
664 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
665 if (mi != pwallet->mapRequestCount.end())
666 nRequests = (*mi).second;
671 // Did anyone request this transaction?
672 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
673 if (mi != pwallet->mapRequestCount.end())
675 nRequests = (*mi).second;
677 // How about the block it's in?
678 if (nRequests == 0 && hashBlock != 0)
680 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
681 if (mi != pwallet->mapRequestCount.end())
682 nRequests = (*mi).second;
684 nRequests = 1; // If it's in someone else's block it must have got out
692 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
693 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount, const isminefilter& filter) const
695 nGeneratedImmature = nGeneratedMature = nFee = 0;
696 listReceived.clear();
698 strSentAccount = strFromAccount;
700 if (IsCoinBase() || IsCoinStake())
702 if (GetBlocksToMaturity() > 0)
703 nGeneratedImmature = pwallet->GetCredit(*this, filter);
705 nGeneratedMature = GetCredit(filter);
710 int64 nDebit = GetDebit(filter);
711 if (nDebit > 0) // debit>0 means we signed/sent this transaction
713 int64 nValueOut = GetValueOut();
714 nFee = nDebit - nValueOut;
718 BOOST_FOREACH(const CTxOut& txout, vout)
720 isminetype fIsMine = pwallet->IsMine(txout);
721 // Only need to handle txouts if AT LEAST one of these is true:
722 // 1) they debit from us (sent)
723 // 2) the output is to us (received)
726 // Don't report 'change' txouts
727 if (pwallet->IsChange(txout))
730 else if (!(fIsMine & filter))
733 // In either case, we need to get the destination address
734 CTxDestination address;
735 if (!ExtractDestination(txout.scriptPubKey, address))
737 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
738 this->GetHash().ToString().c_str());
739 address = CNoDestination();
742 // If we are debited by the transaction, add the output as a "sent" entry
744 listSent.push_back(make_pair(address, txout.nValue));
746 // If we are receiving the output, add it as a "received" entry
747 if (fIsMine & filter)
748 listReceived.push_back(make_pair(address, txout.nValue));
753 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
754 int64& nSent, int64& nFee, const isminefilter& filter) const
756 nGenerated = nReceived = nSent = nFee = 0;
758 int64 allGeneratedImmature, allGeneratedMature, allFee;
759 allGeneratedImmature = allGeneratedMature = allFee = 0;
760 string strSentAccount;
761 list<pair<CTxDestination, int64> > listReceived;
762 list<pair<CTxDestination, int64> > listSent;
763 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
765 if (strAccount == "")
766 nGenerated = allGeneratedMature;
767 if (strAccount == strSentAccount)
769 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
774 LOCK(pwallet->cs_wallet);
775 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
777 if (pwallet->mapAddressBook.count(r.first))
779 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
780 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
781 nReceived += r.second;
783 else if (strAccount.empty())
785 nReceived += r.second;
791 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
795 const int COPY_DEPTH = 3;
796 if (SetMerkleBranch() < COPY_DEPTH)
798 vector<uint256> vWorkQueue;
799 BOOST_FOREACH(const CTxIn& txin, vin)
800 vWorkQueue.push_back(txin.prevout.hash);
802 // This critsect is OK because txdb is already open
804 LOCK(pwallet->cs_wallet);
805 map<uint256, const CMerkleTx*> mapWalletPrev;
806 set<uint256> setAlreadyDone;
807 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
809 uint256 hash = vWorkQueue[i];
810 if (setAlreadyDone.count(hash))
812 setAlreadyDone.insert(hash);
815 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
816 if (mi != pwallet->mapWallet.end())
819 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
820 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
822 else if (mapWalletPrev.count(hash))
824 tx = *mapWalletPrev[hash];
826 else if (!fClient && txdb.ReadDiskTx(hash, tx))
832 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
836 int nDepth = tx.SetMerkleBranch();
837 vtxPrev.push_back(tx);
839 if (nDepth < COPY_DEPTH)
841 BOOST_FOREACH(const CTxIn& txin, tx.vin)
842 vWorkQueue.push_back(txin.prevout.hash);
848 reverse(vtxPrev.begin(), vtxPrev.end());
851 bool CWalletTx::WriteToDisk()
853 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
856 // Scan the block chain (starting in pindexStart) for transactions
857 // from or to us. If fUpdate is true, found transactions that already
858 // exist in the wallet will be updated.
859 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
863 CBlockIndex* pindex = pindexStart;
869 block.ReadFromDisk(pindex, true);
870 BOOST_FOREACH(CTransaction& tx, block.vtx)
872 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
875 pindex = pindex->pnext;
881 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
884 tx.ReadFromDisk(COutPoint(hashTx, 0));
885 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
890 void CWallet::ReacceptWalletTransactions()
898 vector<CDiskTxPos> vMissingTx;
899 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
901 CWalletTx& wtx = item.second;
902 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
906 bool fUpdated = false;
907 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
909 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
910 if (txindex.vSpent.size() != wtx.vout.size())
912 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
915 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
919 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
923 vMissingTx.push_back(txindex.vSpent[i]);
928 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
935 // Re-accept any txes of ours that aren't already in a block
936 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
937 wtx.AcceptWalletTransaction(txdb, false);
940 if (!vMissingTx.empty())
942 // TODO: optimize this to scan just part of the block chain?
943 if (ScanForWalletTransactions(pindexGenesisBlock))
944 fRepeat = true; // Found missing transactions: re-do re-accept.
949 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
951 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
953 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
955 uint256 hash = tx.GetHash();
956 if (!txdb.ContainsTx(hash))
957 RelayTransaction((CTransaction)tx, hash);
960 if (!(IsCoinBase() || IsCoinStake()))
962 uint256 hash = GetHash();
963 if (!txdb.ContainsTx(hash))
965 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
966 RelayTransaction((CTransaction)*this, hash);
971 void CWalletTx::RelayWalletTransaction()
974 RelayWalletTransaction(txdb);
977 void CWallet::ResendWalletTransactions()
979 // Do this infrequently and randomly to avoid giving away
980 // that these are our transactions.
981 static int64 nNextTime;
982 if (GetTime() < nNextTime)
984 bool fFirst = (nNextTime == 0);
985 nNextTime = GetTime() + GetRand(30 * 60);
989 // Only do it if there's been a new block since last time
990 static int64 nLastTime;
991 if (nTimeBestReceived < nLastTime)
993 nLastTime = GetTime();
995 // Rebroadcast any of our txes that aren't in a block yet
996 printf("ResendWalletTransactions()\n");
1000 // Sort them in chronological order
1001 multimap<unsigned int, CWalletTx*> mapSorted;
1002 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1004 CWalletTx& wtx = item.second;
1005 // Don't rebroadcast until it's had plenty of time that
1006 // it should have gotten in already by now.
1007 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1008 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1010 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1012 CWalletTx& wtx = *item.second;
1013 if (wtx.CheckTransaction())
1014 wtx.RelayWalletTransaction(txdb);
1016 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1026 //////////////////////////////////////////////////////////////////////////////
1032 int64 CWallet::GetBalance() const
1037 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1039 const CWalletTx* pcoin = &(*it).second;
1040 if (pcoin->IsTrusted())
1041 nTotal += pcoin->GetAvailableCredit();
1048 int64 CWallet::GetWatchOnlyBalance() const
1053 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1055 const CWalletTx* pcoin = &(*it).second;
1056 if (pcoin->IsTrusted())
1057 nTotal += pcoin->GetAvailableWatchCredit();
1064 int64 CWallet::GetUnconfirmedBalance() const
1069 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1071 const CWalletTx* pcoin = &(*it).second;
1072 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1073 nTotal += pcoin->GetAvailableCredit();
1079 int64 CWallet::GetUnconfirmedWatchOnlyBalance() const
1084 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1086 const CWalletTx* pcoin = &(*it).second;
1087 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1088 nTotal += pcoin->GetAvailableWatchCredit();
1094 int64 CWallet::GetImmatureBalance() const
1099 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1101 const CWalletTx* pcoin = &(*it).second;
1102 nTotal += pcoin->GetImmatureCredit();
1108 int64 CWallet::GetImmatureWatchOnlyBalance() const
1113 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1115 const CWalletTx* pcoin = &(*it).second;
1116 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1122 // populate vCoins with vector of spendable COutputs
1123 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1129 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1131 const CWalletTx* pcoin = &(*it).second;
1133 if (!pcoin->IsFinal())
1136 if (fOnlyConfirmed && !pcoin->IsTrusted())
1139 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1142 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1145 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1146 isminetype mine = IsMine(pcoin->vout[i]);
1147 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1148 pcoin->vout[i].nValue >= nMinimumInputValue &&
1149 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1151 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1158 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64 nMinValue, int64 nMaxValue) const
1164 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1166 const CWalletTx* pcoin = &(*it).second;
1168 if (!pcoin->IsFinal())
1171 if(pcoin->GetDepthInMainChain() < nConf)
1174 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1175 isminetype mine = IsMine(pcoin->vout[i]);
1177 // ignore coin if it was already spent or we don't own it
1178 if (pcoin->IsSpent(i) || mine == MINE_NO)
1181 // if coin value is between required limits then add new item to vector
1182 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1183 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1189 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1190 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1192 vector<char> vfIncluded;
1194 vfBest.assign(vValue.size(), true);
1195 nBest = nTotalLower;
1197 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1199 vfIncluded.assign(vValue.size(), false);
1201 bool fReachedTarget = false;
1202 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1204 for (unsigned int i = 0; i < vValue.size(); i++)
1206 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1208 nTotal += vValue[i].first;
1209 vfIncluded[i] = true;
1210 if (nTotal >= nTargetValue)
1212 fReachedTarget = true;
1216 vfBest = vfIncluded;
1218 nTotal -= vValue[i].first;
1219 vfIncluded[i] = false;
1227 int64 CWallet::GetStake() const
1231 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1233 const CWalletTx* pcoin = &(*it).second;
1234 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1235 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1240 int64 CWallet::GetWatchOnlyStake() const
1244 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1246 const CWalletTx* pcoin = &(*it).second;
1247 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1248 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1253 int64 CWallet::GetNewMint() const
1257 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1259 const CWalletTx* pcoin = &(*it).second;
1260 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1261 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1266 int64 CWallet::GetWatchOnlyNewMint() const
1270 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1272 const CWalletTx* pcoin = &(*it).second;
1273 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1274 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1279 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
1281 setCoinsRet.clear();
1284 // List of values less than target
1285 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1286 coinLowestLarger.first = std::numeric_limits<int64>::max();
1287 coinLowestLarger.second.first = NULL;
1288 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1289 int64 nTotalLower = 0;
1291 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1293 BOOST_FOREACH(const COutput &output, vCoins)
1295 if (!output.fSpendable)
1298 const CWalletTx *pcoin = output.tx;
1300 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1305 // Follow the timestamp rules
1306 if (pcoin->nTime > nSpendTime)
1309 int64 n = pcoin->vout[i].nValue;
1311 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1313 if (n == nTargetValue)
1315 setCoinsRet.insert(coin.second);
1316 nValueRet += coin.first;
1319 else if (n < nTargetValue + CENT)
1321 vValue.push_back(coin);
1324 else if (n < coinLowestLarger.first)
1326 coinLowestLarger = coin;
1330 if (nTotalLower == nTargetValue)
1332 for (unsigned int i = 0; i < vValue.size(); ++i)
1334 setCoinsRet.insert(vValue[i].second);
1335 nValueRet += vValue[i].first;
1340 if (nTotalLower < nTargetValue)
1342 if (coinLowestLarger.second.first == NULL)
1344 setCoinsRet.insert(coinLowestLarger.second);
1345 nValueRet += coinLowestLarger.first;
1349 // Solve subset sum by stochastic approximation
1350 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1351 vector<char> vfBest;
1354 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1355 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1356 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1358 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1359 // or the next bigger coin is closer), return the bigger coin
1360 if (coinLowestLarger.second.first &&
1361 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1363 setCoinsRet.insert(coinLowestLarger.second);
1364 nValueRet += coinLowestLarger.first;
1367 for (unsigned int i = 0; i < vValue.size(); i++)
1370 setCoinsRet.insert(vValue[i].second);
1371 nValueRet += vValue[i].first;
1374 if (fDebug && GetBoolArg("-printpriority"))
1377 printf("SelectCoins() best subset: ");
1378 for (unsigned int i = 0; i < vValue.size(); i++)
1380 printf("%s ", FormatMoney(vValue[i].first).c_str());
1381 printf("total %s\n", FormatMoney(nBest).c_str());
1388 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1390 vector<COutput> vCoins;
1391 AvailableCoins(vCoins, true, coinControl);
1393 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1394 if (coinControl && coinControl->HasSelected())
1396 BOOST_FOREACH(const COutput& out, vCoins)
1400 nValueRet += out.tx->vout[out.i].nValue;
1401 setCoinsRet.insert(make_pair(out.tx, out.i));
1403 return (nValueRet >= nTargetValue);
1406 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1407 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1408 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1411 // Select some coins without random shuffle or best subset approximation
1412 bool CWallet::SelectCoinsSimple(int64 nTargetValue, int64 nMinValue, int64 nMaxValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1414 vector<COutput> vCoins;
1415 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1417 setCoinsRet.clear();
1420 BOOST_FOREACH(COutput output, vCoins)
1422 if(!output.fSpendable)
1424 const CWalletTx *pcoin = output.tx;
1427 // Ignore immature coins
1428 if (pcoin->GetBlocksToMaturity() > 0)
1431 // Stop if we've chosen enough inputs
1432 if (nValueRet >= nTargetValue)
1435 // Follow the timestamp rules
1436 if (pcoin->nTime > nSpendTime)
1439 int64 n = pcoin->vout[i].nValue;
1441 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1443 if (n >= nTargetValue)
1445 // If input value is greater or equal to target then simply insert
1446 // it into the current subset and exit
1447 setCoinsRet.insert(coin.second);
1448 nValueRet += coin.first;
1451 else if (n < nTargetValue + CENT)
1453 setCoinsRet.insert(coin.second);
1454 nValueRet += coin.first;
1461 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1464 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1470 if (vecSend.empty() || nValue < 0)
1473 wtxNew.BindWallet(this);
1476 LOCK2(cs_main, cs_wallet);
1477 // txdb must be opened before the mapWallet lock
1480 nFeeRet = nTransactionFee;
1484 wtxNew.vout.clear();
1485 wtxNew.fFromMe = true;
1487 int64 nTotalValue = nValue + nFeeRet;
1488 double dPriority = 0;
1489 // vouts to the payees
1490 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1491 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1493 // Choose coins to use
1494 set<pair<const CWalletTx*,unsigned int> > setCoins;
1496 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1498 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1500 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1501 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1504 int64 nChange = nValueIn - nValue - nFeeRet;
1505 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1506 // or until nChange becomes zero
1507 // NOTE: this depends on the exact behaviour of GetMinFee
1508 if (wtxNew.nTime < FEE_SWITCH_TIME && !fTestNet)
1510 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1512 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1513 nChange -= nMoveToFee;
1514 nFeeRet += nMoveToFee;
1517 // sub-cent change is moved to fee
1518 if (nChange > 0 && nChange < CENT)
1527 // Fill a vout to ourself
1528 // TODO: pass in scriptChange instead of reservekey so
1529 // change transaction isn't always pay-to-bitcoin-address
1530 CScript scriptChange;
1532 // coin control: send change to custom address
1533 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1534 scriptChange.SetDestination(coinControl->destChange);
1536 // no coin control: send change to newly generated address
1539 // Note: We use a new key here to keep it from being obvious which side is the change.
1540 // The drawback is that by not reusing a previous key, the change may be lost if a
1541 // backup is restored, if the backup doesn't have the new private key for the change.
1542 // If we reused the old key, it would be possible to add code to look for and
1543 // rediscover unknown transactions that were written with keys of ours to recover
1544 // post-backup change.
1546 // Reserve a new key pair from key pool
1547 CPubKey vchPubKey = reservekey.GetReservedKey();
1549 scriptChange.SetDestination(vchPubKey.GetID());
1552 // Insert change txn at random position:
1553 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1554 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1557 reservekey.ReturnKey();
1560 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1561 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1565 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1566 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1570 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1571 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1573 dPriority /= nBytes;
1575 // Check that enough fee is included
1576 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1577 bool fAllowFree = CTransaction::AllowFree(dPriority);
1579 // Disable free transactions until 1 July 2014
1580 if (!fTestNet && wtxNew.nTime < FEE_SWITCH_TIME)
1585 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1587 if (nFeeRet < max(nPayFee, nMinFee))
1589 nFeeRet = max(nPayFee, nMinFee);
1593 // Fill vtxPrev by copying from previous transactions vtxPrev
1594 wtxNew.AddSupportingTransactions(txdb);
1595 wtxNew.fTimeReceivedIsTxTime = true;
1604 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1606 vector< pair<CScript, int64> > vecSend;
1607 vecSend.push_back(make_pair(scriptPubKey, nValue));
1608 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1611 void CWallet::GetStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
1613 int64 nTimeWeight = GetWeight(nTime, (int64)GetTime());
1615 // If time weight is lower or equal to zero then weight is zero.
1616 if (nTimeWeight <= 0)
1622 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1623 nWeight = bnCoinDayWeight.getuint64();
1627 // NovaCoin: get current stake weight
1628 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1630 // Choose coins to use
1631 int64 nBalance = GetBalance();
1632 int64 nReserveBalance = 0;
1634 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1635 return error("CreateCoinStake : invalid reserve balance amount");
1637 if (nBalance <= nReserveBalance)
1642 LOCK2(cs_main, cs_wallet);
1643 // Cache outputs unless best block or wallet transaction set changed
1644 if (!fCoinsDataActual)
1649 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, GetAdjustedTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1652 if (setCoins.empty())
1658 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1660 // Load transaction index item
1661 if (!txdb.ReadTxIndex(pcoin->first->GetHash(), txindex))
1664 // Read block header
1665 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1668 uint64 nStakeModifier = 0;
1669 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
1673 // txid => ((txindex, (tx, vout.n)), (block, modifier))
1674 mapMeta[pcoin->first->GetHash()] = make_pair(make_pair(txindex, *pcoin), make_pair(block, nStakeModifier));
1677 printf("Load coin: %s\n", pcoin->first->GetHash().GetHex().c_str());
1682 printf("Get stake weight: %zu meta items loaded for %zu coins\n", mapMeta.size(), setCoins.size());
1684 fCoinsDataActual = true;
1689 // txid => ((txindex, (tx, vout.n)), (block, modifier))
1690 for(MetaMap::const_iterator meta_item = mapMeta.begin(); meta_item != mapMeta.end(); meta_item++)
1693 CoinsSet::value_type pcoin = meta_item->second.first.second;
1695 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1696 CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1698 // Weight is greater than zero
1699 if (nTimeWeight > 0)
1701 nWeight += bnCoinDayWeight.getuint64();
1704 // Weight is greater than zero, but the maximum value isn't reached yet
1705 if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1707 nMinWeight += bnCoinDayWeight.getuint64();
1710 // Maximum weight was reached
1711 if (nTimeWeight == nStakeMaxAge)
1713 nMaxWeight += bnCoinDayWeight.getuint64();
1720 bool CWallet::MergeCoins(const int64& nAmount, const int64& nMinValue, const int64& nOutputValue, list<uint256>& listMerged)
1722 int64 nBalance = GetBalance();
1724 if (nAmount > nBalance)
1729 set<pair<const CWalletTx*,unsigned int> > setCoins;
1731 // Simple coins selection - no randomization
1732 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
1735 if (setCoins.empty())
1739 vector<const CWalletTx*> vwtxPrev;
1741 // Reserve a new key pair from key pool
1742 CReserveKey reservekey(this);
1743 CPubKey vchPubKey = reservekey.GetReservedKey();
1746 CScript scriptOutput;
1747 scriptOutput.SetDestination(vchPubKey.GetID());
1750 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1753 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1755 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1757 // Add current coin to inputs list and add its credit to transaction output
1758 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1759 wtxNew.vout[0].nValue += nCredit;
1760 vwtxPrev.push_back(pcoin.first);
1763 // Replaced with estimation for performance purposes
1765 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1766 const CWalletTx *txin = vwtxPrev[i];
1768 // Sign scripts to get actual transaction size for fee calculation
1769 if (!SignSignature(*this, *txin, wtxNew, i))
1774 // Assuming that average scriptsig size is 110 bytes
1775 int64 nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1776 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1778 double dFinalPriority = dWeight /= nBytes;
1779 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1781 // Get actual transaction fee according to its estimated size and priority
1782 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1784 // Prepare transaction for commit if sum is enough ot its size is too big
1785 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1787 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1789 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1790 const CWalletTx *txin = vwtxPrev[i];
1793 if (!SignSignature(*this, *txin, wtxNew, i))
1797 // Try to commit, return false on failure
1798 if (!CommitTransaction(wtxNew, reservekey))
1801 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1803 dWeight = 0; // Reset all temporary values
1806 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1810 // Create transactions if there are some unhandled coins left
1811 if (wtxNew.vout[0].nValue > 0) {
1812 int64 nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1814 double dFinalPriority = dWeight /= nBytes;
1815 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1817 // Get actual transaction fee according to its size and priority
1818 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1820 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1822 if (wtxNew.vout[0].nValue <= 0)
1825 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1826 const CWalletTx *txin = vwtxPrev[i];
1828 // Sign all scripts again
1829 if (!SignSignature(*this, *txin, wtxNew, i))
1833 // Try to commit, return false on failure
1834 if (!CommitTransaction(wtxNew, reservekey))
1837 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1844 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1846 // The following combine threshold is important to security
1847 // Should not be adjusted if you don't understand the consequences
1848 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1850 CBigNum bnTargetPerCoinDay;
1851 bnTargetPerCoinDay.SetCompact(nBits);
1856 // Mark coin stake transaction
1857 CScript scriptEmpty;
1858 scriptEmpty.clear();
1859 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1861 // Choose coins to use
1862 int64 nBalance = GetBalance();
1863 int64 nReserveBalance = 0;
1865 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1866 return error("CreateCoinStake : invalid reserve balance amount");
1868 if (nBalance <= nReserveBalance)
1871 vector<const CWalletTx*> vwtxPrev;
1875 LOCK2(cs_main, cs_wallet);
1876 // Cache outputs unless best block or wallet transaction set changed
1877 if (!fCoinsDataActual)
1882 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1885 if (setCoins.empty())
1891 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1893 // Load transaction index item
1894 if (!txdb.ReadTxIndex(pcoin->first->GetHash(), txindex))
1897 // Read block header
1898 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1901 uint64 nStakeModifier = 0;
1902 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
1906 // txid => ((txindex, (tx, vout.n)), (block, modifier))
1907 mapMeta[pcoin->first->GetHash()] = make_pair(make_pair(txindex, *pcoin), make_pair(block, nStakeModifier));
1910 printf("Load coin: %s\n", pcoin->first->GetHash().GetHex().c_str());
1915 printf("Stake miner: %zu meta items loaded for %zu coins\n", mapMeta.size(), setCoins.size());
1917 fCoinsDataActual = true;
1922 CScript scriptPubKeyKernel;
1924 KernelSearchSettings settings;
1925 settings.nBits = nBits;
1926 settings.nTime = txNew.nTime;
1927 settings.nOffset = 0;
1928 settings.nLimit = mapMeta.size();
1929 settings.nSearchInterval = nSearchInterval;
1931 unsigned int nTimeTx, nBlockTime;
1932 COutPoint prevoutStake;
1933 CoinsSet::value_type kernelcoin;
1935 if (ScanForStakeKernelHash(mapMeta, settings, kernelcoin, nTimeTx, nBlockTime))
1938 if (fDebug && GetBoolArg("-printcoinstake"))
1939 printf("CreateCoinStake : kernel found\n");
1940 vector<valtype> vSolutions;
1941 txnouttype whichType;
1942 CScript scriptPubKeyOut;
1943 scriptPubKeyKernel = kernelcoin.first->vout[kernelcoin.second].scriptPubKey;
1944 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1946 if (fDebug && GetBoolArg("-printcoinstake"))
1947 printf("CreateCoinStake : failed to parse kernel\n");
1950 if (fDebug && GetBoolArg("-printcoinstake"))
1951 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1952 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1954 if (fDebug && GetBoolArg("-printcoinstake"))
1955 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1956 return false; // only support pay to public key and pay to address
1958 if (whichType == TX_PUBKEYHASH) // pay to address type
1960 // convert to pay to public key type
1961 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1963 if (fDebug && GetBoolArg("-printcoinstake"))
1964 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1965 return false; // unable to find corresponding public key
1967 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1969 if (whichType == TX_PUBKEY)
1971 valtype& vchPubKey = vSolutions[0];
1972 if (!keystore.GetKey(Hash160(vchPubKey), key))
1974 if (fDebug && GetBoolArg("-printcoinstake"))
1975 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1976 return false; // unable to find corresponding public key
1978 if (key.GetPubKey() != vchPubKey)
1980 if (fDebug && GetBoolArg("-printcoinstake"))
1981 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1982 return false; // keys mismatch
1985 scriptPubKeyOut = scriptPubKeyKernel;
1988 txNew.nTime = nTimeTx;
1989 txNew.vin.push_back(CTxIn(kernelcoin.first->GetHash(), kernelcoin.second));
1990 nCredit += kernelcoin.first->vout[kernelcoin.second].nValue;
1991 vwtxPrev.push_back(kernelcoin.first);
1992 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1994 if (GetWeight((int64)nBlockTime, (int64)txNew.nTime) < nStakeMaxAge)
1995 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1996 if (fDebug && GetBoolArg("-printcoinstake"))
1997 printf("CreateCoinStake : added kernel type=%d\n", whichType);
2000 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
2003 // txid => ((txindex, (tx, vout.n)), (block, modifier))
2004 for(MetaMap::const_iterator meta_item = mapMeta.begin(); meta_item != mapMeta.end(); meta_item++)
2007 CoinsSet::value_type pcoin = meta_item->second.first.second;
2009 // Attempt to add more inputs
2010 // Only add coins of the same key/address as kernel
2011 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
2012 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
2014 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
2016 // Stop adding more inputs if already too many inputs
2017 if (txNew.vin.size() >= 100)
2019 // Stop adding more inputs if value is already pretty significant
2020 if (nCredit > nCombineThreshold)
2022 // Stop adding inputs if reached reserve limit
2023 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
2025 // Do not add additional significant input
2026 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
2028 // Do not add input that is still too young
2029 if (nTimeWeight < nStakeMaxAge)
2032 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
2033 nCredit += pcoin.first->vout[pcoin.second].nValue;
2034 vwtxPrev.push_back(pcoin.first);
2038 // Calculate coin age reward
2042 if (!txNew.GetCoinAge(txdb, nCoinAge))
2043 return error("CreateCoinStake : failed to calculate coin age");
2044 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
2050 // Set output amount
2051 if (txNew.vout.size() == 3)
2053 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2054 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2057 txNew.vout[1].nValue = nCredit - nMinFee;
2061 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2063 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2064 return error("CreateCoinStake : failed to sign coinstake");
2068 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2069 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2070 return error("CreateCoinStake : exceeded coinstake size limit");
2072 // Check enough fee is paid
2073 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2075 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2076 continue; // try signing again
2080 if (fDebug && GetBoolArg("-printfee"))
2081 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2086 // Successfully generated coinstake
2091 // Call after CreateTransaction unless you want to abort
2092 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2095 LOCK2(cs_main, cs_wallet);
2096 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2098 // This is only to keep the database open to defeat the auto-flush for the
2099 // duration of this scope. This is the only place where this optimization
2100 // maybe makes sense; please don't do it anywhere else.
2101 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2103 // Take key pair from key pool so it won't be used again
2104 reservekey.KeepKey();
2106 // Add tx to wallet, because if it has change it's also ours,
2107 // otherwise just for transaction history.
2108 AddToWallet(wtxNew);
2110 // Mark old coins as spent
2111 set<CWalletTx*> setCoins;
2112 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2114 CWalletTx &coin = mapWallet[txin.prevout.hash];
2115 coin.BindWallet(this);
2116 coin.MarkSpent(txin.prevout.n);
2118 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2125 // Track how many getdata requests our transaction gets
2126 mapRequestCount[wtxNew.GetHash()] = 0;
2129 if (!wtxNew.AcceptToMemoryPool())
2131 // This must not fail. The transaction has already been signed and recorded.
2132 printf("CommitTransaction() : Error: Transaction not valid");
2135 wtxNew.RelayWalletTransaction();
2143 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
2145 CReserveKey reservekey(this);
2150 string strError = _("Error: Wallet locked, unable to create transaction ");
2151 printf("SendMoney() : %s", strError.c_str());
2154 if (fWalletUnlockMintOnly)
2156 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2157 printf("SendMoney() : %s", strError.c_str());
2160 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2163 if (nValue + nFeeRequired > GetBalance())
2164 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());
2166 strError = _("Error: Transaction creation failed ");
2167 printf("SendMoney() : %s", strError.c_str());
2171 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2174 if (!CommitTransaction(wtxNew, reservekey))
2175 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.");
2182 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
2186 return _("Invalid amount");
2187 if (nValue + nTransactionFee > GetBalance())
2188 return _("Insufficient funds");
2190 // Parse Bitcoin address
2191 CScript scriptPubKey;
2192 scriptPubKey.SetDestination(address);
2194 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2200 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2204 fFirstRunRet = false;
2205 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2206 if (nLoadWalletRet == DB_NEED_REWRITE)
2208 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2211 // Note: can't top-up keypool here, because wallet is locked.
2212 // User will be prompted to unlock wallet the next operation
2213 // the requires a new key.
2217 if (nLoadWalletRet != DB_LOAD_OK)
2218 return nLoadWalletRet;
2219 fFirstRunRet = !vchDefaultKey.IsValid();
2221 NewThread(ThreadFlushWalletDB, &strWalletFile);
2226 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2228 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2229 mapAddressBook[address] = strName;
2230 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2233 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2236 bool CWallet::DelAddressBookName(const CTxDestination& address)
2238 mapAddressBook.erase(address);
2239 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2242 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2246 void CWallet::PrintWallet(const CBlock& block)
2250 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
2252 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2253 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2255 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2257 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2258 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2265 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2269 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2270 if (mi != mapWallet.end())
2279 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2283 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2286 vchDefaultKey = vchPubKey;
2290 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2292 if (!pwallet->fFileBacked)
2294 strWalletFileOut = pwallet->strWalletFile;
2299 // Mark old keypool keys as used,
2300 // and generate all new keys
2302 bool CWallet::NewKeyPool()
2306 CWalletDB walletdb(strWalletFile);
2307 BOOST_FOREACH(int64 nIndex, setKeyPool)
2308 walletdb.ErasePool(nIndex);
2314 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2315 for (int i = 0; i < nKeys; i++)
2318 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2319 setKeyPool.insert(nIndex);
2321 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2326 bool CWallet::TopUpKeyPool(unsigned int nSize)
2334 CWalletDB walletdb(strWalletFile);
2337 unsigned int nTargetSize;
2339 nTargetSize = nSize;
2341 nTargetSize = max(GetArg("-keypool", 100), 0LL);
2343 while (setKeyPool.size() < (nTargetSize + 1))
2346 if (!setKeyPool.empty())
2347 nEnd = *(--setKeyPool.end()) + 1;
2348 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2349 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2350 setKeyPool.insert(nEnd);
2351 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2357 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2360 keypool.vchPubKey = CPubKey();
2367 // Get the oldest key
2368 if(setKeyPool.empty())
2371 CWalletDB walletdb(strWalletFile);
2373 nIndex = *(setKeyPool.begin());
2374 setKeyPool.erase(setKeyPool.begin());
2375 if (!walletdb.ReadPool(nIndex, keypool))
2376 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2377 if (!HaveKey(keypool.vchPubKey.GetID()))
2378 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2379 assert(keypool.vchPubKey.IsValid());
2380 if (fDebug && GetBoolArg("-printkeypool"))
2381 printf("keypool reserve %"PRI64d"\n", nIndex);
2385 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2388 LOCK2(cs_main, cs_wallet);
2389 CWalletDB walletdb(strWalletFile);
2391 int64 nIndex = 1 + *(--setKeyPool.end());
2392 if (!walletdb.WritePool(nIndex, keypool))
2393 throw runtime_error("AddReserveKey() : writing added key failed");
2394 setKeyPool.insert(nIndex);
2400 void CWallet::KeepKey(int64 nIndex)
2402 // Remove from key pool
2405 CWalletDB walletdb(strWalletFile);
2406 walletdb.ErasePool(nIndex);
2409 printf("keypool keep %"PRI64d"\n", nIndex);
2412 void CWallet::ReturnKey(int64 nIndex)
2414 // Return to key pool
2417 setKeyPool.insert(nIndex);
2420 printf("keypool return %"PRI64d"\n", nIndex);
2423 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2429 ReserveKeyFromKeyPool(nIndex, keypool);
2432 if (fAllowReuse && vchDefaultKey.IsValid())
2434 result = vchDefaultKey;
2437 if (IsLocked()) return false;
2438 result = GenerateNewKey();
2442 result = keypool.vchPubKey;
2447 int64 CWallet::GetOldestKeyPoolTime()
2451 ReserveKeyFromKeyPool(nIndex, keypool);
2455 return keypool.nTime;
2458 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2460 map<CTxDestination, int64> balances;
2464 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2466 CWalletTx *pcoin = &walletEntry.second;
2468 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2471 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2474 int nDepth = pcoin->GetDepthInMainChain();
2475 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2478 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2480 CTxDestination addr;
2481 if (!IsMine(pcoin->vout[i]))
2483 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2486 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2488 if (!balances.count(addr))
2490 balances[addr] += n;
2498 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2500 set< set<CTxDestination> > groupings;
2501 set<CTxDestination> grouping;
2503 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2505 CWalletTx *pcoin = &walletEntry.second;
2507 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2509 // group all input addresses with each other
2510 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2512 CTxDestination address;
2513 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2515 grouping.insert(address);
2518 // group change with input addresses
2519 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2520 if (IsChange(txout))
2522 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2523 CTxDestination txoutAddr;
2524 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2526 grouping.insert(txoutAddr);
2528 groupings.insert(grouping);
2532 // group lone addrs by themselves
2533 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2534 if (IsMine(pcoin->vout[i]))
2536 CTxDestination address;
2537 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2539 grouping.insert(address);
2540 groupings.insert(grouping);
2545 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2546 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2547 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2549 // make a set of all the groups hit by this new group
2550 set< set<CTxDestination>* > hits;
2551 map< CTxDestination, set<CTxDestination>* >::iterator it;
2552 BOOST_FOREACH(CTxDestination address, grouping)
2553 if ((it = setmap.find(address)) != setmap.end())
2554 hits.insert((*it).second);
2556 // merge all hit groups into a new single group and delete old groups
2557 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2558 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2560 merged->insert(hit->begin(), hit->end());
2561 uniqueGroupings.erase(hit);
2564 uniqueGroupings.insert(merged);
2567 BOOST_FOREACH(CTxDestination element, *merged)
2568 setmap[element] = merged;
2571 set< set<CTxDestination> > ret;
2572 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2574 ret.insert(*uniqueGrouping);
2575 delete uniqueGrouping;
2581 // ppcoin: check 'spent' consistency between wallet and txindex
2582 // ppcoin: fix wallet spent state according to txindex
2583 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2586 nBalanceInQuestion = 0;
2589 vector<CWalletTx*> vCoins;
2590 vCoins.reserve(mapWallet.size());
2591 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2592 vCoins.push_back(&(*it).second);
2595 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2597 // Find the corresponding transaction index
2599 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2601 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2603 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2605 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2606 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2608 nBalanceInQuestion += pcoin->vout[n].nValue;
2611 pcoin->MarkUnspent(n);
2612 pcoin->WriteToDisk();
2615 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2617 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2618 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2620 nBalanceInQuestion += pcoin->vout[n].nValue;
2623 pcoin->MarkSpent(n);
2624 pcoin->WriteToDisk();
2630 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2632 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2635 EraseFromWallet(pcoin->GetHash());
2641 // ppcoin: disable transaction (only for coinstake)
2642 void CWallet::DisableTransaction(const CTransaction &tx)
2644 if (!tx.IsCoinStake() || !IsFromMe(tx))
2645 return; // only disconnecting coinstake requires marking input unspent
2648 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2650 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2651 if (mi != mapWallet.end())
2653 CWalletTx& prev = (*mi).second;
2654 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2656 prev.MarkUnspent(txin.prevout.n);
2663 CPubKey CReserveKey::GetReservedKey()
2668 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2670 vchPubKey = keypool.vchPubKey;
2673 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2674 vchPubKey = pwallet->vchDefaultKey;
2677 assert(vchPubKey.IsValid());
2681 void CReserveKey::KeepKey()
2684 pwallet->KeepKey(nIndex);
2686 vchPubKey = CPubKey();
2689 void CReserveKey::ReturnKey()
2692 pwallet->ReturnKey(nIndex);
2694 vchPubKey = CPubKey();
2697 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2701 CWalletDB walletdb(strWalletFile);
2703 LOCK2(cs_main, cs_wallet);
2704 BOOST_FOREACH(const int64& id, setKeyPool)
2707 if (!walletdb.ReadPool(id, keypool))
2708 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2709 assert(keypool.vchPubKey.IsValid());
2710 CKeyID keyID = keypool.vchPubKey.GetID();
2711 if (!HaveKey(keyID))
2712 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2713 setAddress.insert(keyID);
2717 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2721 // Only notify UI if this transaction is in this wallet
2722 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2723 if (mi != mapWallet.end())
2724 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2728 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2729 mapKeyBirth.clear();
2731 // get birth times for keys with metadata
2732 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2733 if (it->second.nCreateTime)
2734 mapKeyBirth[it->first] = it->second.nCreateTime;
2736 // map in which we'll infer heights of other keys
2737 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2738 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2739 std::set<CKeyID> setKeys;
2741 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2742 if (mapKeyBirth.count(keyid) == 0)
2743 mapKeyFirstBlock[keyid] = pindexMax;
2747 // if there are no such keys, we're done
2748 if (mapKeyFirstBlock.empty())
2751 // find first block that affects those keys, if there are any left
2752 std::vector<CKeyID> vAffected;
2753 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2754 // iterate over all wallet transactions...
2755 const CWalletTx &wtx = (*it).second;
2756 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2757 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2758 // ... which are already in a block
2759 int nHeight = blit->second->nHeight;
2760 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2761 // iterate over all their outputs
2762 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2763 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2764 // ... and all their affected keys
2765 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2766 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2767 rit->second = blit->second;
2774 // Extract block timestamps for those keys
2775 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2776 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off