1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
10 #include "ui_interface.h"
13 #include "coincontrol.h"
14 #include <boost/algorithm/string/replace.hpp>
21 bool fCoinsDataActual;
23 //////////////////////////////////////////////////////////////////////////////
28 struct CompareValueOnly
30 bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
31 const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
33 return t1.first < t2.first;
37 CPubKey CWallet::GenerateNewKey()
39 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
43 key.MakeNewKey(fCompressed);
45 // Compressed public keys were introduced in version 0.6.0
47 SetMinVersion(FEATURE_COMPRPUBKEY);
49 CPubKey pubkey = key.GetPubKey();
51 // Create new metadata
52 int64 nCreationTime = GetTime();
53 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
54 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
55 nTimeFirstKey = nCreationTime;
58 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
59 return key.GetPubKey();
62 bool CWallet::AddKey(const CKey& key)
64 CPubKey pubkey = key.GetPubKey();
66 if (!CCryptoKeyStore::AddKey(key))
71 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
75 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
77 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
83 if (pwalletdbEncryption)
84 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
86 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
91 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
93 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
94 nTimeFirstKey = meta.nCreateTime;
96 mapKeyMetadata[pubkey.GetID()] = meta;
100 bool CWallet::AddCScript(const CScript& redeemScript)
102 if (!CCryptoKeyStore::AddCScript(redeemScript))
106 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
109 bool CWallet::AddWatchOnly(const CScript &dest)
111 if (!CCryptoKeyStore::AddWatchOnly(dest))
113 nTimeFirstKey = 1; // No birthday information for watch-only keys.
116 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
119 bool CWallet::LoadWatchOnly(const CScript &dest)
121 return CCryptoKeyStore::AddWatchOnly(dest);
124 // ppcoin: optional setting to unlock wallet for block minting only;
125 // serves to disable the trivial sendmoney when OS account compromised
126 bool fWalletUnlockMintOnly = false;
128 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
134 CKeyingMaterial vMasterKey;
138 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
140 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
142 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
144 if (CCryptoKeyStore::Unlock(vMasterKey))
151 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
153 bool fWasLocked = IsLocked();
160 CKeyingMaterial vMasterKey;
161 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
163 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
165 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
167 if (CCryptoKeyStore::Unlock(vMasterKey))
169 int64 nStartTime = GetTimeMillis();
170 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
171 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
173 nStartTime = GetTimeMillis();
174 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
175 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
177 if (pMasterKey.second.nDeriveIterations < 25000)
178 pMasterKey.second.nDeriveIterations = 25000;
180 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
182 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
184 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
186 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
197 void CWallet::SetBestChain(const CBlockLocator& loc)
199 CWalletDB walletdb(strWalletFile);
200 walletdb.WriteBestBlock(loc);
203 // This class implements an addrIncoming entry that causes pre-0.4
204 // clients to crash on startup if reading a private-key-encrypted wallet.
205 class CCorruptAddress
210 if (nType & SER_DISK)
215 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
217 if (nWalletVersion >= nVersion)
220 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
221 if (fExplicit && nVersion > nWalletMaxVersion)
222 nVersion = FEATURE_LATEST;
224 nWalletVersion = nVersion;
226 if (nVersion > nWalletMaxVersion)
227 nWalletMaxVersion = nVersion;
231 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
232 if (nWalletVersion >= 40000)
234 // Versions prior to 0.4.0 did not support the "minversion" record.
235 // Use a CCorruptAddress to make them crash instead.
236 CCorruptAddress corruptAddress;
237 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
239 if (nWalletVersion > 40000)
240 pwalletdb->WriteMinVersion(nWalletVersion);
248 bool CWallet::SetMaxVersion(int nVersion)
250 // cannot downgrade below current version
251 if (nWalletVersion > nVersion)
254 nWalletMaxVersion = nVersion;
259 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
264 CKeyingMaterial vMasterKey;
265 RandAddSeedPerfmon();
267 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
268 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
270 CMasterKey kMasterKey(nDerivationMethodIndex);
272 RandAddSeedPerfmon();
273 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
274 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
277 int64 nStartTime = GetTimeMillis();
278 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
279 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
281 nStartTime = GetTimeMillis();
282 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
283 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
285 if (kMasterKey.nDeriveIterations < 25000)
286 kMasterKey.nDeriveIterations = 25000;
288 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
290 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
292 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
297 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
300 pwalletdbEncryption = new CWalletDB(strWalletFile);
301 if (!pwalletdbEncryption->TxnBegin())
303 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
306 if (!EncryptKeys(vMasterKey))
309 pwalletdbEncryption->TxnAbort();
310 exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet.
313 // Encryption was introduced in version 0.4.0
314 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
318 if (!pwalletdbEncryption->TxnCommit())
319 exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet.
321 delete pwalletdbEncryption;
322 pwalletdbEncryption = NULL;
326 Unlock(strWalletPassphrase);
330 // Need to completely rewrite the wallet file; if we don't, bdb might keep
331 // bits of the unencrypted private key in slack space in the database file.
332 CDB::Rewrite(strWalletFile);
335 NotifyStatusChanged(this);
340 int64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
342 int64 nRet = nOrderPosNext++;
344 pwalletdb->WriteOrderPosNext(nOrderPosNext);
346 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
351 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
353 CWalletDB walletdb(strWalletFile);
355 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
358 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
359 // would make this much faster for applications that do this a lot.
360 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
362 CWalletTx* wtx = &((*it).second);
363 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
366 walletdb.ListAccountCreditDebit(strAccount, acentries);
367 BOOST_FOREACH(CAccountingEntry& entry, acentries)
369 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
375 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
377 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
378 // Update the wallet spent flag if it doesn't know due to wallet.dat being
379 // restored from backup or the user making copies of wallet.dat.
382 BOOST_FOREACH(const CTxIn& txin, tx.vin)
384 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
385 if (mi != mapWallet.end())
387 CWalletTx& wtx = (*mi).second;
388 if (txin.prevout.n >= wtx.vout.size())
389 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
390 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
392 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
393 wtx.MarkSpent(txin.prevout.n);
395 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
396 vMintingWalletUpdated.push_back(txin.prevout.hash);
403 uint256 hash = tx.GetHash();
404 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
405 CWalletTx& wtx = (*mi).second;
407 BOOST_FOREACH(const CTxOut& txout, tx.vout)
411 wtx.MarkUnspent(&txout - &tx.vout[0]);
413 NotifyTransactionChanged(this, hash, CT_UPDATED);
414 vMintingWalletUpdated.push_back(hash);
422 void CWallet::MarkDirty()
426 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
427 item.second.MarkDirty();
431 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
433 uint256 hash = wtxIn.GetHash();
436 // Inserts only if not already there, returns tx inserted or tx found
437 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
438 CWalletTx& wtx = (*ret.first).second;
439 wtx.BindWallet(this);
440 bool fInsertedNew = ret.second;
443 wtx.nTimeReceived = GetAdjustedTime();
444 wtx.nOrderPos = IncOrderPosNext();
446 wtx.nTimeSmart = wtx.nTimeReceived;
447 if (wtxIn.hashBlock != 0)
449 if (mapBlockIndex.count(wtxIn.hashBlock))
451 unsigned int latestNow = wtx.nTimeReceived;
452 unsigned int latestEntry = 0;
454 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
455 int64 latestTolerated = latestNow + 300;
456 std::list<CAccountingEntry> acentries;
457 TxItems txOrdered = OrderedTxItems(acentries);
458 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
460 CWalletTx *const pwtx = (*it).second.first;
463 CAccountingEntry *const pacentry = (*it).second.second;
467 nSmartTime = pwtx->nTimeSmart;
469 nSmartTime = pwtx->nTimeReceived;
472 nSmartTime = pacentry->nTime;
473 if (nSmartTime <= latestTolerated)
475 latestEntry = nSmartTime;
476 if (nSmartTime > latestNow)
477 latestNow = nSmartTime;
483 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
484 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
487 printf("AddToWallet() : found %s in block %s not in index\n",
488 wtxIn.GetHash().ToString().substr(0,10).c_str(),
489 wtxIn.hashBlock.ToString().c_str());
493 bool fUpdated = false;
497 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
499 wtx.hashBlock = wtxIn.hashBlock;
502 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
504 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
505 wtx.nIndex = wtxIn.nIndex;
508 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
510 wtx.fFromMe = wtxIn.fFromMe;
513 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
517 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
520 if (fInsertedNew || fUpdated)
521 if (!wtx.WriteToDisk())
524 // If default receiving address gets used, replace it with a new one
525 CScript scriptDefaultKey;
526 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
527 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
529 if (txout.scriptPubKey == scriptDefaultKey)
531 CPubKey newDefaultKey;
532 if (GetKeyFromPool(newDefaultKey, false))
534 SetDefaultKey(newDefaultKey);
535 SetAddressBookName(vchDefaultKey.GetID(), "");
540 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
541 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
543 // Notify UI of new or updated transaction
544 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
545 vMintingWalletUpdated.push_back(hash);
546 // notify an external script when a wallet transaction comes in or is updated
547 std::string strCmd = GetArg("-walletnotify", "");
549 if ( !strCmd.empty())
551 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
552 boost::thread t(runCommand, strCmd); // thread runs free
559 // Add a transaction to the wallet, or update it.
560 // pblock is optional, but should be provided if the transaction is known to be in a block.
561 // If fUpdate is true, existing transactions will be updated.
562 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
564 uint256 hash = tx.GetHash();
567 bool fExisted = mapWallet.count(hash);
568 if (fExisted && !fUpdate) return false;
569 if (fExisted || IsMine(tx) || IsFromMe(tx))
571 CWalletTx wtx(this,tx);
572 // Get merkle branch if transaction was found in a block
574 wtx.SetMerkleBranch(pblock);
575 return AddToWallet(wtx);
578 WalletUpdateSpent(tx);
583 bool CWallet::EraseFromWallet(uint256 hash)
589 if (mapWallet.erase(hash))
590 CWalletDB(strWalletFile).EraseTx(hash);
596 isminetype CWallet::IsMine(const CTxIn &txin) const
600 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
601 if (mi != mapWallet.end())
603 const CWalletTx& prev = (*mi).second;
604 if (txin.prevout.n < prev.vout.size())
605 return IsMine(prev.vout[txin.prevout.n]);
611 int64 CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
615 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
616 if (mi != mapWallet.end())
618 const CWalletTx& prev = (*mi).second;
619 if (txin.prevout.n < prev.vout.size())
620 if (IsMine(prev.vout[txin.prevout.n]) & filter)
621 return prev.vout[txin.prevout.n].nValue;
627 bool CWallet::IsChange(const CTxOut& txout) const
629 // TODO: fix handling of 'change' outputs. The assumption is that any
630 // payment to a script that is ours, but isn't in the address book
631 // is change. That assumption is likely to break when we implement multisignature
632 // wallets that return change back into a multi-signature-protected address;
633 // a better way of identifying which outputs are 'the send' and which are
634 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
635 // which output, if any, was change).
636 if (::IsMine(*this, txout.scriptPubKey))
638 CTxDestination address;
639 if (!ExtractDestination(txout.scriptPubKey, address))
643 if (!mapAddressBook.count(address))
649 int64 CWalletTx::GetTxTime() const
651 int64 n = nTimeSmart;
652 return n ? n : nTimeReceived;
655 int CWalletTx::GetRequestCount() const
657 // Returns -1 if it wasn't being tracked
660 LOCK(pwallet->cs_wallet);
661 if (IsCoinBase() || IsCoinStake())
666 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
667 if (mi != pwallet->mapRequestCount.end())
668 nRequests = (*mi).second;
673 // Did anyone request this transaction?
674 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
675 if (mi != pwallet->mapRequestCount.end())
677 nRequests = (*mi).second;
679 // How about the block it's in?
680 if (nRequests == 0 && hashBlock != 0)
682 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
683 if (mi != pwallet->mapRequestCount.end())
684 nRequests = (*mi).second;
686 nRequests = 1; // If it's in someone else's block it must have got out
694 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
695 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount, const isminefilter& filter) const
697 nGeneratedImmature = nGeneratedMature = nFee = 0;
698 listReceived.clear();
700 strSentAccount = strFromAccount;
702 if (IsCoinBase() || IsCoinStake())
704 if (GetBlocksToMaturity() > 0)
705 nGeneratedImmature = pwallet->GetCredit(*this, filter);
707 nGeneratedMature = GetCredit(filter);
712 int64 nDebit = GetDebit(filter);
713 if (nDebit > 0) // debit>0 means we signed/sent this transaction
715 int64 nValueOut = GetValueOut();
716 nFee = nDebit - nValueOut;
720 BOOST_FOREACH(const CTxOut& txout, vout)
722 isminetype fIsMine = pwallet->IsMine(txout);
723 // Only need to handle txouts if AT LEAST one of these is true:
724 // 1) they debit from us (sent)
725 // 2) the output is to us (received)
728 // Don't report 'change' txouts
729 if (pwallet->IsChange(txout))
732 else if (!(fIsMine & filter))
735 // In either case, we need to get the destination address
736 CTxDestination address;
737 if (!ExtractDestination(txout.scriptPubKey, address))
739 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
740 this->GetHash().ToString().c_str());
741 address = CNoDestination();
744 // If we are debited by the transaction, add the output as a "sent" entry
746 listSent.push_back(make_pair(address, txout.nValue));
748 // If we are receiving the output, add it as a "received" entry
749 if (fIsMine & filter)
750 listReceived.push_back(make_pair(address, txout.nValue));
755 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
756 int64& nSent, int64& nFee, const isminefilter& filter) const
758 nGenerated = nReceived = nSent = nFee = 0;
760 int64 allGeneratedImmature, allGeneratedMature, allFee;
761 allGeneratedImmature = allGeneratedMature = allFee = 0;
762 string strSentAccount;
763 list<pair<CTxDestination, int64> > listReceived;
764 list<pair<CTxDestination, int64> > listSent;
765 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
767 if (strAccount == "")
768 nGenerated = allGeneratedMature;
769 if (strAccount == strSentAccount)
771 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
776 LOCK(pwallet->cs_wallet);
777 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
779 if (pwallet->mapAddressBook.count(r.first))
781 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
782 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
783 nReceived += r.second;
785 else if (strAccount.empty())
787 nReceived += r.second;
793 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
797 const int COPY_DEPTH = 3;
798 if (SetMerkleBranch() < COPY_DEPTH)
800 vector<uint256> vWorkQueue;
801 BOOST_FOREACH(const CTxIn& txin, vin)
802 vWorkQueue.push_back(txin.prevout.hash);
804 // This critsect is OK because txdb is already open
806 LOCK(pwallet->cs_wallet);
807 map<uint256, const CMerkleTx*> mapWalletPrev;
808 set<uint256> setAlreadyDone;
809 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
811 uint256 hash = vWorkQueue[i];
812 if (setAlreadyDone.count(hash))
814 setAlreadyDone.insert(hash);
817 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
818 if (mi != pwallet->mapWallet.end())
821 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
822 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
824 else if (mapWalletPrev.count(hash))
826 tx = *mapWalletPrev[hash];
828 else if (!fClient && txdb.ReadDiskTx(hash, tx))
834 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
838 int nDepth = tx.SetMerkleBranch();
839 vtxPrev.push_back(tx);
841 if (nDepth < COPY_DEPTH)
843 BOOST_FOREACH(const CTxIn& txin, tx.vin)
844 vWorkQueue.push_back(txin.prevout.hash);
850 reverse(vtxPrev.begin(), vtxPrev.end());
853 bool CWalletTx::WriteToDisk()
855 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
858 // Scan the block chain (starting in pindexStart) for transactions
859 // from or to us. If fUpdate is true, found transactions that already
860 // exist in the wallet will be updated.
861 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
865 CBlockIndex* pindex = pindexStart;
871 block.ReadFromDisk(pindex, true);
872 BOOST_FOREACH(CTransaction& tx, block.vtx)
874 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
877 pindex = pindex->pnext;
883 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
886 tx.ReadFromDisk(COutPoint(hashTx, 0));
887 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
892 void CWallet::ReacceptWalletTransactions()
900 vector<CDiskTxPos> vMissingTx;
901 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
903 CWalletTx& wtx = item.second;
904 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
908 bool fUpdated = false;
909 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
911 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
912 if (txindex.vSpent.size() != wtx.vout.size())
914 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
917 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
921 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
925 vMissingTx.push_back(txindex.vSpent[i]);
930 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
937 // Re-accept any txes of ours that aren't already in a block
938 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
939 wtx.AcceptWalletTransaction(txdb, false);
942 if (!vMissingTx.empty())
944 // TODO: optimize this to scan just part of the block chain?
945 if (ScanForWalletTransactions(pindexGenesisBlock))
946 fRepeat = true; // Found missing transactions: re-do re-accept.
951 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
953 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
955 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
957 uint256 hash = tx.GetHash();
958 if (!txdb.ContainsTx(hash))
959 RelayTransaction((CTransaction)tx, hash);
962 if (!(IsCoinBase() || IsCoinStake()))
964 uint256 hash = GetHash();
965 if (!txdb.ContainsTx(hash))
967 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
968 RelayTransaction((CTransaction)*this, hash);
973 void CWalletTx::RelayWalletTransaction()
976 RelayWalletTransaction(txdb);
979 void CWallet::ResendWalletTransactions()
981 // Do this infrequently and randomly to avoid giving away
982 // that these are our transactions.
983 static int64 nNextTime;
984 if (GetTime() < nNextTime)
986 bool fFirst = (nNextTime == 0);
987 nNextTime = GetTime() + GetRand(30 * 60);
991 // Only do it if there's been a new block since last time
992 static int64 nLastTime;
993 if (nTimeBestReceived < nLastTime)
995 nLastTime = GetTime();
997 // Rebroadcast any of our txes that aren't in a block yet
998 printf("ResendWalletTransactions()\n");
1002 // Sort them in chronological order
1003 multimap<unsigned int, CWalletTx*> mapSorted;
1004 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1006 CWalletTx& wtx = item.second;
1007 // Don't rebroadcast until it's had plenty of time that
1008 // it should have gotten in already by now.
1009 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1010 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1012 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1014 CWalletTx& wtx = *item.second;
1015 if (wtx.CheckTransaction())
1016 wtx.RelayWalletTransaction(txdb);
1018 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1028 //////////////////////////////////////////////////////////////////////////////
1034 int64 CWallet::GetBalance() const
1039 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1041 const CWalletTx* pcoin = &(*it).second;
1042 if (pcoin->IsTrusted())
1043 nTotal += pcoin->GetAvailableCredit();
1050 int64 CWallet::GetWatchOnlyBalance() const
1055 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1057 const CWalletTx* pcoin = &(*it).second;
1058 if (pcoin->IsTrusted())
1059 nTotal += pcoin->GetAvailableWatchCredit();
1066 int64 CWallet::GetUnconfirmedBalance() const
1071 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1073 const CWalletTx* pcoin = &(*it).second;
1074 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1075 nTotal += pcoin->GetAvailableCredit();
1081 int64 CWallet::GetUnconfirmedWatchOnlyBalance() const
1086 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1088 const CWalletTx* pcoin = &(*it).second;
1089 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1090 nTotal += pcoin->GetAvailableWatchCredit();
1096 int64 CWallet::GetImmatureBalance() const
1101 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1103 const CWalletTx* pcoin = &(*it).second;
1104 nTotal += pcoin->GetImmatureCredit();
1110 int64 CWallet::GetImmatureWatchOnlyBalance() const
1115 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1117 const CWalletTx* pcoin = &(*it).second;
1118 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1124 // populate vCoins with vector of spendable COutputs
1125 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1131 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1133 const CWalletTx* pcoin = &(*it).second;
1135 if (!pcoin->IsFinal())
1138 if (fOnlyConfirmed && !pcoin->IsTrusted())
1141 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1144 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1147 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1148 isminetype mine = IsMine(pcoin->vout[i]);
1149 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1150 pcoin->vout[i].nValue >= nMinimumInputValue &&
1151 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1153 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1160 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64 nMinValue, int64 nMaxValue) const
1166 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1168 const CWalletTx* pcoin = &(*it).second;
1170 if (!pcoin->IsFinal())
1173 if(pcoin->GetDepthInMainChain() < nConf)
1176 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1177 isminetype mine = IsMine(pcoin->vout[i]);
1179 // ignore coin if it was already spent or we don't own it
1180 if (pcoin->IsSpent(i) || mine == MINE_NO)
1183 // if coin value is between required limits then add new item to vector
1184 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1185 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1191 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1192 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1194 vector<char> vfIncluded;
1196 vfBest.assign(vValue.size(), true);
1197 nBest = nTotalLower;
1199 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1201 vfIncluded.assign(vValue.size(), false);
1203 bool fReachedTarget = false;
1204 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1206 for (unsigned int i = 0; i < vValue.size(); i++)
1208 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1210 nTotal += vValue[i].first;
1211 vfIncluded[i] = true;
1212 if (nTotal >= nTargetValue)
1214 fReachedTarget = true;
1218 vfBest = vfIncluded;
1220 nTotal -= vValue[i].first;
1221 vfIncluded[i] = false;
1229 int64 CWallet::GetStake() const
1233 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1235 const CWalletTx* pcoin = &(*it).second;
1236 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1237 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1242 int64 CWallet::GetWatchOnlyStake() const
1246 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1248 const CWalletTx* pcoin = &(*it).second;
1249 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1250 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1255 int64 CWallet::GetNewMint() const
1259 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1261 const CWalletTx* pcoin = &(*it).second;
1262 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1263 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1268 int64 CWallet::GetWatchOnlyNewMint() const
1272 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1274 const CWalletTx* pcoin = &(*it).second;
1275 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1276 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1281 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1283 setCoinsRet.clear();
1286 // List of values less than target
1287 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1288 coinLowestLarger.first = std::numeric_limits<int64>::max();
1289 coinLowestLarger.second.first = NULL;
1290 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1291 int64 nTotalLower = 0;
1293 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1295 BOOST_FOREACH(const COutput &output, vCoins)
1297 if (!output.fSpendable)
1300 const CWalletTx *pcoin = output.tx;
1302 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1307 // Follow the timestamp rules
1308 if (pcoin->nTime > nSpendTime)
1311 int64 n = pcoin->vout[i].nValue;
1313 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1315 if (n == nTargetValue)
1317 setCoinsRet.insert(coin.second);
1318 nValueRet += coin.first;
1321 else if (n < nTargetValue + CENT)
1323 vValue.push_back(coin);
1326 else if (n < coinLowestLarger.first)
1328 coinLowestLarger = coin;
1332 if (nTotalLower == nTargetValue)
1334 for (unsigned int i = 0; i < vValue.size(); ++i)
1336 setCoinsRet.insert(vValue[i].second);
1337 nValueRet += vValue[i].first;
1342 if (nTotalLower < nTargetValue)
1344 if (coinLowestLarger.second.first == NULL)
1346 setCoinsRet.insert(coinLowestLarger.second);
1347 nValueRet += coinLowestLarger.first;
1351 // Solve subset sum by stochastic approximation
1352 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1353 vector<char> vfBest;
1356 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1357 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1358 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1360 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1361 // or the next bigger coin is closer), return the bigger coin
1362 if (coinLowestLarger.second.first &&
1363 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1365 setCoinsRet.insert(coinLowestLarger.second);
1366 nValueRet += coinLowestLarger.first;
1369 for (unsigned int i = 0; i < vValue.size(); i++)
1372 setCoinsRet.insert(vValue[i].second);
1373 nValueRet += vValue[i].first;
1376 if (fDebug && GetBoolArg("-printpriority"))
1379 printf("SelectCoins() best subset: ");
1380 for (unsigned int i = 0; i < vValue.size(); i++)
1382 printf("%s ", FormatMoney(vValue[i].first).c_str());
1383 printf("total %s\n", FormatMoney(nBest).c_str());
1390 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1392 vector<COutput> vCoins;
1393 AvailableCoins(vCoins, true, coinControl);
1395 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1396 if (coinControl && coinControl->HasSelected())
1398 BOOST_FOREACH(const COutput& out, vCoins)
1402 nValueRet += out.tx->vout[out.i].nValue;
1403 setCoinsRet.insert(make_pair(out.tx, out.i));
1405 return (nValueRet >= nTargetValue);
1408 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1409 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1410 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1413 // Select some coins without random shuffle or best subset approximation
1414 bool CWallet::SelectCoinsSimple(int64 nTargetValue, int64 nMinValue, int64 nMaxValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1416 vector<COutput> vCoins;
1417 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1419 setCoinsRet.clear();
1422 BOOST_FOREACH(COutput output, vCoins)
1424 if(!output.fSpendable)
1426 const CWalletTx *pcoin = output.tx;
1429 // Ignore immature coins
1430 if (pcoin->GetBlocksToMaturity() > 0)
1433 // Stop if we've chosen enough inputs
1434 if (nValueRet >= nTargetValue)
1437 // Follow the timestamp rules
1438 if (pcoin->nTime > nSpendTime)
1441 int64 n = pcoin->vout[i].nValue;
1443 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1445 if (n >= nTargetValue)
1447 // If input value is greater or equal to target then simply insert
1448 // it into the current subset and exit
1449 setCoinsRet.insert(coin.second);
1450 nValueRet += coin.first;
1453 else if (n < nTargetValue + CENT)
1455 setCoinsRet.insert(coin.second);
1456 nValueRet += coin.first;
1463 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1466 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1472 if (vecSend.empty() || nValue < 0)
1475 wtxNew.BindWallet(this);
1478 LOCK2(cs_main, cs_wallet);
1479 // txdb must be opened before the mapWallet lock
1482 nFeeRet = nTransactionFee;
1486 wtxNew.vout.clear();
1487 wtxNew.fFromMe = true;
1489 int64 nTotalValue = nValue + nFeeRet;
1490 double dPriority = 0;
1491 // vouts to the payees
1492 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1493 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1495 // Choose coins to use
1496 set<pair<const CWalletTx*,unsigned int> > setCoins;
1498 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1500 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1502 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1503 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1506 int64 nChange = nValueIn - nValue - nFeeRet;
1507 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1508 // or until nChange becomes zero
1509 // NOTE: this depends on the exact behaviour of GetMinFee
1510 if (wtxNew.nTime < FEE_SWITCH_TIME && !fTestNet)
1512 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1514 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1515 nChange -= nMoveToFee;
1516 nFeeRet += nMoveToFee;
1519 // sub-cent change is moved to fee
1520 if (nChange > 0 && nChange < CENT)
1529 // Fill a vout to ourself
1530 // TODO: pass in scriptChange instead of reservekey so
1531 // change transaction isn't always pay-to-bitcoin-address
1532 CScript scriptChange;
1534 // coin control: send change to custom address
1535 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1536 scriptChange.SetDestination(coinControl->destChange);
1538 // no coin control: send change to newly generated address
1541 // Note: We use a new key here to keep it from being obvious which side is the change.
1542 // The drawback is that by not reusing a previous key, the change may be lost if a
1543 // backup is restored, if the backup doesn't have the new private key for the change.
1544 // If we reused the old key, it would be possible to add code to look for and
1545 // rediscover unknown transactions that were written with keys of ours to recover
1546 // post-backup change.
1548 // Reserve a new key pair from key pool
1549 CPubKey vchPubKey = reservekey.GetReservedKey();
1551 scriptChange.SetDestination(vchPubKey.GetID());
1554 // Insert change txn at random position:
1555 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1556 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1559 reservekey.ReturnKey();
1562 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1563 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1567 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1568 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1572 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1573 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1575 dPriority /= nBytes;
1577 // Check that enough fee is included
1578 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1579 bool fAllowFree = CTransaction::AllowFree(dPriority);
1581 // Disable free transactions until 1 July 2014
1582 if (!fTestNet && wtxNew.nTime < FEE_SWITCH_TIME)
1587 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1589 if (nFeeRet < max(nPayFee, nMinFee))
1591 nFeeRet = max(nPayFee, nMinFee);
1595 // Fill vtxPrev by copying from previous transactions vtxPrev
1596 wtxNew.AddSupportingTransactions(txdb);
1597 wtxNew.fTimeReceivedIsTxTime = true;
1606 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1608 vector< pair<CScript, int64> > vecSend;
1609 vecSend.push_back(make_pair(scriptPubKey, nValue));
1610 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1613 void CWallet::GetStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
1615 int64 nTimeWeight = GetWeight(nTime, (int64)GetTime());
1617 // If time weight is lower or equal to zero then weight is zero.
1618 if (nTimeWeight <= 0)
1624 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1625 nWeight = bnCoinDayWeight.getuint64();
1629 // NovaCoin: get current stake weight
1630 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1632 // Choose coins to use
1633 int64 nBalance = GetBalance();
1634 int64 nReserveBalance = 0;
1636 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1637 return error("CreateCoinStake : invalid reserve balance amount");
1639 if (nBalance <= nReserveBalance)
1644 LOCK2(cs_main, cs_wallet);
1645 // Cache outputs unless best block or wallet transaction set changed
1646 if (!fCoinsDataActual)
1651 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, GetAdjustedTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1654 if (setCoins.empty())
1660 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1662 // Load transaction index item
1663 if (!txdb.ReadTxIndex(pcoin->first->GetHash(), txindex))
1666 // Read block header
1667 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1670 uint64 nStakeModifier = 0;
1671 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
1675 // (txid, vout.n) => ((txindex, (tx, vout.n)), (block, modifier))
1676 mapMeta[make_pair(pcoin->first->GetHash(), pcoin->second)] = make_pair(make_pair(txindex, *pcoin), make_pair(block, nStakeModifier));
1679 printf("Load coin: %s\n", pcoin->first->GetHash().GetHex().c_str());
1684 printf("Get stake weight: %d meta items loaded for %d coins\n", mapMeta.size(), setCoins.size());
1686 fCoinsDataActual = true;
1691 // (txid, vout.n) => ((txindex, (tx, vout.n)), (block, modifier))
1692 for(MetaMap::const_iterator meta_item = mapMeta.begin(); meta_item != mapMeta.end(); meta_item++)
1695 CoinsSet::value_type pcoin = meta_item->second.first.second;
1697 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1698 CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1700 // Weight is greater than zero
1701 if (nTimeWeight > 0)
1703 nWeight += bnCoinDayWeight.getuint64();
1706 // Weight is greater than zero, but the maximum value isn't reached yet
1707 if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1709 nMinWeight += bnCoinDayWeight.getuint64();
1712 // Maximum weight was reached
1713 if (nTimeWeight == nStakeMaxAge)
1715 nMaxWeight += bnCoinDayWeight.getuint64();
1722 bool CWallet::MergeCoins(const int64& nAmount, const int64& nMinValue, const int64& nOutputValue, list<uint256>& listMerged)
1724 int64 nBalance = GetBalance();
1726 if (nAmount > nBalance)
1731 set<pair<const CWalletTx*,unsigned int> > setCoins;
1733 // Simple coins selection - no randomization
1734 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
1737 if (setCoins.empty())
1741 vector<const CWalletTx*> vwtxPrev;
1743 // Reserve a new key pair from key pool
1744 CReserveKey reservekey(this);
1745 CPubKey vchPubKey = reservekey.GetReservedKey();
1748 CScript scriptOutput;
1749 scriptOutput.SetDestination(vchPubKey.GetID());
1752 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1755 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1757 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1759 // Add current coin to inputs list and add its credit to transaction output
1760 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1761 wtxNew.vout[0].nValue += nCredit;
1762 vwtxPrev.push_back(pcoin.first);
1765 // Replaced with estimation for performance purposes
1767 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1768 const CWalletTx *txin = vwtxPrev[i];
1770 // Sign scripts to get actual transaction size for fee calculation
1771 if (!SignSignature(*this, *txin, wtxNew, i))
1776 // Assuming that average scriptsig size is 110 bytes
1777 int64 nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1778 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1780 double dFinalPriority = dWeight /= nBytes;
1781 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1783 // Get actual transaction fee according to its estimated size and priority
1784 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1786 // Prepare transaction for commit if sum is enough ot its size is too big
1787 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1789 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1791 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1792 const CWalletTx *txin = vwtxPrev[i];
1795 if (!SignSignature(*this, *txin, wtxNew, i))
1799 // Try to commit, return false on failure
1800 if (!CommitTransaction(wtxNew, reservekey))
1803 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1805 dWeight = 0; // Reset all temporary values
1808 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1812 // Create transactions if there are some unhandled coins left
1813 if (wtxNew.vout[0].nValue > 0) {
1814 int64 nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1816 double dFinalPriority = dWeight /= nBytes;
1817 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1819 // Get actual transaction fee according to its size and priority
1820 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1822 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1824 if (wtxNew.vout[0].nValue <= 0)
1827 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1828 const CWalletTx *txin = vwtxPrev[i];
1830 // Sign all scripts again
1831 if (!SignSignature(*this, *txin, wtxNew, i))
1835 // Try to commit, return false on failure
1836 if (!CommitTransaction(wtxNew, reservekey))
1839 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1846 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1848 // The following combine threshold is important to security
1849 // Should not be adjusted if you don't understand the consequences
1850 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1852 CBigNum bnTargetPerCoinDay;
1853 bnTargetPerCoinDay.SetCompact(nBits);
1858 // Mark coin stake transaction
1859 CScript scriptEmpty;
1860 scriptEmpty.clear();
1861 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1863 // Choose coins to use
1864 int64 nBalance = GetBalance();
1865 int64 nReserveBalance = 0;
1867 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1868 return error("CreateCoinStake : invalid reserve balance amount");
1870 if (nBalance <= nReserveBalance)
1873 vector<const CWalletTx*> vwtxPrev;
1877 LOCK2(cs_main, cs_wallet);
1878 // Cache outputs unless best block or wallet transaction set changed
1879 if (!fCoinsDataActual)
1884 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1887 if (setCoins.empty())
1893 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1895 // Load transaction index item
1896 if (!txdb.ReadTxIndex(pcoin->first->GetHash(), txindex))
1899 // Read block header
1900 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1903 uint64 nStakeModifier = 0;
1904 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
1908 // txid => ((txindex, (tx, vout.n)), (block, modifier))
1909 mapMeta[make_pair(pcoin->first->GetHash(), pcoin->second)] = make_pair(make_pair(txindex, *pcoin), make_pair(block, nStakeModifier));
1912 printf("Load coin: %s\n", pcoin->first->GetHash().GetHex().c_str());
1917 printf("Stake miner: %d meta items loaded for %d coins\n", mapMeta.size(), setCoins.size());
1919 fCoinsDataActual = true;
1924 CScript scriptPubKeyKernel;
1926 KernelSearchSettings settings;
1927 settings.nBits = nBits;
1928 settings.nTime = txNew.nTime;
1929 settings.nOffset = 0;
1930 settings.nLimit = mapMeta.size();
1931 settings.nSearchInterval = nSearchInterval;
1933 unsigned int nTimeTx, nBlockTime;
1934 COutPoint prevoutStake;
1935 CoinsSet::value_type kernelcoin;
1937 if (ScanForStakeKernelHash(mapMeta, settings, kernelcoin, nTimeTx, nBlockTime))
1940 if (fDebug && GetBoolArg("-printcoinstake"))
1941 printf("CreateCoinStake : kernel found\n");
1942 vector<valtype> vSolutions;
1943 txnouttype whichType;
1944 CScript scriptPubKeyOut;
1945 scriptPubKeyKernel = kernelcoin.first->vout[kernelcoin.second].scriptPubKey;
1946 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1948 if (fDebug && GetBoolArg("-printcoinstake"))
1949 printf("CreateCoinStake : failed to parse kernel\n");
1952 if (fDebug && GetBoolArg("-printcoinstake"))
1953 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1954 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1956 if (fDebug && GetBoolArg("-printcoinstake"))
1957 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1958 return false; // only support pay to public key and pay to address
1960 if (whichType == TX_PUBKEYHASH) // pay to address type
1962 // convert to pay to public key type
1963 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1965 if (fDebug && GetBoolArg("-printcoinstake"))
1966 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1967 return false; // unable to find corresponding public key
1969 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1971 if (whichType == TX_PUBKEY)
1973 valtype& vchPubKey = vSolutions[0];
1974 if (!keystore.GetKey(Hash160(vchPubKey), key))
1976 if (fDebug && GetBoolArg("-printcoinstake"))
1977 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1978 return false; // unable to find corresponding public key
1980 if (key.GetPubKey() != vchPubKey)
1982 if (fDebug && GetBoolArg("-printcoinstake"))
1983 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1984 return false; // keys mismatch
1987 scriptPubKeyOut = scriptPubKeyKernel;
1990 txNew.nTime = nTimeTx;
1991 txNew.vin.push_back(CTxIn(kernelcoin.first->GetHash(), kernelcoin.second));
1992 nCredit += kernelcoin.first->vout[kernelcoin.second].nValue;
1993 vwtxPrev.push_back(kernelcoin.first);
1994 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1996 if (GetWeight((int64)nBlockTime, (int64)txNew.nTime) < nStakeMaxAge)
1997 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1998 if (fDebug && GetBoolArg("-printcoinstake"))
1999 printf("CreateCoinStake : added kernel type=%d\n", whichType);
2002 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
2005 // (txid, vout.n) => ((txindex, (tx, vout.n)), (block, modifier))
2006 for(MetaMap::const_iterator meta_item = mapMeta.begin(); meta_item != mapMeta.end(); meta_item++)
2009 CoinsSet::value_type pcoin = meta_item->second.first.second;
2011 // Attempt to add more inputs
2012 // Only add coins of the same key/address as kernel
2013 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
2014 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
2016 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
2018 // Stop adding more inputs if already too many inputs
2019 if (txNew.vin.size() >= 100)
2021 // Stop adding more inputs if value is already pretty significant
2022 if (nCredit > nCombineThreshold)
2024 // Stop adding inputs if reached reserve limit
2025 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
2027 // Do not add additional significant input
2028 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
2030 // Do not add input that is still too young
2031 if (nTimeWeight < nStakeMaxAge)
2034 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
2035 nCredit += pcoin.first->vout[pcoin.second].nValue;
2036 vwtxPrev.push_back(pcoin.first);
2040 // Calculate coin age reward
2044 if (!txNew.GetCoinAge(txdb, nCoinAge))
2045 return error("CreateCoinStake : failed to calculate coin age");
2046 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
2052 // Set output amount
2053 if (txNew.vout.size() == 3)
2055 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2056 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2059 txNew.vout[1].nValue = nCredit - nMinFee;
2063 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2065 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2066 return error("CreateCoinStake : failed to sign coinstake");
2070 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2071 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2072 return error("CreateCoinStake : exceeded coinstake size limit");
2074 // Check enough fee is paid
2075 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2077 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2078 continue; // try signing again
2082 if (fDebug && GetBoolArg("-printfee"))
2083 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2088 // Successfully generated coinstake
2093 // Call after CreateTransaction unless you want to abort
2094 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2097 LOCK2(cs_main, cs_wallet);
2098 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2100 // This is only to keep the database open to defeat the auto-flush for the
2101 // duration of this scope. This is the only place where this optimization
2102 // maybe makes sense; please don't do it anywhere else.
2103 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2105 // Take key pair from key pool so it won't be used again
2106 reservekey.KeepKey();
2108 // Add tx to wallet, because if it has change it's also ours,
2109 // otherwise just for transaction history.
2110 AddToWallet(wtxNew);
2112 // Mark old coins as spent
2113 set<CWalletTx*> setCoins;
2114 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2116 CWalletTx &coin = mapWallet[txin.prevout.hash];
2117 coin.BindWallet(this);
2118 coin.MarkSpent(txin.prevout.n);
2120 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2121 vMintingWalletUpdated.push_back(coin.GetHash());
2128 // Track how many getdata requests our transaction gets
2129 mapRequestCount[wtxNew.GetHash()] = 0;
2132 if (!wtxNew.AcceptToMemoryPool())
2134 // This must not fail. The transaction has already been signed and recorded.
2135 printf("CommitTransaction() : Error: Transaction not valid");
2138 wtxNew.RelayWalletTransaction();
2146 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
2148 CReserveKey reservekey(this);
2153 string strError = _("Error: Wallet locked, unable to create transaction ");
2154 printf("SendMoney() : %s", strError.c_str());
2157 if (fWalletUnlockMintOnly)
2159 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2160 printf("SendMoney() : %s", strError.c_str());
2163 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2166 if (nValue + nFeeRequired > GetBalance())
2167 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());
2169 strError = _("Error: Transaction creation failed ");
2170 printf("SendMoney() : %s", strError.c_str());
2174 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2177 if (!CommitTransaction(wtxNew, reservekey))
2178 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.");
2185 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
2189 return _("Invalid amount");
2190 if (nValue + nTransactionFee > GetBalance())
2191 return _("Insufficient funds");
2193 // Parse Bitcoin address
2194 CScript scriptPubKey;
2195 scriptPubKey.SetDestination(address);
2197 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2203 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2207 fFirstRunRet = false;
2208 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2209 if (nLoadWalletRet == DB_NEED_REWRITE)
2211 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2214 // Note: can't top-up keypool here, because wallet is locked.
2215 // User will be prompted to unlock wallet the next operation
2216 // the requires a new key.
2220 if (nLoadWalletRet != DB_LOAD_OK)
2221 return nLoadWalletRet;
2222 fFirstRunRet = !vchDefaultKey.IsValid();
2224 NewThread(ThreadFlushWalletDB, &strWalletFile);
2229 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2231 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2232 mapAddressBook[address] = strName;
2233 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2236 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2239 bool CWallet::DelAddressBookName(const CTxDestination& address)
2241 mapAddressBook.erase(address);
2242 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2245 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2249 void CWallet::PrintWallet(const CBlock& block)
2253 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
2255 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2256 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2258 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2260 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2261 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2268 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2272 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2273 if (mi != mapWallet.end())
2282 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2286 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2289 vchDefaultKey = vchPubKey;
2293 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2295 if (!pwallet->fFileBacked)
2297 strWalletFileOut = pwallet->strWalletFile;
2302 // Mark old keypool keys as used,
2303 // and generate all new keys
2305 bool CWallet::NewKeyPool()
2309 CWalletDB walletdb(strWalletFile);
2310 BOOST_FOREACH(int64 nIndex, setKeyPool)
2311 walletdb.ErasePool(nIndex);
2317 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2318 for (int i = 0; i < nKeys; i++)
2321 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2322 setKeyPool.insert(nIndex);
2324 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2329 bool CWallet::TopUpKeyPool(unsigned int nSize)
2337 CWalletDB walletdb(strWalletFile);
2340 unsigned int nTargetSize;
2342 nTargetSize = nSize;
2344 nTargetSize = max(GetArg("-keypool", 100), 0LL);
2346 while (setKeyPool.size() < (nTargetSize + 1))
2349 if (!setKeyPool.empty())
2350 nEnd = *(--setKeyPool.end()) + 1;
2351 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2352 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2353 setKeyPool.insert(nEnd);
2354 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2360 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2363 keypool.vchPubKey = CPubKey();
2370 // Get the oldest key
2371 if(setKeyPool.empty())
2374 CWalletDB walletdb(strWalletFile);
2376 nIndex = *(setKeyPool.begin());
2377 setKeyPool.erase(setKeyPool.begin());
2378 if (!walletdb.ReadPool(nIndex, keypool))
2379 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2380 if (!HaveKey(keypool.vchPubKey.GetID()))
2381 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2382 assert(keypool.vchPubKey.IsValid());
2383 if (fDebug && GetBoolArg("-printkeypool"))
2384 printf("keypool reserve %"PRI64d"\n", nIndex);
2388 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2391 LOCK2(cs_main, cs_wallet);
2392 CWalletDB walletdb(strWalletFile);
2394 int64 nIndex = 1 + *(--setKeyPool.end());
2395 if (!walletdb.WritePool(nIndex, keypool))
2396 throw runtime_error("AddReserveKey() : writing added key failed");
2397 setKeyPool.insert(nIndex);
2403 void CWallet::KeepKey(int64 nIndex)
2405 // Remove from key pool
2408 CWalletDB walletdb(strWalletFile);
2409 walletdb.ErasePool(nIndex);
2412 printf("keypool keep %"PRI64d"\n", nIndex);
2415 void CWallet::ReturnKey(int64 nIndex)
2417 // Return to key pool
2420 setKeyPool.insert(nIndex);
2423 printf("keypool return %"PRI64d"\n", nIndex);
2426 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2432 ReserveKeyFromKeyPool(nIndex, keypool);
2435 if (fAllowReuse && vchDefaultKey.IsValid())
2437 result = vchDefaultKey;
2440 if (IsLocked()) return false;
2441 result = GenerateNewKey();
2445 result = keypool.vchPubKey;
2450 int64 CWallet::GetOldestKeyPoolTime()
2454 ReserveKeyFromKeyPool(nIndex, keypool);
2458 return keypool.nTime;
2461 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2463 map<CTxDestination, int64> balances;
2467 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2469 CWalletTx *pcoin = &walletEntry.second;
2471 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2474 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2477 int nDepth = pcoin->GetDepthInMainChain();
2478 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2481 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2483 CTxDestination addr;
2484 if (!IsMine(pcoin->vout[i]))
2486 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2489 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2491 if (!balances.count(addr))
2493 balances[addr] += n;
2501 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2503 set< set<CTxDestination> > groupings;
2504 set<CTxDestination> grouping;
2506 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2508 CWalletTx *pcoin = &walletEntry.second;
2510 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2512 // group all input addresses with each other
2513 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2515 CTxDestination address;
2516 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2518 grouping.insert(address);
2521 // group change with input addresses
2522 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2523 if (IsChange(txout))
2525 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2526 CTxDestination txoutAddr;
2527 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2529 grouping.insert(txoutAddr);
2531 groupings.insert(grouping);
2535 // group lone addrs by themselves
2536 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2537 if (IsMine(pcoin->vout[i]))
2539 CTxDestination address;
2540 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2542 grouping.insert(address);
2543 groupings.insert(grouping);
2548 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2549 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2550 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2552 // make a set of all the groups hit by this new group
2553 set< set<CTxDestination>* > hits;
2554 map< CTxDestination, set<CTxDestination>* >::iterator it;
2555 BOOST_FOREACH(CTxDestination address, grouping)
2556 if ((it = setmap.find(address)) != setmap.end())
2557 hits.insert((*it).second);
2559 // merge all hit groups into a new single group and delete old groups
2560 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2561 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2563 merged->insert(hit->begin(), hit->end());
2564 uniqueGroupings.erase(hit);
2567 uniqueGroupings.insert(merged);
2570 BOOST_FOREACH(CTxDestination element, *merged)
2571 setmap[element] = merged;
2574 set< set<CTxDestination> > ret;
2575 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2577 ret.insert(*uniqueGrouping);
2578 delete uniqueGrouping;
2584 // ppcoin: check 'spent' consistency between wallet and txindex
2585 // ppcoin: fix wallet spent state according to txindex
2586 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2589 nBalanceInQuestion = 0;
2592 vector<CWalletTx*> vCoins;
2593 vCoins.reserve(mapWallet.size());
2594 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2595 vCoins.push_back(&(*it).second);
2598 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2600 // Find the corresponding transaction index
2602 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2604 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2606 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2608 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2609 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2611 nBalanceInQuestion += pcoin->vout[n].nValue;
2614 pcoin->MarkUnspent(n);
2615 pcoin->WriteToDisk();
2618 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2620 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2621 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2623 nBalanceInQuestion += pcoin->vout[n].nValue;
2626 pcoin->MarkSpent(n);
2627 pcoin->WriteToDisk();
2633 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2635 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2638 EraseFromWallet(pcoin->GetHash());
2644 // ppcoin: disable transaction (only for coinstake)
2645 void CWallet::DisableTransaction(const CTransaction &tx)
2647 if (!tx.IsCoinStake() || !IsFromMe(tx))
2648 return; // only disconnecting coinstake requires marking input unspent
2651 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2653 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2654 if (mi != mapWallet.end())
2656 CWalletTx& prev = (*mi).second;
2657 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2659 prev.MarkUnspent(txin.prevout.n);
2666 CPubKey CReserveKey::GetReservedKey()
2671 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2673 vchPubKey = keypool.vchPubKey;
2676 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2677 vchPubKey = pwallet->vchDefaultKey;
2680 assert(vchPubKey.IsValid());
2684 void CReserveKey::KeepKey()
2687 pwallet->KeepKey(nIndex);
2689 vchPubKey = CPubKey();
2692 void CReserveKey::ReturnKey()
2695 pwallet->ReturnKey(nIndex);
2697 vchPubKey = CPubKey();
2700 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2704 CWalletDB walletdb(strWalletFile);
2706 LOCK2(cs_main, cs_wallet);
2707 BOOST_FOREACH(const int64& id, setKeyPool)
2710 if (!walletdb.ReadPool(id, keypool))
2711 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2712 assert(keypool.vchPubKey.IsValid());
2713 CKeyID keyID = keypool.vchPubKey.GetID();
2714 if (!HaveKey(keyID))
2715 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2716 setAddress.insert(keyID);
2720 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2724 // Only notify UI if this transaction is in this wallet
2725 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2726 if (mi != mapWallet.end())
2728 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2729 vMintingWalletUpdated.push_back(hashTx);
2734 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2735 mapKeyBirth.clear();
2737 // get birth times for keys with metadata
2738 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2739 if (it->second.nCreateTime)
2740 mapKeyBirth[it->first] = it->second.nCreateTime;
2742 // map in which we'll infer heights of other keys
2743 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2744 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2745 std::set<CKeyID> setKeys;
2747 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2748 if (mapKeyBirth.count(keyid) == 0)
2749 mapKeyFirstBlock[keyid] = pindexMax;
2753 // if there are no such keys, we're done
2754 if (mapKeyFirstBlock.empty())
2757 // find first block that affects those keys, if there are any left
2758 std::vector<CKeyID> vAffected;
2759 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2760 // iterate over all wallet transactions...
2761 const CWalletTx &wtx = (*it).second;
2762 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2763 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2764 // ... which are already in a block
2765 int nHeight = blit->second->nHeight;
2766 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2767 // iterate over all their outputs
2768 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2769 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2770 // ... and all their affected keys
2771 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2772 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2773 rit->second = blit->second;
2780 // Extract block timestamps for those keys
2781 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2782 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2785 void CWallet::ClearOrphans()
2787 list<uint256> orphans;
2790 for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2792 const CWalletTx *wtx = &(*it).second;
2793 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
2795 orphans.push_back(wtx->GetHash());
2799 for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
2800 EraseFromWallet(*it);