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>
17 extern int nStakeMaxAge;
19 //////////////////////////////////////////////////////////////////////////////
24 struct CompareValueOnly
26 bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
27 const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
29 return t1.first < t2.first;
33 CPubKey CWallet::GenerateNewKey()
35 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
39 key.MakeNewKey(fCompressed);
41 // Compressed public keys were introduced in version 0.6.0
43 SetMinVersion(FEATURE_COMPRPUBKEY);
45 CPubKey pubkey = key.GetPubKey();
47 // Create new metadata
48 int64 nCreationTime = GetTime();
49 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
50 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
51 nTimeFirstKey = nCreationTime;
54 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
55 return key.GetPubKey();
58 bool CWallet::AddKey(const CKey& key)
60 CPubKey pubkey = key.GetPubKey();
62 if (!CCryptoKeyStore::AddKey(key))
67 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
71 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
73 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
79 if (pwalletdbEncryption)
80 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
82 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
87 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
89 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
90 nTimeFirstKey = meta.nCreateTime;
92 mapKeyMetadata[pubkey.GetID()] = meta;
96 bool CWallet::AddCScript(const CScript& redeemScript)
98 if (!CCryptoKeyStore::AddCScript(redeemScript))
102 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
105 bool CWallet::AddWatchOnly(const CScript &dest)
107 if (!CCryptoKeyStore::AddWatchOnly(dest))
109 nTimeFirstKey = 1; // No birthday information for watch-only keys.
112 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
115 bool CWallet::LoadWatchOnly(const CScript &dest)
117 return CCryptoKeyStore::AddWatchOnly(dest);
120 // ppcoin: optional setting to unlock wallet for block minting only;
121 // serves to disable the trivial sendmoney when OS account compromised
122 bool fWalletUnlockMintOnly = false;
124 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
130 CKeyingMaterial vMasterKey;
134 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
136 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
138 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
140 if (CCryptoKeyStore::Unlock(vMasterKey))
147 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
149 bool fWasLocked = IsLocked();
156 CKeyingMaterial vMasterKey;
157 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
159 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
161 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
163 if (CCryptoKeyStore::Unlock(vMasterKey))
165 int64 nStartTime = GetTimeMillis();
166 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
167 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
169 nStartTime = GetTimeMillis();
170 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
171 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
173 if (pMasterKey.second.nDeriveIterations < 25000)
174 pMasterKey.second.nDeriveIterations = 25000;
176 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
178 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
180 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
182 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
193 void CWallet::SetBestChain(const CBlockLocator& loc)
195 CWalletDB walletdb(strWalletFile);
196 walletdb.WriteBestBlock(loc);
199 // This class implements an addrIncoming entry that causes pre-0.4
200 // clients to crash on startup if reading a private-key-encrypted wallet.
201 class CCorruptAddress
206 if (nType & SER_DISK)
211 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
213 if (nWalletVersion >= nVersion)
216 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
217 if (fExplicit && nVersion > nWalletMaxVersion)
218 nVersion = FEATURE_LATEST;
220 nWalletVersion = nVersion;
222 if (nVersion > nWalletMaxVersion)
223 nWalletMaxVersion = nVersion;
227 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
228 if (nWalletVersion >= 40000)
230 // Versions prior to 0.4.0 did not support the "minversion" record.
231 // Use a CCorruptAddress to make them crash instead.
232 CCorruptAddress corruptAddress;
233 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
235 if (nWalletVersion > 40000)
236 pwalletdb->WriteMinVersion(nWalletVersion);
244 bool CWallet::SetMaxVersion(int nVersion)
246 // cannot downgrade below current version
247 if (nWalletVersion > nVersion)
250 nWalletMaxVersion = nVersion;
255 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
260 CKeyingMaterial vMasterKey;
261 RandAddSeedPerfmon();
263 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
264 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
266 CMasterKey kMasterKey(nDerivationMethodIndex);
268 RandAddSeedPerfmon();
269 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
270 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
273 int64 nStartTime = GetTimeMillis();
274 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
275 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
277 nStartTime = GetTimeMillis();
278 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
279 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
281 if (kMasterKey.nDeriveIterations < 25000)
282 kMasterKey.nDeriveIterations = 25000;
284 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
286 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
288 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
293 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
296 pwalletdbEncryption = new CWalletDB(strWalletFile);
297 if (!pwalletdbEncryption->TxnBegin())
299 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
302 if (!EncryptKeys(vMasterKey))
305 pwalletdbEncryption->TxnAbort();
306 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.
309 // Encryption was introduced in version 0.4.0
310 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
314 if (!pwalletdbEncryption->TxnCommit())
315 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.
317 delete pwalletdbEncryption;
318 pwalletdbEncryption = NULL;
322 Unlock(strWalletPassphrase);
326 // Need to completely rewrite the wallet file; if we don't, bdb might keep
327 // bits of the unencrypted private key in slack space in the database file.
328 CDB::Rewrite(strWalletFile);
331 NotifyStatusChanged(this);
336 int64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
338 int64 nRet = nOrderPosNext++;
340 pwalletdb->WriteOrderPosNext(nOrderPosNext);
342 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
347 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
349 CWalletDB walletdb(strWalletFile);
351 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
354 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
355 // would make this much faster for applications that do this a lot.
356 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
358 CWalletTx* wtx = &((*it).second);
359 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
362 walletdb.ListAccountCreditDebit(strAccount, acentries);
363 BOOST_FOREACH(CAccountingEntry& entry, acentries)
365 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
371 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
373 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
374 // Update the wallet spent flag if it doesn't know due to wallet.dat being
375 // restored from backup or the user making copies of wallet.dat.
378 BOOST_FOREACH(const CTxIn& txin, tx.vin)
380 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
381 if (mi != mapWallet.end())
383 CWalletTx& wtx = (*mi).second;
384 if (txin.prevout.n >= wtx.vout.size())
385 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
386 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
388 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
389 wtx.MarkSpent(txin.prevout.n);
391 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
398 uint256 hash = tx.GetHash();
399 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
400 CWalletTx& wtx = (*mi).second;
402 BOOST_FOREACH(const CTxOut& txout, tx.vout)
406 wtx.MarkUnspent(&txout - &tx.vout[0]);
408 NotifyTransactionChanged(this, hash, CT_UPDATED);
416 void CWallet::MarkDirty()
420 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
421 item.second.MarkDirty();
425 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
427 uint256 hash = wtxIn.GetHash();
430 // Inserts only if not already there, returns tx inserted or tx found
431 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
432 CWalletTx& wtx = (*ret.first).second;
433 wtx.BindWallet(this);
434 bool fInsertedNew = ret.second;
437 wtx.nTimeReceived = GetAdjustedTime();
438 wtx.nOrderPos = IncOrderPosNext();
440 wtx.nTimeSmart = wtx.nTimeReceived;
441 if (wtxIn.hashBlock != 0)
443 if (mapBlockIndex.count(wtxIn.hashBlock))
445 unsigned int latestNow = wtx.nTimeReceived;
446 unsigned int latestEntry = 0;
448 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
449 int64 latestTolerated = latestNow + 300;
450 std::list<CAccountingEntry> acentries;
451 TxItems txOrdered = OrderedTxItems(acentries);
452 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
454 CWalletTx *const pwtx = (*it).second.first;
457 CAccountingEntry *const pacentry = (*it).second.second;
461 nSmartTime = pwtx->nTimeSmart;
463 nSmartTime = pwtx->nTimeReceived;
466 nSmartTime = pacentry->nTime;
467 if (nSmartTime <= latestTolerated)
469 latestEntry = nSmartTime;
470 if (nSmartTime > latestNow)
471 latestNow = nSmartTime;
477 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
478 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
481 printf("AddToWallet() : found %s in block %s not in index\n",
482 wtxIn.GetHash().ToString().substr(0,10).c_str(),
483 wtxIn.hashBlock.ToString().c_str());
487 bool fUpdated = false;
491 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
493 wtx.hashBlock = wtxIn.hashBlock;
496 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
498 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
499 wtx.nIndex = wtxIn.nIndex;
502 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
504 wtx.fFromMe = wtxIn.fFromMe;
507 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
511 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
514 if (fInsertedNew || fUpdated)
515 if (!wtx.WriteToDisk())
518 // If default receiving address gets used, replace it with a new one
519 CScript scriptDefaultKey;
520 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
521 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
523 if (txout.scriptPubKey == scriptDefaultKey)
525 CPubKey newDefaultKey;
526 if (GetKeyFromPool(newDefaultKey, false))
528 SetDefaultKey(newDefaultKey);
529 SetAddressBookName(vchDefaultKey.GetID(), "");
534 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
535 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
537 // Notify UI of new or updated transaction
538 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
540 // notify an external script when a wallet transaction comes in or is updated
541 std::string strCmd = GetArg("-walletnotify", "");
543 if ( !strCmd.empty())
545 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
546 boost::thread t(runCommand, strCmd); // thread runs free
553 // Add a transaction to the wallet, or update it.
554 // pblock is optional, but should be provided if the transaction is known to be in a block.
555 // If fUpdate is true, existing transactions will be updated.
556 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
558 uint256 hash = tx.GetHash();
561 bool fExisted = mapWallet.count(hash);
562 if (fExisted && !fUpdate) return false;
563 if (fExisted || IsMine(tx) || IsFromMe(tx))
565 CWalletTx wtx(this,tx);
566 // Get merkle branch if transaction was found in a block
568 wtx.SetMerkleBranch(pblock);
569 return AddToWallet(wtx);
572 WalletUpdateSpent(tx);
577 bool CWallet::EraseFromWallet(uint256 hash)
583 if (mapWallet.erase(hash))
584 CWalletDB(strWalletFile).EraseTx(hash);
590 isminetype CWallet::IsMine(const CTxIn &txin) const
594 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
595 if (mi != mapWallet.end())
597 const CWalletTx& prev = (*mi).second;
598 if (txin.prevout.n < prev.vout.size())
599 return IsMine(prev.vout[txin.prevout.n]);
605 int64 CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
609 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
610 if (mi != mapWallet.end())
612 const CWalletTx& prev = (*mi).second;
613 if (txin.prevout.n < prev.vout.size())
614 if (IsMine(prev.vout[txin.prevout.n]) & filter)
615 return prev.vout[txin.prevout.n].nValue;
621 bool CWallet::IsChange(const CTxOut& txout) const
623 // TODO: fix handling of 'change' outputs. The assumption is that any
624 // payment to a script that is ours, but isn't in the address book
625 // is change. That assumption is likely to break when we implement multisignature
626 // wallets that return change back into a multi-signature-protected address;
627 // a better way of identifying which outputs are 'the send' and which are
628 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
629 // which output, if any, was change).
630 if (::IsMine(*this, txout.scriptPubKey))
632 CTxDestination address;
633 if (!ExtractDestination(txout.scriptPubKey, address))
637 if (!mapAddressBook.count(address))
643 int64 CWalletTx::GetTxTime() const
645 int64 n = nTimeSmart;
646 return n ? n : nTimeReceived;
649 int CWalletTx::GetRequestCount() const
651 // Returns -1 if it wasn't being tracked
654 LOCK(pwallet->cs_wallet);
655 if (IsCoinBase() || IsCoinStake())
660 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
661 if (mi != pwallet->mapRequestCount.end())
662 nRequests = (*mi).second;
667 // Did anyone request this transaction?
668 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
669 if (mi != pwallet->mapRequestCount.end())
671 nRequests = (*mi).second;
673 // How about the block it's in?
674 if (nRequests == 0 && hashBlock != 0)
676 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
677 if (mi != pwallet->mapRequestCount.end())
678 nRequests = (*mi).second;
680 nRequests = 1; // If it's in someone else's block it must have got out
688 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
689 list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount, const isminefilter& filter) const
691 nGeneratedImmature = nGeneratedMature = nFee = 0;
692 listReceived.clear();
694 strSentAccount = strFromAccount;
696 if (IsCoinBase() || IsCoinStake())
698 if (GetBlocksToMaturity() > 0)
699 nGeneratedImmature = pwallet->GetCredit(*this, filter);
701 nGeneratedMature = GetCredit(filter);
706 int64 nDebit = GetDebit(filter);
707 if (nDebit > 0) // debit>0 means we signed/sent this transaction
709 int64 nValueOut = GetValueOut();
710 nFee = nDebit - nValueOut;
714 BOOST_FOREACH(const CTxOut& txout, vout)
716 isminetype fIsMine = pwallet->IsMine(txout);
717 // Only need to handle txouts if AT LEAST one of these is true:
718 // 1) they debit from us (sent)
719 // 2) the output is to us (received)
722 // Don't report 'change' txouts
723 if (pwallet->IsChange(txout))
726 else if (!(fIsMine & filter))
729 // In either case, we need to get the destination address
730 CTxDestination address;
731 if (!ExtractDestination(txout.scriptPubKey, address))
733 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
734 this->GetHash().ToString().c_str());
735 address = CNoDestination();
738 // If we are debited by the transaction, add the output as a "sent" entry
740 listSent.push_back(make_pair(address, txout.nValue));
742 // If we are receiving the output, add it as a "received" entry
743 if (fIsMine & filter)
744 listReceived.push_back(make_pair(address, txout.nValue));
749 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
750 int64& nSent, int64& nFee, const isminefilter& filter) const
752 nGenerated = nReceived = nSent = nFee = 0;
754 int64 allGeneratedImmature, allGeneratedMature, allFee;
755 allGeneratedImmature = allGeneratedMature = allFee = 0;
756 string strSentAccount;
757 list<pair<CTxDestination, int64> > listReceived;
758 list<pair<CTxDestination, int64> > listSent;
759 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
761 if (strAccount == "")
762 nGenerated = allGeneratedMature;
763 if (strAccount == strSentAccount)
765 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
770 LOCK(pwallet->cs_wallet);
771 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
773 if (pwallet->mapAddressBook.count(r.first))
775 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
776 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
777 nReceived += r.second;
779 else if (strAccount.empty())
781 nReceived += r.second;
787 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
791 const int COPY_DEPTH = 3;
792 if (SetMerkleBranch() < COPY_DEPTH)
794 vector<uint256> vWorkQueue;
795 BOOST_FOREACH(const CTxIn& txin, vin)
796 vWorkQueue.push_back(txin.prevout.hash);
798 // This critsect is OK because txdb is already open
800 LOCK(pwallet->cs_wallet);
801 map<uint256, const CMerkleTx*> mapWalletPrev;
802 set<uint256> setAlreadyDone;
803 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
805 uint256 hash = vWorkQueue[i];
806 if (setAlreadyDone.count(hash))
808 setAlreadyDone.insert(hash);
811 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
812 if (mi != pwallet->mapWallet.end())
815 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
816 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
818 else if (mapWalletPrev.count(hash))
820 tx = *mapWalletPrev[hash];
822 else if (!fClient && txdb.ReadDiskTx(hash, tx))
828 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
832 int nDepth = tx.SetMerkleBranch();
833 vtxPrev.push_back(tx);
835 if (nDepth < COPY_DEPTH)
837 BOOST_FOREACH(const CTxIn& txin, tx.vin)
838 vWorkQueue.push_back(txin.prevout.hash);
844 reverse(vtxPrev.begin(), vtxPrev.end());
847 bool CWalletTx::WriteToDisk()
849 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
852 // Scan the block chain (starting in pindexStart) for transactions
853 // from or to us. If fUpdate is true, found transactions that already
854 // exist in the wallet will be updated.
855 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
859 CBlockIndex* pindex = pindexStart;
865 block.ReadFromDisk(pindex, true);
866 BOOST_FOREACH(CTransaction& tx, block.vtx)
868 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
871 pindex = pindex->pnext;
877 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
880 tx.ReadFromDisk(COutPoint(hashTx, 0));
881 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
886 void CWallet::ReacceptWalletTransactions()
894 vector<CDiskTxPos> vMissingTx;
895 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
897 CWalletTx& wtx = item.second;
898 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
902 bool fUpdated = false;
903 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
905 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
906 if (txindex.vSpent.size() != wtx.vout.size())
908 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
911 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
915 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
919 vMissingTx.push_back(txindex.vSpent[i]);
924 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
931 // Re-accept any txes of ours that aren't already in a block
932 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
933 wtx.AcceptWalletTransaction(txdb, false);
936 if (!vMissingTx.empty())
938 // TODO: optimize this to scan just part of the block chain?
939 if (ScanForWalletTransactions(pindexGenesisBlock))
940 fRepeat = true; // Found missing transactions: re-do re-accept.
945 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
947 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
949 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
951 uint256 hash = tx.GetHash();
952 if (!txdb.ContainsTx(hash))
953 RelayTransaction((CTransaction)tx, hash);
956 if (!(IsCoinBase() || IsCoinStake()))
958 uint256 hash = GetHash();
959 if (!txdb.ContainsTx(hash))
961 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
962 RelayTransaction((CTransaction)*this, hash);
967 void CWalletTx::RelayWalletTransaction()
970 RelayWalletTransaction(txdb);
973 void CWallet::ResendWalletTransactions()
975 // Do this infrequently and randomly to avoid giving away
976 // that these are our transactions.
977 static int64 nNextTime;
978 if (GetTime() < nNextTime)
980 bool fFirst = (nNextTime == 0);
981 nNextTime = GetTime() + GetRand(30 * 60);
985 // Only do it if there's been a new block since last time
986 static int64 nLastTime;
987 if (nTimeBestReceived < nLastTime)
989 nLastTime = GetTime();
991 // Rebroadcast any of our txes that aren't in a block yet
992 printf("ResendWalletTransactions()\n");
996 // Sort them in chronological order
997 multimap<unsigned int, CWalletTx*> mapSorted;
998 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1000 CWalletTx& wtx = item.second;
1001 // Don't rebroadcast until it's had plenty of time that
1002 // it should have gotten in already by now.
1003 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1004 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1006 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1008 CWalletTx& wtx = *item.second;
1009 if (wtx.CheckTransaction())
1010 wtx.RelayWalletTransaction(txdb);
1012 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1022 //////////////////////////////////////////////////////////////////////////////
1028 int64 CWallet::GetBalance() const
1033 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1035 const CWalletTx* pcoin = &(*it).second;
1036 if (pcoin->IsTrusted())
1037 nTotal += pcoin->GetAvailableCredit();
1044 int64 CWallet::GetWatchOnlyBalance() const
1049 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1051 const CWalletTx* pcoin = &(*it).second;
1052 if (pcoin->IsTrusted())
1053 nTotal += pcoin->GetAvailableWatchCredit();
1060 int64 CWallet::GetUnconfirmedBalance() const
1065 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1067 const CWalletTx* pcoin = &(*it).second;
1068 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1069 nTotal += pcoin->GetAvailableCredit();
1075 int64 CWallet::GetUnconfirmedWatchOnlyBalance() const
1080 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1082 const CWalletTx* pcoin = &(*it).second;
1083 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1084 nTotal += pcoin->GetAvailableWatchCredit();
1090 int64 CWallet::GetImmatureBalance() const
1095 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1097 const CWalletTx* pcoin = &(*it).second;
1098 nTotal += pcoin->GetImmatureCredit();
1104 int64 CWallet::GetImmatureWatchOnlyBalance() const
1109 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1111 const CWalletTx* pcoin = &(*it).second;
1112 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1118 // populate vCoins with vector of spendable COutputs
1119 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1125 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1127 const CWalletTx* pcoin = &(*it).second;
1129 if (!pcoin->IsFinal())
1132 if (fOnlyConfirmed && !pcoin->IsTrusted())
1135 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1138 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1141 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1142 isminetype mine = IsMine(pcoin->vout[i]);
1143 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1144 pcoin->vout[i].nValue >= nMinimumInputValue &&
1145 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1147 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1154 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
1160 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1162 const CWalletTx* pcoin = &(*it).second;
1164 if (!pcoin->IsFinal())
1167 if(pcoin->GetDepthInMainChain() < nConf)
1170 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1171 isminetype mine = IsMine(pcoin->vout[i]);
1173 if (!(pcoin->IsSpent(i)) && mine != MINE_NO && pcoin->vout[i].nValue >= nMinimumInputValue)
1174 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1180 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1181 vector<char>& vfBest, int64& nBest, int iterations = 1000)
1183 vector<char> vfIncluded;
1185 vfBest.assign(vValue.size(), true);
1186 nBest = nTotalLower;
1188 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1190 vfIncluded.assign(vValue.size(), false);
1192 bool fReachedTarget = false;
1193 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1195 for (unsigned int i = 0; i < vValue.size(); i++)
1197 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1199 nTotal += vValue[i].first;
1200 vfIncluded[i] = true;
1201 if (nTotal >= nTargetValue)
1203 fReachedTarget = true;
1207 vfBest = vfIncluded;
1209 nTotal -= vValue[i].first;
1210 vfIncluded[i] = false;
1218 int64 CWallet::GetStake() const
1222 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1224 const CWalletTx* pcoin = &(*it).second;
1225 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1226 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1231 int64 CWallet::GetWatchOnlyStake() const
1235 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1237 const CWalletTx* pcoin = &(*it).second;
1238 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1239 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1244 int64 CWallet::GetNewMint() const
1248 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1250 const CWalletTx* pcoin = &(*it).second;
1251 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1252 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1257 int64 CWallet::GetWatchOnlyNewMint() const
1261 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1263 const CWalletTx* pcoin = &(*it).second;
1264 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1265 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1270 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
1272 setCoinsRet.clear();
1275 // List of values less than target
1276 pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1277 coinLowestLarger.first = std::numeric_limits<int64>::max();
1278 coinLowestLarger.second.first = NULL;
1279 vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1280 int64 nTotalLower = 0;
1282 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1284 BOOST_FOREACH(const COutput &output, vCoins)
1286 if (!output.fSpendable)
1289 const CWalletTx *pcoin = output.tx;
1291 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1296 // Follow the timestamp rules
1297 if (pcoin->nTime > nSpendTime)
1300 int64 n = pcoin->vout[i].nValue;
1302 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1304 if (n == nTargetValue)
1306 setCoinsRet.insert(coin.second);
1307 nValueRet += coin.first;
1310 else if (n < nTargetValue + CENT)
1312 vValue.push_back(coin);
1315 else if (n < coinLowestLarger.first)
1317 coinLowestLarger = coin;
1321 if (nTotalLower == nTargetValue)
1323 for (unsigned int i = 0; i < vValue.size(); ++i)
1325 setCoinsRet.insert(vValue[i].second);
1326 nValueRet += vValue[i].first;
1331 if (nTotalLower < nTargetValue)
1333 if (coinLowestLarger.second.first == NULL)
1335 setCoinsRet.insert(coinLowestLarger.second);
1336 nValueRet += coinLowestLarger.first;
1340 // Solve subset sum by stochastic approximation
1341 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1342 vector<char> vfBest;
1345 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1346 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1347 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1349 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1350 // or the next bigger coin is closer), return the bigger coin
1351 if (coinLowestLarger.second.first &&
1352 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1354 setCoinsRet.insert(coinLowestLarger.second);
1355 nValueRet += coinLowestLarger.first;
1358 for (unsigned int i = 0; i < vValue.size(); i++)
1361 setCoinsRet.insert(vValue[i].second);
1362 nValueRet += vValue[i].first;
1365 if (fDebug && GetBoolArg("-printpriority"))
1368 printf("SelectCoins() best subset: ");
1369 for (unsigned int i = 0; i < vValue.size(); i++)
1371 printf("%s ", FormatMoney(vValue[i].first).c_str());
1372 printf("total %s\n", FormatMoney(nBest).c_str());
1379 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1381 vector<COutput> vCoins;
1382 AvailableCoins(vCoins, true, coinControl);
1384 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1385 if (coinControl && coinControl->HasSelected())
1387 BOOST_FOREACH(const COutput& out, vCoins)
1391 nValueRet += out.tx->vout[out.i].nValue;
1392 setCoinsRet.insert(make_pair(out.tx, out.i));
1394 return (nValueRet >= nTargetValue);
1397 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1398 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1399 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1402 // Select some coins without random shuffle or best subset approximation
1403 bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1405 vector<COutput> vCoins;
1406 AvailableCoinsMinConf(vCoins, nMinConf);
1408 setCoinsRet.clear();
1411 BOOST_FOREACH(COutput output, vCoins)
1413 if(!output.fSpendable)
1415 const CWalletTx *pcoin = output.tx;
1418 // Ignore immature coins
1419 if (pcoin->GetBlocksToMaturity() > 0)
1422 // Stop if we've chosen enough inputs
1423 if (nValueRet >= nTargetValue)
1426 // Follow the timestamp rules
1427 if (pcoin->nTime > nSpendTime)
1430 int64 n = pcoin->vout[i].nValue;
1432 pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1434 if (n >= nTargetValue)
1436 // If input value is greater or equal to target then simply insert
1437 // it into the current subset and exit
1438 setCoinsRet.insert(coin.second);
1439 nValueRet += coin.first;
1442 else if (n < nTargetValue + CENT)
1444 setCoinsRet.insert(coin.second);
1445 nValueRet += coin.first;
1452 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1455 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1461 if (vecSend.empty() || nValue < 0)
1464 wtxNew.BindWallet(this);
1467 LOCK2(cs_main, cs_wallet);
1468 // txdb must be opened before the mapWallet lock
1471 nFeeRet = nTransactionFee;
1475 wtxNew.vout.clear();
1476 wtxNew.fFromMe = true;
1478 int64 nTotalValue = nValue + nFeeRet;
1479 double dPriority = 0;
1480 // vouts to the payees
1481 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1482 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1484 // Choose coins to use
1485 set<pair<const CWalletTx*,unsigned int> > setCoins;
1487 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1489 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1491 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1492 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1495 int64 nChange = nValueIn - nValue - nFeeRet;
1496 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1497 // or until nChange becomes zero
1498 // NOTE: this depends on the exact behaviour of GetMinFee
1499 if (wtxNew.nTime < FEE_SWITCH_TIME && !fTestNet)
1501 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1503 int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1504 nChange -= nMoveToFee;
1505 nFeeRet += nMoveToFee;
1508 // sub-cent change is moved to fee
1509 if (nChange > 0 && nChange < CENT)
1518 // Fill a vout to ourself
1519 // TODO: pass in scriptChange instead of reservekey so
1520 // change transaction isn't always pay-to-bitcoin-address
1521 CScript scriptChange;
1523 // coin control: send change to custom address
1524 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1525 scriptChange.SetDestination(coinControl->destChange);
1527 // no coin control: send change to newly generated address
1530 // Note: We use a new key here to keep it from being obvious which side is the change.
1531 // The drawback is that by not reusing a previous key, the change may be lost if a
1532 // backup is restored, if the backup doesn't have the new private key for the change.
1533 // If we reused the old key, it would be possible to add code to look for and
1534 // rediscover unknown transactions that were written with keys of ours to recover
1535 // post-backup change.
1537 // Reserve a new key pair from key pool
1538 CPubKey vchPubKey = reservekey.GetReservedKey();
1540 scriptChange.SetDestination(vchPubKey.GetID());
1543 // Insert change txn at random position:
1544 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1545 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1548 reservekey.ReturnKey();
1551 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1552 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1556 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1557 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1561 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1562 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1564 dPriority /= nBytes;
1566 // Check that enough fee is included
1567 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1568 bool fAllowFree = CTransaction::AllowFree(dPriority);
1570 // Disable free transactions until 1 July 2014
1571 if (!fTestNet && wtxNew.nTime < FEE_SWITCH_TIME)
1576 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1578 if (nFeeRet < max(nPayFee, nMinFee))
1580 nFeeRet = max(nPayFee, nMinFee);
1584 // Fill vtxPrev by copying from previous transactions vtxPrev
1585 wtxNew.AddSupportingTransactions(txdb);
1586 wtxNew.fTimeReceivedIsTxTime = true;
1595 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1597 vector< pair<CScript, int64> > vecSend;
1598 vecSend.push_back(make_pair(scriptPubKey, nValue));
1599 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1602 void CWallet::GetStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
1604 int64 nTimeWeight = GetWeight(nTime, (int64)GetTime());
1606 // If time weight is lower or equal to zero then weight is zero.
1607 if (nTimeWeight <= 0)
1613 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1614 nWeight = bnCoinDayWeight.getuint64();
1618 // NovaCoin: get current stake weight
1619 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1621 // Choose coins to use
1622 int64 nBalance = GetBalance();
1623 int64 nReserveBalance = 0;
1625 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1627 error("GetStakeWeight : invalid reserve balance amount");
1631 if (nBalance <= nReserveBalance)
1634 vector<const CWalletTx*> vwtxPrev;
1637 * TODO: performance comparison
1639 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1640 static uint256 hashPrevBlock;
1641 static int64 nValueIn = 0;
1643 // Cache outputs unless best block changed
1644 if (hashPrevBlock != pindexBest->GetBlockHash())
1646 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetAdjustedTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1649 if (setCoins.empty())
1652 hashPrevBlock == pindexBest->GetBlockHash();
1656 set<pair<const CWalletTx*,unsigned int> > setCoins;
1659 // Simple coins selection - no randomization
1660 if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1663 if (setCoins.empty())
1667 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1671 LOCK2(cs_main, cs_wallet);
1672 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1676 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1677 CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1679 // Weight is greater than zero
1680 if (nTimeWeight > 0)
1682 nWeight += bnCoinDayWeight.getuint64();
1685 // Weight is greater than zero, but the maximum value isn't reached yet
1686 if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1688 nMinWeight += bnCoinDayWeight.getuint64();
1691 // Maximum weight was reached
1692 if (nTimeWeight == nStakeMaxAge)
1694 nMaxWeight += bnCoinDayWeight.getuint64();
1701 bool CWallet::MergeCoins(const int64& nAmount, const int64& nMaxValue, const int64& nOutputValue, list<uint256>& listMerged)
1703 int64 nBalance = GetBalance();
1705 if (nAmount > nBalance)
1710 set<pair<const CWalletTx*,unsigned int> > setCoins;
1712 // Simple coins selection - no randomization
1713 if (!SelectCoinsSimple(nAmount, GetTime(), 1, setCoins, nValueIn))
1716 if (setCoins.empty())
1720 vector<const CWalletTx*> vwtxPrev;
1722 // Reserve a new key pair from key pool
1723 CReserveKey reservekey(this);
1724 CPubKey vchPubKey = reservekey.GetReservedKey();
1727 CScript scriptOutput;
1728 scriptOutput.SetDestination(vchPubKey.GetID());
1731 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1734 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1736 int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1738 // Ignore coin if credit is too high
1739 if (nCredit >= nMaxValue)
1742 // Add current coin to inputs list and add its credit to transaction output
1743 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1744 wtxNew.vout[0].nValue += nCredit;
1745 vwtxPrev.push_back(pcoin.first);
1748 // Replaced with estimation for performance purposes
1750 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1751 const CWalletTx *txin = vwtxPrev[i];
1753 // Sign scripts to get actual transaction size for fee calculation
1754 if (!SignSignature(*this, *txin, wtxNew, i))
1759 // Assuming that average scriptsig size is 110 bytes
1760 int64 nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1761 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1763 double dFinalPriority = dWeight /= nBytes;
1764 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1766 // Get actual transaction fee according to its estimated size and priority
1767 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1769 // Prepare transaction for commit if sum is enough ot its size is too big
1770 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1772 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1774 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1775 const CWalletTx *txin = vwtxPrev[i];
1778 if (!SignSignature(*this, *txin, wtxNew, i))
1782 // Try to commit, return false on failure
1783 if (!CommitTransaction(wtxNew, reservekey))
1786 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1788 dWeight = 0; // Reset all temporary values
1791 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1795 // Create transactions if there are some unhandled coins left
1796 if (wtxNew.vout[0].nValue > 0) {
1797 int64 nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1799 double dFinalPriority = dWeight /= nBytes;
1800 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1802 // Get actual transaction fee according to its size and priority
1803 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1805 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1807 if (wtxNew.vout[0].nValue <= 0)
1810 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1811 const CWalletTx *txin = vwtxPrev[i];
1813 // Sign all scripts again
1814 if (!SignSignature(*this, *txin, wtxNew, i))
1818 // Try to commit, return false on failure
1819 if (!CommitTransaction(wtxNew, reservekey))
1822 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1829 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1831 // The following combine threshold is important to security
1832 // Should not be adjusted if you don't understand the consequences
1833 int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1835 CBigNum bnTargetPerCoinDay;
1836 bnTargetPerCoinDay.SetCompact(nBits);
1841 // Mark coin stake transaction
1842 CScript scriptEmpty;
1843 scriptEmpty.clear();
1844 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1846 // Choose coins to use
1847 int64 nBalance = GetBalance();
1848 int64 nReserveBalance = 0;
1850 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1851 return error("CreateCoinStake : invalid reserve balance amount");
1853 if (nBalance <= nReserveBalance)
1856 vector<const CWalletTx*> vwtxPrev;
1859 * TODO: performance comparison
1861 static set<pair<const CWalletTx*,unsigned int> > setCoins;
1862 static uint256 hashPrevBlock;
1863 static int64 nValueIn = 0;
1865 // Cache outputs unless best block changed
1866 if (hashPrevBlock != pindexBest->GetBlockHash())
1868 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1871 if (setCoins.empty())
1874 hashPrevBlock == pindexBest->GetBlockHash();
1878 set<pair<const CWalletTx*,unsigned int> > setCoins;
1881 // Select coins with suitable depth
1882 if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1885 if (setCoins.empty())
1889 CScript scriptPubKeyKernel;
1891 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1895 LOCK2(cs_main, cs_wallet);
1896 if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1900 // Read block header
1903 LOCK2(cs_main, cs_wallet);
1904 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1908 static int nMaxStakeSearchInterval = 60;
1909 if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1910 continue; // only count coins meeting min age requirement
1912 bool fKernelFound = false;
1913 for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1915 // Search backward in time from the given txNew timestamp
1916 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1917 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1918 COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1919 if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake))
1922 if (fDebug && GetBoolArg("-printcoinstake"))
1923 printf("CreateCoinStake : kernel found\n");
1924 vector<valtype> vSolutions;
1925 txnouttype whichType;
1926 CScript scriptPubKeyOut;
1927 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1928 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1930 if (fDebug && GetBoolArg("-printcoinstake"))
1931 printf("CreateCoinStake : failed to parse kernel\n");
1934 if (fDebug && GetBoolArg("-printcoinstake"))
1935 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1936 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1938 if (fDebug && GetBoolArg("-printcoinstake"))
1939 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1940 break; // only support pay to public key and pay to address
1942 if (whichType == TX_PUBKEYHASH) // pay to address type
1944 // convert to pay to public key type
1945 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1947 if (fDebug && GetBoolArg("-printcoinstake"))
1948 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1949 break; // unable to find corresponding public key
1951 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1953 if (whichType == TX_PUBKEY)
1955 valtype& vchPubKey = vSolutions[0];
1956 if (!keystore.GetKey(Hash160(vchPubKey), key))
1958 if (fDebug && GetBoolArg("-printcoinstake"))
1959 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1960 break; // unable to find corresponding public key
1963 if (key.GetPubKey() != vchPubKey)
1965 if (fDebug && GetBoolArg("-printcoinstake"))
1966 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1967 break; // keys mismatch
1970 scriptPubKeyOut = scriptPubKeyKernel;
1974 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1975 nCredit += pcoin.first->vout[pcoin.second].nValue;
1976 vwtxPrev.push_back(pcoin.first);
1977 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1979 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1980 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1981 if (fDebug && GetBoolArg("-printcoinstake"))
1982 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1983 fKernelFound = true;
1988 if (fKernelFound || fShutdown)
1989 break; // if kernel is found stop searching
1992 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1995 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1997 // Attempt to add more inputs
1998 // Only add coins of the same key/address as kernel
1999 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
2000 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
2002 int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
2004 // Stop adding more inputs if already too many inputs
2005 if (txNew.vin.size() >= 100)
2007 // Stop adding more inputs if value is already pretty significant
2008 if (nCredit > nCombineThreshold)
2010 // Stop adding inputs if reached reserve limit
2011 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
2013 // Do not add additional significant input
2014 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
2016 // Do not add input that is still too young
2017 if (nTimeWeight < nStakeMaxAge)
2020 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
2021 nCredit += pcoin.first->vout[pcoin.second].nValue;
2022 vwtxPrev.push_back(pcoin.first);
2026 // Calculate coin age reward
2030 if (!txNew.GetCoinAge(txdb, nCoinAge))
2031 return error("CreateCoinStake : failed to calculate coin age");
2032 nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
2038 // Set output amount
2039 if (txNew.vout.size() == 3)
2041 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2042 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2045 txNew.vout[1].nValue = nCredit - nMinFee;
2049 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2051 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2052 return error("CreateCoinStake : failed to sign coinstake");
2056 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2057 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2058 return error("CreateCoinStake : exceeded coinstake size limit");
2060 // Check enough fee is paid
2061 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2063 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2064 continue; // try signing again
2068 if (fDebug && GetBoolArg("-printfee"))
2069 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2074 // Successfully generated coinstake
2079 // Call after CreateTransaction unless you want to abort
2080 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2083 LOCK2(cs_main, cs_wallet);
2084 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2086 // This is only to keep the database open to defeat the auto-flush for the
2087 // duration of this scope. This is the only place where this optimization
2088 // maybe makes sense; please don't do it anywhere else.
2089 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2091 // Take key pair from key pool so it won't be used again
2092 reservekey.KeepKey();
2094 // Add tx to wallet, because if it has change it's also ours,
2095 // otherwise just for transaction history.
2096 AddToWallet(wtxNew);
2098 // Mark old coins as spent
2099 set<CWalletTx*> setCoins;
2100 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2102 CWalletTx &coin = mapWallet[txin.prevout.hash];
2103 coin.BindWallet(this);
2104 coin.MarkSpent(txin.prevout.n);
2106 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2113 // Track how many getdata requests our transaction gets
2114 mapRequestCount[wtxNew.GetHash()] = 0;
2117 if (!wtxNew.AcceptToMemoryPool())
2119 // This must not fail. The transaction has already been signed and recorded.
2120 printf("CommitTransaction() : Error: Transaction not valid");
2123 wtxNew.RelayWalletTransaction();
2131 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
2133 CReserveKey reservekey(this);
2138 string strError = _("Error: Wallet locked, unable to create transaction ");
2139 printf("SendMoney() : %s", strError.c_str());
2142 if (fWalletUnlockMintOnly)
2144 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2145 printf("SendMoney() : %s", strError.c_str());
2148 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2151 if (nValue + nFeeRequired > GetBalance())
2152 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());
2154 strError = _("Error: Transaction creation failed ");
2155 printf("SendMoney() : %s", strError.c_str());
2159 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2162 if (!CommitTransaction(wtxNew, reservekey))
2163 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.");
2170 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
2174 return _("Invalid amount");
2175 if (nValue + nTransactionFee > GetBalance())
2176 return _("Insufficient funds");
2178 // Parse Bitcoin address
2179 CScript scriptPubKey;
2180 scriptPubKey.SetDestination(address);
2182 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2188 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2192 fFirstRunRet = false;
2193 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2194 if (nLoadWalletRet == DB_NEED_REWRITE)
2196 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2199 // Note: can't top-up keypool here, because wallet is locked.
2200 // User will be prompted to unlock wallet the next operation
2201 // the requires a new key.
2205 if (nLoadWalletRet != DB_LOAD_OK)
2206 return nLoadWalletRet;
2207 fFirstRunRet = !vchDefaultKey.IsValid();
2209 NewThread(ThreadFlushWalletDB, &strWalletFile);
2214 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2216 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2217 mapAddressBook[address] = strName;
2218 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2221 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2224 bool CWallet::DelAddressBookName(const CTxDestination& address)
2226 mapAddressBook.erase(address);
2227 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2230 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2234 void CWallet::PrintWallet(const CBlock& block)
2238 if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
2240 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2241 printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2243 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2245 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2246 printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2253 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2257 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2258 if (mi != mapWallet.end())
2267 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2271 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2274 vchDefaultKey = vchPubKey;
2278 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2280 if (!pwallet->fFileBacked)
2282 strWalletFileOut = pwallet->strWalletFile;
2287 // Mark old keypool keys as used,
2288 // and generate all new keys
2290 bool CWallet::NewKeyPool()
2294 CWalletDB walletdb(strWalletFile);
2295 BOOST_FOREACH(int64 nIndex, setKeyPool)
2296 walletdb.ErasePool(nIndex);
2302 int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2303 for (int i = 0; i < nKeys; i++)
2306 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2307 setKeyPool.insert(nIndex);
2309 printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2314 bool CWallet::TopUpKeyPool(unsigned int nSize)
2322 CWalletDB walletdb(strWalletFile);
2325 unsigned int nTargetSize;
2327 nTargetSize = nSize;
2329 nTargetSize = max(GetArg("-keypool", 100), 0LL);
2331 while (setKeyPool.size() < (nTargetSize + 1))
2334 if (!setKeyPool.empty())
2335 nEnd = *(--setKeyPool.end()) + 1;
2336 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2337 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2338 setKeyPool.insert(nEnd);
2339 printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2345 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2348 keypool.vchPubKey = CPubKey();
2355 // Get the oldest key
2356 if(setKeyPool.empty())
2359 CWalletDB walletdb(strWalletFile);
2361 nIndex = *(setKeyPool.begin());
2362 setKeyPool.erase(setKeyPool.begin());
2363 if (!walletdb.ReadPool(nIndex, keypool))
2364 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2365 if (!HaveKey(keypool.vchPubKey.GetID()))
2366 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2367 assert(keypool.vchPubKey.IsValid());
2368 if (fDebug && GetBoolArg("-printkeypool"))
2369 printf("keypool reserve %"PRI64d"\n", nIndex);
2373 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2376 LOCK2(cs_main, cs_wallet);
2377 CWalletDB walletdb(strWalletFile);
2379 int64 nIndex = 1 + *(--setKeyPool.end());
2380 if (!walletdb.WritePool(nIndex, keypool))
2381 throw runtime_error("AddReserveKey() : writing added key failed");
2382 setKeyPool.insert(nIndex);
2388 void CWallet::KeepKey(int64 nIndex)
2390 // Remove from key pool
2393 CWalletDB walletdb(strWalletFile);
2394 walletdb.ErasePool(nIndex);
2397 printf("keypool keep %"PRI64d"\n", nIndex);
2400 void CWallet::ReturnKey(int64 nIndex)
2402 // Return to key pool
2405 setKeyPool.insert(nIndex);
2408 printf("keypool return %"PRI64d"\n", nIndex);
2411 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2417 ReserveKeyFromKeyPool(nIndex, keypool);
2420 if (fAllowReuse && vchDefaultKey.IsValid())
2422 result = vchDefaultKey;
2425 if (IsLocked()) return false;
2426 result = GenerateNewKey();
2430 result = keypool.vchPubKey;
2435 int64 CWallet::GetOldestKeyPoolTime()
2439 ReserveKeyFromKeyPool(nIndex, keypool);
2443 return keypool.nTime;
2446 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2448 map<CTxDestination, int64> balances;
2452 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2454 CWalletTx *pcoin = &walletEntry.second;
2456 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2459 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2462 int nDepth = pcoin->GetDepthInMainChain();
2463 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2466 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2468 CTxDestination addr;
2469 if (!IsMine(pcoin->vout[i]))
2471 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2474 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2476 if (!balances.count(addr))
2478 balances[addr] += n;
2486 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2488 set< set<CTxDestination> > groupings;
2489 set<CTxDestination> grouping;
2491 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2493 CWalletTx *pcoin = &walletEntry.second;
2495 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2497 // group all input addresses with each other
2498 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2500 CTxDestination address;
2501 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2503 grouping.insert(address);
2506 // group change with input addresses
2507 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2508 if (IsChange(txout))
2510 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2511 CTxDestination txoutAddr;
2512 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2514 grouping.insert(txoutAddr);
2516 groupings.insert(grouping);
2520 // group lone addrs by themselves
2521 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2522 if (IsMine(pcoin->vout[i]))
2524 CTxDestination address;
2525 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2527 grouping.insert(address);
2528 groupings.insert(grouping);
2533 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2534 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2535 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2537 // make a set of all the groups hit by this new group
2538 set< set<CTxDestination>* > hits;
2539 map< CTxDestination, set<CTxDestination>* >::iterator it;
2540 BOOST_FOREACH(CTxDestination address, grouping)
2541 if ((it = setmap.find(address)) != setmap.end())
2542 hits.insert((*it).second);
2544 // merge all hit groups into a new single group and delete old groups
2545 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2546 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2548 merged->insert(hit->begin(), hit->end());
2549 uniqueGroupings.erase(hit);
2552 uniqueGroupings.insert(merged);
2555 BOOST_FOREACH(CTxDestination element, *merged)
2556 setmap[element] = merged;
2559 set< set<CTxDestination> > ret;
2560 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2562 ret.insert(*uniqueGrouping);
2563 delete uniqueGrouping;
2569 // ppcoin: check 'spent' consistency between wallet and txindex
2570 // ppcoin: fix wallet spent state according to txindex
2571 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2574 nBalanceInQuestion = 0;
2577 vector<CWalletTx*> vCoins;
2578 vCoins.reserve(mapWallet.size());
2579 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2580 vCoins.push_back(&(*it).second);
2583 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2585 // Find the corresponding transaction index
2587 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2589 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2591 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2593 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2594 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2596 nBalanceInQuestion += pcoin->vout[n].nValue;
2599 pcoin->MarkUnspent(n);
2600 pcoin->WriteToDisk();
2603 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2605 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2606 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2608 nBalanceInQuestion += pcoin->vout[n].nValue;
2611 pcoin->MarkSpent(n);
2612 pcoin->WriteToDisk();
2618 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2620 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2623 EraseFromWallet(pcoin->GetHash());
2629 // ppcoin: disable transaction (only for coinstake)
2630 void CWallet::DisableTransaction(const CTransaction &tx)
2632 if (!tx.IsCoinStake() || !IsFromMe(tx))
2633 return; // only disconnecting coinstake requires marking input unspent
2636 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2638 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2639 if (mi != mapWallet.end())
2641 CWalletTx& prev = (*mi).second;
2642 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2644 prev.MarkUnspent(txin.prevout.n);
2651 CPubKey CReserveKey::GetReservedKey()
2656 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2658 vchPubKey = keypool.vchPubKey;
2661 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2662 vchPubKey = pwallet->vchDefaultKey;
2665 assert(vchPubKey.IsValid());
2669 void CReserveKey::KeepKey()
2672 pwallet->KeepKey(nIndex);
2674 vchPubKey = CPubKey();
2677 void CReserveKey::ReturnKey()
2680 pwallet->ReturnKey(nIndex);
2682 vchPubKey = CPubKey();
2685 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2689 CWalletDB walletdb(strWalletFile);
2691 LOCK2(cs_main, cs_wallet);
2692 BOOST_FOREACH(const int64& id, setKeyPool)
2695 if (!walletdb.ReadPool(id, keypool))
2696 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2697 assert(keypool.vchPubKey.IsValid());
2698 CKeyID keyID = keypool.vchPubKey.GetID();
2699 if (!HaveKey(keyID))
2700 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2701 setAddress.insert(keyID);
2705 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2709 // Only notify UI if this transaction is in this wallet
2710 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2711 if (mi != mapWallet.end())
2712 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2716 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2717 mapKeyBirth.clear();
2719 // get birth times for keys with metadata
2720 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2721 if (it->second.nCreateTime)
2722 mapKeyBirth[it->first] = it->second.nCreateTime;
2724 // map in which we'll infer heights of other keys
2725 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2726 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2727 std::set<CKeyID> setKeys;
2729 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2730 if (mapKeyBirth.count(keyid) == 0)
2731 mapKeyFirstBlock[keyid] = pindexMax;
2735 // if there are no such keys, we're done
2736 if (mapKeyFirstBlock.empty())
2739 // find first block that affects those keys, if there are any left
2740 std::vector<CKeyID> vAffected;
2741 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2742 // iterate over all wallet transactions...
2743 const CWalletTx &wtx = (*it).second;
2744 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2745 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2746 // ... which are already in a block
2747 int nHeight = blit->second->nHeight;
2748 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2749 // iterate over all their outputs
2750 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2751 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2752 // ... and all their affected keys
2753 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2754 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2755 rit->second = blit->second;
2762 // Extract block timestamps for those keys
2763 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2764 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off