1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
10 #include "ui_interface.h"
13 #include "coincontrol.h"
14 #include <boost/algorithm/string/replace.hpp>
21 bool fCoinsDataActual;
23 //////////////////////////////////////////////////////////////////////////////
28 struct CompareValueOnly
30 bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1,
31 const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const
33 return t1.first < t2.first;
37 CPubKey CWallet::GenerateNewKey()
39 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
43 key.MakeNewKey(fCompressed);
45 // Compressed public keys were introduced in version 0.6.0
47 SetMinVersion(FEATURE_COMPRPUBKEY);
49 CPubKey pubkey = key.GetPubKey();
51 // Create new metadata
52 int64_t nCreationTime = GetTime();
53 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
54 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
55 nTimeFirstKey = nCreationTime;
58 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
59 return key.GetPubKey();
62 bool CWallet::AddKey(const CKey& key)
64 CPubKey pubkey = key.GetPubKey();
66 if (!CCryptoKeyStore::AddKey(key))
71 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
75 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
77 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
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_t 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_t 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_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
342 int64_t 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_t 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_t 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_t CWalletTx::GetTxTime() const
654 int CWalletTx::GetRequestCount() const
656 // Returns -1 if it wasn't being tracked
659 LOCK(pwallet->cs_wallet);
660 if (IsCoinBase() || IsCoinStake())
665 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
666 if (mi != pwallet->mapRequestCount.end())
667 nRequests = (*mi).second;
672 // Did anyone request this transaction?
673 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
674 if (mi != pwallet->mapRequestCount.end())
676 nRequests = (*mi).second;
678 // How about the block it's in?
679 if (nRequests == 0 && hashBlock != 0)
681 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
682 if (mi != pwallet->mapRequestCount.end())
683 nRequests = (*mi).second;
685 nRequests = 1; // If it's in someone else's block it must have got out
693 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CTxDestination, int64_t> >& listReceived,
694 list<pair<CTxDestination, int64_t> >& listSent, int64_t& nFee, string& strSentAccount, const isminefilter& filter) const
696 nGeneratedImmature = nGeneratedMature = nFee = 0;
697 listReceived.clear();
699 strSentAccount = strFromAccount;
701 if (IsCoinBase() || IsCoinStake())
703 if (GetBlocksToMaturity() > 0)
704 nGeneratedImmature = pwallet->GetCredit(*this, filter);
706 nGeneratedMature = GetCredit(filter);
711 int64_t nDebit = GetDebit(filter);
712 if (nDebit > 0) // debit>0 means we signed/sent this transaction
714 int64_t nValueOut = GetValueOut();
715 nFee = nDebit - nValueOut;
719 BOOST_FOREACH(const CTxOut& txout, vout)
721 isminetype fIsMine = pwallet->IsMine(txout);
722 // Only need to handle txouts if AT LEAST one of these is true:
723 // 1) they debit from us (sent)
724 // 2) the output is to us (received)
727 // Don't report 'change' txouts
728 if (pwallet->IsChange(txout))
731 else if (!(fIsMine & filter))
734 // In either case, we need to get the destination address
735 CTxDestination address;
736 if (!ExtractDestination(txout.scriptPubKey, address))
738 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
739 this->GetHash().ToString().c_str());
740 address = CNoDestination();
743 // If we are debited by the transaction, add the output as a "sent" entry
745 listSent.push_back(make_pair(address, txout.nValue));
747 // If we are receiving the output, add it as a "received" entry
748 if (fIsMine & filter)
749 listReceived.push_back(make_pair(address, txout.nValue));
754 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
755 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const
757 nGenerated = nReceived = nSent = nFee = 0;
759 int64_t allGeneratedImmature, allGeneratedMature, allFee;
760 allGeneratedImmature = allGeneratedMature = allFee = 0;
761 string strSentAccount;
762 list<pair<CTxDestination, int64_t> > listReceived;
763 list<pair<CTxDestination, int64_t> > listSent;
764 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
766 if (strAccount == "")
767 nGenerated = allGeneratedMature;
768 if (strAccount == strSentAccount)
770 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& s, listSent)
775 LOCK(pwallet->cs_wallet);
776 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived)
778 if (pwallet->mapAddressBook.count(r.first))
780 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
781 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
782 nReceived += r.second;
784 else if (strAccount.empty())
786 nReceived += r.second;
792 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
796 const int COPY_DEPTH = 3;
797 if (SetMerkleBranch() < COPY_DEPTH)
799 vector<uint256> vWorkQueue;
800 BOOST_FOREACH(const CTxIn& txin, vin)
801 vWorkQueue.push_back(txin.prevout.hash);
803 // This critsect is OK because txdb is already open
805 LOCK(pwallet->cs_wallet);
806 map<uint256, const CMerkleTx*> mapWalletPrev;
807 set<uint256> setAlreadyDone;
808 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
810 uint256 hash = vWorkQueue[i];
811 if (setAlreadyDone.count(hash))
813 setAlreadyDone.insert(hash);
816 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
817 if (mi != pwallet->mapWallet.end())
820 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
821 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
823 else if (mapWalletPrev.count(hash))
825 tx = *mapWalletPrev[hash];
827 else if (!fClient && txdb.ReadDiskTx(hash, tx))
833 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
837 int nDepth = tx.SetMerkleBranch();
838 vtxPrev.push_back(tx);
840 if (nDepth < COPY_DEPTH)
842 BOOST_FOREACH(const CTxIn& txin, tx.vin)
843 vWorkQueue.push_back(txin.prevout.hash);
849 reverse(vtxPrev.begin(), vtxPrev.end());
852 bool CWalletTx::WriteToDisk()
854 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
857 // Scan the block chain (starting in pindexStart) for transactions
858 // from or to us. If fUpdate is true, found transactions that already
859 // exist in the wallet will be updated.
860 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
864 CBlockIndex* pindex = pindexStart;
870 block.ReadFromDisk(pindex, true);
871 BOOST_FOREACH(CTransaction& tx, block.vtx)
873 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
876 pindex = pindex->pnext;
882 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
885 tx.ReadFromDisk(COutPoint(hashTx, 0));
886 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
891 void CWallet::ReacceptWalletTransactions()
899 vector<CDiskTxPos> vMissingTx;
900 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
902 CWalletTx& wtx = item.second;
903 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
907 bool fUpdated = false;
908 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
910 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
911 if (txindex.vSpent.size() != wtx.vout.size())
913 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
916 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
920 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
924 vMissingTx.push_back(txindex.vSpent[i]);
929 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
936 // Re-accept any txes of ours that aren't already in a block
937 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
938 wtx.AcceptWalletTransaction(txdb, false);
941 if (!vMissingTx.empty())
943 // TODO: optimize this to scan just part of the block chain?
944 if (ScanForWalletTransactions(pindexGenesisBlock))
945 fRepeat = true; // Found missing transactions: re-do re-accept.
950 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
952 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
954 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
956 uint256 hash = tx.GetHash();
957 if (!txdb.ContainsTx(hash))
958 RelayTransaction((CTransaction)tx, hash);
961 if (!(IsCoinBase() || IsCoinStake()))
963 uint256 hash = GetHash();
964 if (!txdb.ContainsTx(hash))
966 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
967 RelayTransaction((CTransaction)*this, hash);
972 void CWalletTx::RelayWalletTransaction()
975 RelayWalletTransaction(txdb);
978 void CWallet::ResendWalletTransactions()
980 // Do this infrequently and randomly to avoid giving away
981 // that these are our transactions.
982 static int64_t nNextTime;
983 if (GetTime() < nNextTime)
985 bool fFirst = (nNextTime == 0);
986 nNextTime = GetTime() + GetRand(30 * 60);
990 // Only do it if there's been a new block since last time
991 static int64_t nLastTime;
992 if (nTimeBestReceived < nLastTime)
994 nLastTime = GetTime();
996 // Rebroadcast any of our txes that aren't in a block yet
997 printf("ResendWalletTransactions()\n");
1001 // Sort them in chronological order
1002 multimap<unsigned int, CWalletTx*> mapSorted;
1003 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1005 CWalletTx& wtx = item.second;
1006 // Don't rebroadcast until it's had plenty of time that
1007 // it should have gotten in already by now.
1008 if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
1009 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1011 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1013 CWalletTx& wtx = *item.second;
1014 if (wtx.CheckTransaction())
1015 wtx.RelayWalletTransaction(txdb);
1017 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1027 //////////////////////////////////////////////////////////////////////////////
1033 int64_t CWallet::GetBalance() const
1038 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1040 const CWalletTx* pcoin = &(*it).second;
1041 if (pcoin->IsTrusted())
1042 nTotal += pcoin->GetAvailableCredit();
1049 int64_t CWallet::GetWatchOnlyBalance() const
1054 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1056 const CWalletTx* pcoin = &(*it).second;
1057 if (pcoin->IsTrusted())
1058 nTotal += pcoin->GetAvailableWatchCredit();
1065 int64_t CWallet::GetUnconfirmedBalance() const
1070 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1072 const CWalletTx* pcoin = &(*it).second;
1073 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1074 nTotal += pcoin->GetAvailableCredit();
1080 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1085 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1087 const CWalletTx* pcoin = &(*it).second;
1088 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1089 nTotal += pcoin->GetAvailableWatchCredit();
1095 int64_t CWallet::GetImmatureBalance() const
1100 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1102 const CWalletTx* pcoin = &(*it).second;
1103 nTotal += pcoin->GetImmatureCredit();
1109 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1114 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1116 const CWalletTx* pcoin = &(*it).second;
1117 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1123 // populate vCoins with vector of spendable COutputs
1124 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1130 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1132 const CWalletTx* pcoin = &(*it).second;
1134 if (!pcoin->IsFinal())
1137 if (fOnlyConfirmed && !pcoin->IsTrusted())
1140 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1143 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1146 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1147 isminetype mine = IsMine(pcoin->vout[i]);
1148 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1149 pcoin->vout[i].nValue >= nMinimumInputValue &&
1150 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1152 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1159 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1165 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1167 const CWalletTx* pcoin = &(*it).second;
1169 if (!pcoin->IsFinal())
1172 if(pcoin->GetDepthInMainChain() < nConf)
1175 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1176 isminetype mine = IsMine(pcoin->vout[i]);
1178 // ignore coin if it was already spent or we don't own it
1179 if (pcoin->IsSpent(i) || mine == MINE_NO)
1182 // if coin value is between required limits then add new item to vector
1183 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1184 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1190 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1191 vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1193 vector<char> vfIncluded;
1195 vfBest.assign(vValue.size(), true);
1196 nBest = nTotalLower;
1198 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1200 vfIncluded.assign(vValue.size(), false);
1202 bool fReachedTarget = false;
1203 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1205 for (unsigned int i = 0; i < vValue.size(); i++)
1207 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1209 nTotal += vValue[i].first;
1210 vfIncluded[i] = true;
1211 if (nTotal >= nTargetValue)
1213 fReachedTarget = true;
1217 vfBest = vfIncluded;
1219 nTotal -= vValue[i].first;
1220 vfIncluded[i] = false;
1228 int64_t CWallet::GetStake() const
1232 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1234 const CWalletTx* pcoin = &(*it).second;
1235 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1236 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1241 int64_t CWallet::GetWatchOnlyStake() const
1245 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1247 const CWalletTx* pcoin = &(*it).second;
1248 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1249 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1254 int64_t CWallet::GetNewMint() const
1258 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1260 const CWalletTx* pcoin = &(*it).second;
1261 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1262 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1267 int64_t CWallet::GetWatchOnlyNewMint() const
1271 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1273 const CWalletTx* pcoin = &(*it).second;
1274 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1275 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1280 bool CWallet::SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const
1282 setCoinsRet.clear();
1285 // List of values less than target
1286 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1287 coinLowestLarger.first = std::numeric_limits<int64_t>::max();
1288 coinLowestLarger.second.first = NULL;
1289 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1290 int64_t nTotalLower = 0;
1292 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1294 BOOST_FOREACH(const COutput &output, vCoins)
1296 if (!output.fSpendable)
1299 const CWalletTx *pcoin = output.tx;
1301 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1306 // Follow the timestamp rules
1307 if (pcoin->nTime > nSpendTime)
1310 int64_t n = pcoin->vout[i].nValue;
1312 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1314 if (n == nTargetValue)
1316 setCoinsRet.insert(coin.second);
1317 nValueRet += coin.first;
1320 else if (n < nTargetValue + CENT)
1322 vValue.push_back(coin);
1325 else if (n < coinLowestLarger.first)
1327 coinLowestLarger = coin;
1331 if (nTotalLower == nTargetValue)
1333 for (unsigned int i = 0; i < vValue.size(); ++i)
1335 setCoinsRet.insert(vValue[i].second);
1336 nValueRet += vValue[i].first;
1341 if (nTotalLower < nTargetValue)
1343 if (coinLowestLarger.second.first == NULL)
1345 setCoinsRet.insert(coinLowestLarger.second);
1346 nValueRet += coinLowestLarger.first;
1350 // Solve subset sum by stochastic approximation
1351 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1352 vector<char> vfBest;
1355 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1356 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1357 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1359 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1360 // or the next bigger coin is closer), return the bigger coin
1361 if (coinLowestLarger.second.first &&
1362 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1364 setCoinsRet.insert(coinLowestLarger.second);
1365 nValueRet += coinLowestLarger.first;
1368 for (unsigned int i = 0; i < vValue.size(); i++)
1371 setCoinsRet.insert(vValue[i].second);
1372 nValueRet += vValue[i].first;
1375 if (fDebug && GetBoolArg("-printpriority"))
1378 printf("SelectCoins() best subset: ");
1379 for (unsigned int i = 0; i < vValue.size(); i++)
1381 printf("%s ", FormatMoney(vValue[i].first).c_str());
1382 printf("total %s\n", FormatMoney(nBest).c_str());
1389 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
1391 vector<COutput> vCoins;
1392 AvailableCoins(vCoins, true, coinControl);
1394 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1395 if (coinControl && coinControl->HasSelected())
1397 BOOST_FOREACH(const COutput& out, vCoins)
1401 nValueRet += out.tx->vout[out.i].nValue;
1402 setCoinsRet.insert(make_pair(out.tx, out.i));
1404 return (nValueRet >= nTargetValue);
1407 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1408 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1409 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1412 // Select some coins without random shuffle or best subset approximation
1413 bool CWallet::SelectCoinsSimple(int64_t nTargetValue, int64_t nMinValue, int64_t nMaxValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet) const
1415 vector<COutput> vCoins;
1416 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1418 setCoinsRet.clear();
1421 BOOST_FOREACH(COutput output, vCoins)
1423 if(!output.fSpendable)
1425 const CWalletTx *pcoin = output.tx;
1428 // Ignore immature coins
1429 if (pcoin->GetBlocksToMaturity() > 0)
1432 // Stop if we've chosen enough inputs
1433 if (nValueRet >= nTargetValue)
1436 // Follow the timestamp rules
1437 if (pcoin->nTime > nSpendTime)
1440 int64_t n = pcoin->vout[i].nValue;
1442 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1444 if (n >= nTargetValue)
1446 // If input value is greater or equal to target then simply insert
1447 // it into the current subset and exit
1448 setCoinsRet.insert(coin.second);
1449 nValueRet += coin.first;
1452 else if (n < nTargetValue + CENT)
1454 setCoinsRet.insert(coin.second);
1455 nValueRet += coin.first;
1462 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1465 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1471 if (vecSend.empty() || nValue < 0)
1474 wtxNew.BindWallet(this);
1477 LOCK2(cs_main, cs_wallet);
1478 // txdb must be opened before the mapWallet lock
1481 nFeeRet = nTransactionFee;
1485 wtxNew.vout.clear();
1486 wtxNew.fFromMe = true;
1488 int64_t nTotalValue = nValue + nFeeRet;
1489 double dPriority = 0;
1490 // vouts to the payees
1491 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1492 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1494 // Choose coins to use
1495 set<pair<const CWalletTx*,unsigned int> > setCoins;
1496 int64_t nValueIn = 0;
1497 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1499 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1501 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1502 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1505 int64_t nChange = nValueIn - nValue - nFeeRet;
1506 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1507 // or until nChange becomes zero
1508 // NOTE: this depends on the exact behaviour of GetMinFee
1509 if (wtxNew.nTime < FEE_SWITCH_TIME && !fTestNet)
1511 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1513 int64_t nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1514 nChange -= nMoveToFee;
1515 nFeeRet += nMoveToFee;
1518 // sub-cent change is moved to fee
1519 if (nChange > 0 && nChange < CENT)
1528 // Fill a vout to ourself
1529 // TODO: pass in scriptChange instead of reservekey so
1530 // change transaction isn't always pay-to-bitcoin-address
1531 CScript scriptChange;
1533 // coin control: send change to custom address
1534 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1535 scriptChange.SetDestination(coinControl->destChange);
1537 // no coin control: send change to newly generated address
1540 // Note: We use a new key here to keep it from being obvious which side is the change.
1541 // The drawback is that by not reusing a previous key, the change may be lost if a
1542 // backup is restored, if the backup doesn't have the new private key for the change.
1543 // If we reused the old key, it would be possible to add code to look for and
1544 // rediscover unknown transactions that were written with keys of ours to recover
1545 // post-backup change.
1547 // Reserve a new key pair from key pool
1548 CPubKey vchPubKey = reservekey.GetReservedKey();
1550 scriptChange.SetDestination(vchPubKey.GetID());
1553 // Insert change txn at random position:
1554 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1555 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1558 reservekey.ReturnKey();
1561 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1562 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1566 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1567 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1571 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1572 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1574 dPriority /= nBytes;
1576 // Check that enough fee is included
1577 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
1578 bool fAllowFree = CTransaction::AllowFree(dPriority);
1580 // Disable free transactions until 1 July 2014
1581 if (!fTestNet && wtxNew.nTime < FEE_SWITCH_TIME)
1586 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1588 if (nFeeRet < max(nPayFee, nMinFee))
1590 nFeeRet = max(nPayFee, nMinFee);
1594 // Fill vtxPrev by copying from previous transactions vtxPrev
1595 wtxNew.AddSupportingTransactions(txdb);
1596 wtxNew.fTimeReceivedIsTxTime = true;
1605 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1607 vector< pair<CScript, int64_t> > vecSend;
1608 vecSend.push_back(make_pair(scriptPubKey, nValue));
1609 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1612 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
1614 int64_t nTimeWeight = GetWeight(nTime, (int64_t)GetTime());
1616 // If time weight is lower or equal to zero then weight is zero.
1617 if (nTimeWeight <= 0)
1623 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1624 nWeight = bnCoinDayWeight.getuint64();
1628 // NovaCoin: get current stake miner statistics
1629 void CWallet::GetStakeStats(float &nKernelsRate, float &nCoinDaysRate)
1631 static uint64_t nLastKernels = 0, nLastCoinDays = 0;
1632 static float nLastKernelsRate = 0, nLastCoinDaysRate = 0;
1633 static int64_t nLastTime = GetTime();
1635 if (nKernelsTried < nLastKernels)
1640 nLastTime = GetTime();
1643 int64_t nInterval = GetTime() - nLastTime;
1644 //if (nKernelsTried > 1000 && nInterval > 5)
1647 nKernelsRate = nLastKernelsRate = ( nKernelsTried - nLastKernels ) / (float) nInterval;
1648 nCoinDaysRate = nLastCoinDaysRate = ( nCoinDaysTried - nLastCoinDays ) / (float) nInterval;
1650 nLastKernels = nKernelsTried;
1651 nLastCoinDays = nCoinDaysTried;
1652 nLastTime = GetTime();
1656 nKernelsRate = nLastKernelsRate;
1657 nCoinDaysRate = nLastCoinDaysRate;
1661 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
1663 int64_t nBalance = GetBalance();
1665 if (nAmount > nBalance)
1669 int64_t nValueIn = 0;
1670 set<pair<const CWalletTx*,unsigned int> > setCoins;
1672 // Simple coins selection - no randomization
1673 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
1676 if (setCoins.empty())
1680 vector<const CWalletTx*> vwtxPrev;
1682 // Reserve a new key pair from key pool
1683 CReserveKey reservekey(this);
1684 CPubKey vchPubKey = reservekey.GetReservedKey();
1687 CScript scriptOutput;
1688 scriptOutput.SetDestination(vchPubKey.GetID());
1691 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1694 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1696 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1698 // Add current coin to inputs list and add its credit to transaction output
1699 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1700 wtxNew.vout[0].nValue += nCredit;
1701 vwtxPrev.push_back(pcoin.first);
1704 // Replaced with estimation for performance purposes
1706 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1707 const CWalletTx *txin = vwtxPrev[i];
1709 // Sign scripts to get actual transaction size for fee calculation
1710 if (!SignSignature(*this, *txin, wtxNew, i))
1715 // Assuming that average scriptsig size is 110 bytes
1716 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1717 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1719 double dFinalPriority = dWeight /= nBytes;
1720 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1722 // Get actual transaction fee according to its estimated size and priority
1723 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1725 // Prepare transaction for commit if sum is enough ot its size is too big
1726 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1728 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1730 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1731 const CWalletTx *txin = vwtxPrev[i];
1734 if (!SignSignature(*this, *txin, wtxNew, i))
1738 // Try to commit, return false on failure
1739 if (!CommitTransaction(wtxNew, reservekey))
1742 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1744 dWeight = 0; // Reset all temporary values
1747 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1751 // Create transactions if there are some unhandled coins left
1752 if (wtxNew.vout[0].nValue > 0) {
1753 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1755 double dFinalPriority = dWeight /= nBytes;
1756 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1758 // Get actual transaction fee according to its size and priority
1759 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1761 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1763 if (wtxNew.vout[0].nValue <= 0)
1766 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1767 const CWalletTx *txin = vwtxPrev[i];
1769 // Sign all scripts again
1770 if (!SignSignature(*this, *txin, wtxNew, i))
1774 // Try to commit, return false on failure
1775 if (!CommitTransaction(wtxNew, reservekey))
1778 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1785 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64_t nSearchInterval, CTransaction& txNew, CKey& key)
1787 // The following combine threshold is important to security
1788 // Should not be adjusted if you don't understand the consequences
1789 int64_t nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1791 CBigNum bnTargetPerCoinDay;
1792 bnTargetPerCoinDay.SetCompact(nBits);
1797 // Mark coin stake transaction
1798 CScript scriptEmpty;
1799 scriptEmpty.clear();
1800 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1802 // Choose coins to use
1803 int64_t nBalance = GetBalance();
1804 int64_t nReserveBalance = 0;
1806 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1807 return error("CreateCoinStake : invalid reserve balance amount");
1809 if (nBalance <= nReserveBalance)
1812 vector<const CWalletTx*> vwtxPrev;
1816 LOCK2(cs_main, cs_wallet);
1817 // Cache outputs unless best block or wallet transaction set changed
1818 if (!fCoinsDataActual)
1821 int64_t nValueIn = 0;
1823 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1826 if (setCoins.empty())
1832 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1834 // Load transaction index item
1835 if (!txdb.ReadTxIndex(pcoin->first->GetHash(), txindex))
1838 // Read block header
1839 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1842 uint64_t nStakeModifier = 0;
1843 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
1847 // txid => ((txindex, (tx, vout.n)), (block, modifier))
1848 mapMeta[make_pair(pcoin->first->GetHash(), pcoin->second)] = make_pair(make_pair(txindex, *pcoin), make_pair(block, nStakeModifier));
1851 printf("Load coin: %s\n", pcoin->first->GetHash().GetHex().c_str());
1856 printf("Stake miner: %" PRIszu " meta items loaded for %" PRIszu " coins\n", mapMeta.size(), setCoins.size());
1858 fCoinsDataActual = true;
1864 int64_t nCredit = 0;
1865 CScript scriptPubKeyKernel;
1867 KernelSearchSettings settings;
1868 settings.nBits = nBits;
1869 settings.nTime = txNew.nTime;
1870 settings.nOffset = 0;
1871 settings.nLimit = mapMeta.size();
1872 settings.nSearchInterval = nSearchInterval;
1874 unsigned int nTimeTx, nBlockTime;
1875 COutPoint prevoutStake;
1876 CoinsSet::value_type kernelcoin;
1878 if (ScanForStakeKernelHash(mapMeta, settings, kernelcoin, nTimeTx, nBlockTime, nKernelsTried, nCoinDaysTried))
1881 if (fDebug && GetBoolArg("-printcoinstake"))
1882 printf("CreateCoinStake : kernel found\n");
1883 vector<valtype> vSolutions;
1884 txnouttype whichType;
1885 CScript scriptPubKeyOut;
1886 scriptPubKeyKernel = kernelcoin.first->vout[kernelcoin.second].scriptPubKey;
1887 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1889 if (fDebug && GetBoolArg("-printcoinstake"))
1890 printf("CreateCoinStake : failed to parse kernel\n");
1893 if (fDebug && GetBoolArg("-printcoinstake"))
1894 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1895 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1897 if (fDebug && GetBoolArg("-printcoinstake"))
1898 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1899 return false; // only support pay to public key and pay to address
1901 if (whichType == TX_PUBKEYHASH) // pay to address type
1903 // convert to pay to public key type
1904 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1906 if (fDebug && GetBoolArg("-printcoinstake"))
1907 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1908 return false; // unable to find corresponding public key
1910 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1912 if (whichType == TX_PUBKEY)
1914 valtype& vchPubKey = vSolutions[0];
1915 if (!keystore.GetKey(Hash160(vchPubKey), key))
1917 if (fDebug && GetBoolArg("-printcoinstake"))
1918 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1919 return false; // unable to find corresponding public key
1921 if (key.GetPubKey() != vchPubKey)
1923 if (fDebug && GetBoolArg("-printcoinstake"))
1924 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1925 return false; // keys mismatch
1928 scriptPubKeyOut = scriptPubKeyKernel;
1931 txNew.nTime = nTimeTx;
1932 txNew.vin.push_back(CTxIn(kernelcoin.first->GetHash(), kernelcoin.second));
1933 nCredit += kernelcoin.first->vout[kernelcoin.second].nValue;
1934 vwtxPrev.push_back(kernelcoin.first);
1935 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1937 if (GetWeight((int64_t)nBlockTime, (int64_t)txNew.nTime) < nStakeMaxAge)
1938 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1939 if (fDebug && GetBoolArg("-printcoinstake"))
1940 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1943 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1946 // (txid, vout.n) => ((txindex, (tx, vout.n)), (block, modifier))
1947 for(MetaMap::const_iterator meta_item = mapMeta.begin(); meta_item != mapMeta.end(); meta_item++)
1950 CoinsSet::value_type pcoin = meta_item->second.first.second;
1952 // Attempt to add more inputs
1953 // Only add coins of the same key/address as kernel
1954 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1955 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1957 int64_t nTimeWeight = GetWeight((int64_t)pcoin.first->nTime, (int64_t)txNew.nTime);
1959 // Stop adding more inputs if already too many inputs
1960 if (txNew.vin.size() >= 100)
1962 // Stop adding more inputs if value is already pretty significant
1963 if (nCredit > nCombineThreshold)
1965 // Stop adding inputs if reached reserve limit
1966 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1968 // Do not add additional significant input
1969 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1971 // Do not add input that is still too young
1972 if (nTimeWeight < nStakeMaxAge)
1975 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1976 nCredit += pcoin.first->vout[pcoin.second].nValue;
1977 vwtxPrev.push_back(pcoin.first);
1981 // Calculate coin age reward
1985 if (!txNew.GetCoinAge(txdb, nCoinAge))
1986 return error("CreateCoinStake : failed to calculate coin age");
1988 int64_t nReward = GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1989 // Refuse to create mint that has zero or negative reward
1996 int64_t nMinFee = 0;
1999 // Set output amount
2000 if (txNew.vout.size() == 3)
2002 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2003 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2006 txNew.vout[1].nValue = nCredit - nMinFee;
2010 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2012 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2013 return error("CreateCoinStake : failed to sign coinstake");
2017 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2018 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2019 return error("CreateCoinStake : exceeded coinstake size limit");
2021 // Check enough fee is paid
2022 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2024 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2025 continue; // try signing again
2029 if (fDebug && GetBoolArg("-printfee"))
2030 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2035 // Successfully generated coinstake
2040 // Call after CreateTransaction unless you want to abort
2041 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2044 LOCK2(cs_main, cs_wallet);
2045 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2047 // This is only to keep the database open to defeat the auto-flush for the
2048 // duration of this scope. This is the only place where this optimization
2049 // maybe makes sense; please don't do it anywhere else.
2050 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2052 // Take key pair from key pool so it won't be used again
2053 reservekey.KeepKey();
2055 // Add tx to wallet, because if it has change it's also ours,
2056 // otherwise just for transaction history.
2057 AddToWallet(wtxNew);
2059 // Mark old coins as spent
2060 set<CWalletTx*> setCoins;
2061 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2063 CWalletTx &coin = mapWallet[txin.prevout.hash];
2064 coin.BindWallet(this);
2065 coin.MarkSpent(txin.prevout.n);
2067 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2068 vMintingWalletUpdated.push_back(coin.GetHash());
2075 // Track how many getdata requests our transaction gets
2076 mapRequestCount[wtxNew.GetHash()] = 0;
2079 if (!wtxNew.AcceptToMemoryPool())
2081 // This must not fail. The transaction has already been signed and recorded.
2082 printf("CommitTransaction() : Error: Transaction not valid");
2085 wtxNew.RelayWalletTransaction();
2093 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2095 CReserveKey reservekey(this);
2096 int64_t nFeeRequired;
2100 string strError = _("Error: Wallet locked, unable to create transaction ");
2101 printf("SendMoney() : %s", strError.c_str());
2104 if (fWalletUnlockMintOnly)
2106 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2107 printf("SendMoney() : %s", strError.c_str());
2110 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2113 if (nValue + nFeeRequired > GetBalance())
2114 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());
2116 strError = _("Error: Transaction creation failed ");
2117 printf("SendMoney() : %s", strError.c_str());
2121 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2124 if (!CommitTransaction(wtxNew, reservekey))
2125 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.");
2132 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2136 return _("Invalid amount");
2137 if (nValue + nTransactionFee > GetBalance())
2138 return _("Insufficient funds");
2140 // Parse Bitcoin address
2141 CScript scriptPubKey;
2142 scriptPubKey.SetDestination(address);
2144 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2150 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2154 fFirstRunRet = false;
2155 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2156 if (nLoadWalletRet == DB_NEED_REWRITE)
2158 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2161 // Note: can't top-up keypool here, because wallet is locked.
2162 // User will be prompted to unlock wallet the next operation
2163 // the requires a new key.
2167 if (nLoadWalletRet != DB_LOAD_OK)
2168 return nLoadWalletRet;
2169 fFirstRunRet = !vchDefaultKey.IsValid();
2171 NewThread(ThreadFlushWalletDB, &strWalletFile);
2176 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2178 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2179 mapAddressBook[address] = strName;
2180 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2183 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2186 bool CWallet::DelAddressBookName(const CTxDestination& address)
2188 mapAddressBook.erase(address);
2189 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2192 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2196 void CWallet::PrintWallet(const CBlock& block)
2200 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
2202 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2203 printf(" mine: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2205 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2207 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2208 printf(" stake: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2215 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2219 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2220 if (mi != mapWallet.end())
2229 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2233 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2236 vchDefaultKey = vchPubKey;
2240 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2242 if (!pwallet->fFileBacked)
2244 strWalletFileOut = pwallet->strWalletFile;
2249 // Mark old keypool keys as used,
2250 // and generate all new keys
2252 bool CWallet::NewKeyPool()
2256 CWalletDB walletdb(strWalletFile);
2257 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2258 walletdb.ErasePool(nIndex);
2264 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
2265 for (int i = 0; i < nKeys; i++)
2267 int64_t nIndex = i+1;
2268 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2269 setKeyPool.insert(nIndex);
2271 printf("CWallet::NewKeyPool wrote %" PRId64 " new keys\n", nKeys);
2276 bool CWallet::TopUpKeyPool(unsigned int nSize)
2284 CWalletDB walletdb(strWalletFile);
2287 unsigned int nTargetSize;
2289 nTargetSize = nSize;
2291 nTargetSize = max<unsigned int>(GetArg("-keypool", 100), 0LL);
2293 while (setKeyPool.size() < (nTargetSize + 1))
2296 if (!setKeyPool.empty())
2297 nEnd = *(--setKeyPool.end()) + 1;
2298 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2299 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2300 setKeyPool.insert(nEnd);
2301 printf("keypool added key %" PRId64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2307 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2310 keypool.vchPubKey = CPubKey();
2317 // Get the oldest key
2318 if(setKeyPool.empty())
2321 CWalletDB walletdb(strWalletFile);
2323 nIndex = *(setKeyPool.begin());
2324 setKeyPool.erase(setKeyPool.begin());
2325 if (!walletdb.ReadPool(nIndex, keypool))
2326 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2327 if (!HaveKey(keypool.vchPubKey.GetID()))
2328 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2329 assert(keypool.vchPubKey.IsValid());
2330 if (fDebug && GetBoolArg("-printkeypool"))
2331 printf("keypool reserve %" PRId64 "\n", nIndex);
2335 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2338 LOCK2(cs_main, cs_wallet);
2339 CWalletDB walletdb(strWalletFile);
2341 int64_t nIndex = 1 + *(--setKeyPool.end());
2342 if (!walletdb.WritePool(nIndex, keypool))
2343 throw runtime_error("AddReserveKey() : writing added key failed");
2344 setKeyPool.insert(nIndex);
2350 void CWallet::KeepKey(int64_t nIndex)
2352 // Remove from key pool
2355 CWalletDB walletdb(strWalletFile);
2356 walletdb.ErasePool(nIndex);
2359 printf("keypool keep %" PRId64 "\n", nIndex);
2362 void CWallet::ReturnKey(int64_t nIndex)
2364 // Return to key pool
2367 setKeyPool.insert(nIndex);
2370 printf("keypool return %" PRId64 "\n", nIndex);
2373 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2379 ReserveKeyFromKeyPool(nIndex, keypool);
2382 if (fAllowReuse && vchDefaultKey.IsValid())
2384 result = vchDefaultKey;
2387 if (IsLocked()) return false;
2388 result = GenerateNewKey();
2392 result = keypool.vchPubKey;
2397 int64_t CWallet::GetOldestKeyPoolTime()
2401 ReserveKeyFromKeyPool(nIndex, keypool);
2405 return keypool.nTime;
2408 std::map<CTxDestination, int64_t> CWallet::GetAddressBalances()
2410 map<CTxDestination, int64_t> balances;
2414 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2416 CWalletTx *pcoin = &walletEntry.second;
2418 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2421 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2424 int nDepth = pcoin->GetDepthInMainChain();
2425 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2428 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2430 CTxDestination addr;
2431 if (!IsMine(pcoin->vout[i]))
2433 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2436 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2438 if (!balances.count(addr))
2440 balances[addr] += n;
2448 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2450 set< set<CTxDestination> > groupings;
2451 set<CTxDestination> grouping;
2453 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2455 CWalletTx *pcoin = &walletEntry.second;
2457 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2459 // group all input addresses with each other
2460 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2462 CTxDestination address;
2463 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2465 grouping.insert(address);
2468 // group change with input addresses
2469 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2470 if (IsChange(txout))
2472 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2473 CTxDestination txoutAddr;
2474 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2476 grouping.insert(txoutAddr);
2478 groupings.insert(grouping);
2482 // group lone addrs by themselves
2483 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2484 if (IsMine(pcoin->vout[i]))
2486 CTxDestination address;
2487 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2489 grouping.insert(address);
2490 groupings.insert(grouping);
2495 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2496 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2497 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2499 // make a set of all the groups hit by this new group
2500 set< set<CTxDestination>* > hits;
2501 map< CTxDestination, set<CTxDestination>* >::iterator it;
2502 BOOST_FOREACH(CTxDestination address, grouping)
2503 if ((it = setmap.find(address)) != setmap.end())
2504 hits.insert((*it).second);
2506 // merge all hit groups into a new single group and delete old groups
2507 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2508 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2510 merged->insert(hit->begin(), hit->end());
2511 uniqueGroupings.erase(hit);
2514 uniqueGroupings.insert(merged);
2517 BOOST_FOREACH(CTxDestination element, *merged)
2518 setmap[element] = merged;
2521 set< set<CTxDestination> > ret;
2522 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2524 ret.insert(*uniqueGrouping);
2525 delete uniqueGrouping;
2531 // ppcoin: check 'spent' consistency between wallet and txindex
2532 // ppcoin: fix wallet spent state according to txindex
2533 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
2536 nBalanceInQuestion = 0;
2539 vector<CWalletTx*> vCoins;
2540 vCoins.reserve(mapWallet.size());
2541 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2542 vCoins.push_back(&(*it).second);
2545 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2547 // Find the corresponding transaction index
2549 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2551 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2553 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2555 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2556 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2558 nBalanceInQuestion += pcoin->vout[n].nValue;
2561 pcoin->MarkUnspent(n);
2562 pcoin->WriteToDisk();
2565 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2567 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2568 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2570 nBalanceInQuestion += pcoin->vout[n].nValue;
2573 pcoin->MarkSpent(n);
2574 pcoin->WriteToDisk();
2580 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2582 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2585 EraseFromWallet(pcoin->GetHash());
2591 // ppcoin: disable transaction (only for coinstake)
2592 void CWallet::DisableTransaction(const CTransaction &tx)
2594 if (!tx.IsCoinStake() || !IsFromMe(tx))
2595 return; // only disconnecting coinstake requires marking input unspent
2598 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2600 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2601 if (mi != mapWallet.end())
2603 CWalletTx& prev = (*mi).second;
2604 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2606 prev.MarkUnspent(txin.prevout.n);
2613 CPubKey CReserveKey::GetReservedKey()
2618 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2620 vchPubKey = keypool.vchPubKey;
2623 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2624 vchPubKey = pwallet->vchDefaultKey;
2627 assert(vchPubKey.IsValid());
2631 void CReserveKey::KeepKey()
2634 pwallet->KeepKey(nIndex);
2636 vchPubKey = CPubKey();
2639 void CReserveKey::ReturnKey()
2642 pwallet->ReturnKey(nIndex);
2644 vchPubKey = CPubKey();
2647 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2651 CWalletDB walletdb(strWalletFile);
2653 LOCK2(cs_main, cs_wallet);
2654 BOOST_FOREACH(const int64_t& id, setKeyPool)
2657 if (!walletdb.ReadPool(id, keypool))
2658 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2659 assert(keypool.vchPubKey.IsValid());
2660 CKeyID keyID = keypool.vchPubKey.GetID();
2661 if (!HaveKey(keyID))
2662 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2663 setAddress.insert(keyID);
2667 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2671 // Only notify UI if this transaction is in this wallet
2672 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2673 if (mi != mapWallet.end())
2675 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2676 vMintingWalletUpdated.push_back(hashTx);
2681 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2682 mapKeyBirth.clear();
2684 // get birth times for keys with metadata
2685 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2686 if (it->second.nCreateTime)
2687 mapKeyBirth[it->first] = it->second.nCreateTime;
2689 // map in which we'll infer heights of other keys
2690 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2691 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2692 std::set<CKeyID> setKeys;
2694 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2695 if (mapKeyBirth.count(keyid) == 0)
2696 mapKeyFirstBlock[keyid] = pindexMax;
2700 // if there are no such keys, we're done
2701 if (mapKeyFirstBlock.empty())
2704 // find first block that affects those keys, if there are any left
2705 std::vector<CKeyID> vAffected;
2706 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2707 // iterate over all wallet transactions...
2708 const CWalletTx &wtx = (*it).second;
2709 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2710 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2711 // ... which are already in a block
2712 int nHeight = blit->second->nHeight;
2713 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2714 // iterate over all their outputs
2715 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2716 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2717 // ... and all their affected keys
2718 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2719 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2720 rit->second = blit->second;
2727 // Extract block timestamps for those keys
2728 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2729 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2732 void CWallet::ClearOrphans()
2734 list<uint256> orphans;
2737 for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2739 const CWalletTx *wtx = &(*it).second;
2740 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
2742 orphans.push_back(wtx->GetHash());
2746 for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
2747 EraseFromWallet(*it);