1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
10 #include "ui_interface.h"
13 #include "coincontrol.h"
14 #include <boost/algorithm/string/replace.hpp>
21 bool fCoinsDataActual;
23 //////////////////////////////////////////////////////////////////////////////
28 struct CompareValueOnly
30 bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1,
31 const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const
33 return t1.first < t2.first;
37 CPubKey CWallet::GenerateNewKey()
39 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
43 key.MakeNewKey(fCompressed);
45 // Compressed public keys were introduced in version 0.6.0
47 SetMinVersion(FEATURE_COMPRPUBKEY);
49 CPubKey pubkey = key.GetPubKey();
51 // Create new metadata
52 int64_t nCreationTime = GetTime();
53 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
54 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
55 nTimeFirstKey = nCreationTime;
58 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
59 return key.GetPubKey();
62 bool CWallet::AddKey(const CKey& key)
64 CPubKey pubkey = key.GetPubKey();
66 if (!CCryptoKeyStore::AddKey(key))
71 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
75 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
77 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
80 // check if we need to remove from watch-only
82 script.SetDestination(vchPubKey.GetID());
83 if (HaveWatchOnly(script))
84 RemoveWatchOnly(script);
90 if (pwalletdbEncryption)
91 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
93 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
98 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
100 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
101 nTimeFirstKey = meta.nCreateTime;
103 mapKeyMetadata[pubkey.GetID()] = meta;
107 bool CWallet::AddCScript(const CScript& redeemScript)
109 if (!CCryptoKeyStore::AddCScript(redeemScript))
113 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
116 bool CWallet::LoadCScript(const CScript& redeemScript)
118 /* A sanity check was added in commit 5ed0a2b to avoid adding redeemScripts
119 * that never can be redeemed. However, old wallets may still contain
120 * these. Do not add them to the wallet and warn. */
121 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
123 std::string strAddr = CBitcoinAddress(redeemScript.GetID()).ToString();
124 printf("LoadCScript() : Warning: This wallet contains a redeemScript of size %" PRIszu " which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
125 redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr.c_str());
129 return CCryptoKeyStore::AddCScript(redeemScript);
133 bool CWallet::AddWatchOnly(const CScript &dest)
135 if (!CCryptoKeyStore::AddWatchOnly(dest))
137 nTimeFirstKey = 1; // No birthday information for watch-only keys.
138 NotifyWatchonlyChanged(true);
141 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
144 bool CWallet::RemoveWatchOnly(const CScript &dest)
147 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
149 if (!HaveWatchOnly())
150 NotifyWatchonlyChanged(false);
152 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
158 bool CWallet::LoadWatchOnly(const CScript &dest)
160 return CCryptoKeyStore::AddWatchOnly(dest);
163 // ppcoin: optional setting to unlock wallet for block minting only;
164 // serves to disable the trivial sendmoney when OS account compromised
165 bool fWalletUnlockMintOnly = false;
167 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
173 CKeyingMaterial vMasterKey;
177 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
179 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
181 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
183 if (CCryptoKeyStore::Unlock(vMasterKey))
190 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
192 bool fWasLocked = IsLocked();
199 CKeyingMaterial vMasterKey;
200 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
202 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
204 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
206 if (CCryptoKeyStore::Unlock(vMasterKey))
208 int64_t nStartTime = GetTimeMillis();
209 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
210 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
212 nStartTime = GetTimeMillis();
213 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
214 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
216 if (pMasterKey.second.nDeriveIterations < 25000)
217 pMasterKey.second.nDeriveIterations = 25000;
219 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
221 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
223 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
225 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
236 void CWallet::SetBestChain(const CBlockLocator& loc)
238 CWalletDB walletdb(strWalletFile);
239 walletdb.WriteBestBlock(loc);
242 // This class implements an addrIncoming entry that causes pre-0.4
243 // clients to crash on startup if reading a private-key-encrypted wallet.
244 class CCorruptAddress
249 if (nType & SER_DISK)
254 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
256 if (nWalletVersion >= nVersion)
259 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
260 if (fExplicit && nVersion > nWalletMaxVersion)
261 nVersion = FEATURE_LATEST;
263 nWalletVersion = nVersion;
265 if (nVersion > nWalletMaxVersion)
266 nWalletMaxVersion = nVersion;
270 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
271 if (nWalletVersion >= 40000)
273 // Versions prior to 0.4.0 did not support the "minversion" record.
274 // Use a CCorruptAddress to make them crash instead.
275 CCorruptAddress corruptAddress;
276 pwalletdb->WriteSetting("addrIncoming", corruptAddress);
278 if (nWalletVersion > 40000)
279 pwalletdb->WriteMinVersion(nWalletVersion);
287 bool CWallet::SetMaxVersion(int nVersion)
289 // cannot downgrade below current version
290 if (nWalletVersion > nVersion)
293 nWalletMaxVersion = nVersion;
298 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
303 CKeyingMaterial vMasterKey;
304 RandAddSeedPerfmon();
306 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
307 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
309 CMasterKey kMasterKey(nDerivationMethodIndex);
311 RandAddSeedPerfmon();
312 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
313 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
316 int64_t nStartTime = GetTimeMillis();
317 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
318 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
320 nStartTime = GetTimeMillis();
321 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
322 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
324 if (kMasterKey.nDeriveIterations < 25000)
325 kMasterKey.nDeriveIterations = 25000;
327 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
329 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
331 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
336 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
339 pwalletdbEncryption = new CWalletDB(strWalletFile);
340 if (!pwalletdbEncryption->TxnBegin())
342 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
345 if (!EncryptKeys(vMasterKey))
348 pwalletdbEncryption->TxnAbort();
349 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.
352 // Encryption was introduced in version 0.4.0
353 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
357 if (!pwalletdbEncryption->TxnCommit())
358 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.
360 delete pwalletdbEncryption;
361 pwalletdbEncryption = NULL;
365 Unlock(strWalletPassphrase);
369 // Need to completely rewrite the wallet file; if we don't, bdb might keep
370 // bits of the unencrypted private key in slack space in the database file.
371 CDB::Rewrite(strWalletFile);
374 NotifyStatusChanged(this);
379 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
381 int64_t nRet = nOrderPosNext++;
383 pwalletdb->WriteOrderPosNext(nOrderPosNext);
385 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
390 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
392 CWalletDB walletdb(strWalletFile);
394 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
397 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
398 // would make this much faster for applications that do this a lot.
399 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
401 CWalletTx* wtx = &((*it).second);
402 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
405 walletdb.ListAccountCreditDebit(strAccount, acentries);
406 BOOST_FOREACH(CAccountingEntry& entry, acentries)
408 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
414 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
416 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
417 // Update the wallet spent flag if it doesn't know due to wallet.dat being
418 // restored from backup or the user making copies of wallet.dat.
421 BOOST_FOREACH(const CTxIn& txin, tx.vin)
423 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
424 if (mi != mapWallet.end())
426 CWalletTx& wtx = (*mi).second;
427 if (txin.prevout.n >= wtx.vout.size())
428 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
429 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
431 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
432 wtx.MarkSpent(txin.prevout.n);
434 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
435 vMintingWalletUpdated.push_back(txin.prevout.hash);
442 uint256 hash = tx.GetHash();
443 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
444 CWalletTx& wtx = (*mi).second;
446 BOOST_FOREACH(const CTxOut& txout, tx.vout)
450 wtx.MarkUnspent(&txout - &tx.vout[0]);
452 NotifyTransactionChanged(this, hash, CT_UPDATED);
453 vMintingWalletUpdated.push_back(hash);
461 void CWallet::MarkDirty()
465 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
466 item.second.MarkDirty();
470 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
472 uint256 hash = wtxIn.GetHash();
475 // Inserts only if not already there, returns tx inserted or tx found
476 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
477 CWalletTx& wtx = (*ret.first).second;
478 wtx.BindWallet(this);
479 bool fInsertedNew = ret.second;
482 wtx.nTimeReceived = GetAdjustedTime();
483 wtx.nOrderPos = IncOrderPosNext();
485 wtx.nTimeSmart = wtx.nTimeReceived;
486 if (wtxIn.hashBlock != 0)
488 if (mapBlockIndex.count(wtxIn.hashBlock))
490 unsigned int latestNow = wtx.nTimeReceived;
491 unsigned int latestEntry = 0;
493 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
494 int64_t latestTolerated = latestNow + 300;
495 std::list<CAccountingEntry> acentries;
496 TxItems txOrdered = OrderedTxItems(acentries);
497 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
499 CWalletTx *const pwtx = (*it).second.first;
502 CAccountingEntry *const pacentry = (*it).second.second;
506 nSmartTime = pwtx->nTimeSmart;
508 nSmartTime = pwtx->nTimeReceived;
511 nSmartTime = pacentry->nTime;
512 if (nSmartTime <= latestTolerated)
514 latestEntry = nSmartTime;
515 if (nSmartTime > latestNow)
516 latestNow = nSmartTime;
522 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
523 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
526 printf("AddToWallet() : found %s in block %s not in index\n",
527 wtxIn.GetHash().ToString().substr(0,10).c_str(),
528 wtxIn.hashBlock.ToString().c_str());
532 bool fUpdated = false;
536 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
538 wtx.hashBlock = wtxIn.hashBlock;
541 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
543 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
544 wtx.nIndex = wtxIn.nIndex;
547 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
549 wtx.fFromMe = wtxIn.fFromMe;
552 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
556 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
559 if (fInsertedNew || fUpdated)
560 if (!wtx.WriteToDisk())
563 // If default receiving address gets used, replace it with a new one
564 CScript scriptDefaultKey;
565 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
566 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
568 if (txout.scriptPubKey == scriptDefaultKey)
570 CPubKey newDefaultKey;
571 if (GetKeyFromPool(newDefaultKey, false))
573 SetDefaultKey(newDefaultKey);
574 SetAddressBookName(vchDefaultKey.GetID(), "");
579 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
580 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
582 // Notify UI of new or updated transaction
583 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
584 vMintingWalletUpdated.push_back(hash);
585 // notify an external script when a wallet transaction comes in or is updated
586 std::string strCmd = GetArg("-walletnotify", "");
588 if ( !strCmd.empty())
590 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
591 boost::thread t(runCommand, strCmd); // thread runs free
598 // Add a transaction to the wallet, or update it.
599 // pblock is optional, but should be provided if the transaction is known to be in a block.
600 // If fUpdate is true, existing transactions will be updated.
601 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
603 uint256 hash = tx.GetHash();
606 bool fExisted = mapWallet.count(hash);
607 if (fExisted && !fUpdate) return false;
608 if (fExisted || IsMine(tx) || IsFromMe(tx))
610 CWalletTx wtx(this,tx);
611 // Get merkle branch if transaction was found in a block
613 wtx.SetMerkleBranch(pblock);
614 return AddToWallet(wtx);
617 WalletUpdateSpent(tx);
622 bool CWallet::EraseFromWallet(uint256 hash)
628 if (mapWallet.erase(hash))
629 CWalletDB(strWalletFile).EraseTx(hash);
635 isminetype CWallet::IsMine(const CTxIn &txin) const
639 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
640 if (mi != mapWallet.end())
642 const CWalletTx& prev = (*mi).second;
643 if (txin.prevout.n < prev.vout.size())
644 return IsMine(prev.vout[txin.prevout.n]);
650 int64_t CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
654 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
655 if (mi != mapWallet.end())
657 const CWalletTx& prev = (*mi).second;
658 if (txin.prevout.n < prev.vout.size())
659 if (IsMine(prev.vout[txin.prevout.n]) & filter)
660 return prev.vout[txin.prevout.n].nValue;
666 bool CWallet::IsChange(const CTxOut& txout) const
668 // TODO: fix handling of 'change' outputs. The assumption is that any
669 // payment to a script that is ours, but isn't in the address book
670 // is change. That assumption is likely to break when we implement multisignature
671 // wallets that return change back into a multi-signature-protected address;
672 // a better way of identifying which outputs are 'the send' and which are
673 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
674 // which output, if any, was change).
675 if (::IsMine(*this, txout.scriptPubKey))
677 CTxDestination address;
678 if (!ExtractDestination(txout.scriptPubKey, address))
682 if (!mapAddressBook.count(address))
688 int64_t CWalletTx::GetTxTime() const
693 int CWalletTx::GetRequestCount() const
695 // Returns -1 if it wasn't being tracked
698 LOCK(pwallet->cs_wallet);
699 if (IsCoinBase() || IsCoinStake())
704 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
705 if (mi != pwallet->mapRequestCount.end())
706 nRequests = (*mi).second;
711 // Did anyone request this transaction?
712 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
713 if (mi != pwallet->mapRequestCount.end())
715 nRequests = (*mi).second;
717 // How about the block it's in?
718 if (nRequests == 0 && hashBlock != 0)
720 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
721 if (mi != pwallet->mapRequestCount.end())
722 nRequests = (*mi).second;
724 nRequests = 1; // If it's in someone else's block it must have got out
732 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CTxDestination, int64_t> >& listReceived,
733 list<pair<CTxDestination, int64_t> >& listSent, int64_t& nFee, string& strSentAccount, const isminefilter& filter) const
735 nGeneratedImmature = nGeneratedMature = nFee = 0;
736 listReceived.clear();
738 strSentAccount = strFromAccount;
740 if (IsCoinBase() || IsCoinStake())
742 if (GetBlocksToMaturity() > 0)
743 nGeneratedImmature = pwallet->GetCredit(*this, filter);
745 nGeneratedMature = GetCredit(filter);
750 int64_t nDebit = GetDebit(filter);
751 if (nDebit > 0) // debit>0 means we signed/sent this transaction
753 int64_t nValueOut = GetValueOut();
754 nFee = nDebit - nValueOut;
758 BOOST_FOREACH(const CTxOut& txout, vout)
760 isminetype fIsMine = pwallet->IsMine(txout);
761 // Only need to handle txouts if AT LEAST one of these is true:
762 // 1) they debit from us (sent)
763 // 2) the output is to us (received)
766 // Don't report 'change' txouts
767 if (pwallet->IsChange(txout))
770 else if (!(fIsMine & filter))
773 // In either case, we need to get the destination address
774 CTxDestination address;
775 if (!ExtractDestination(txout.scriptPubKey, address))
777 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
778 this->GetHash().ToString().c_str());
779 address = CNoDestination();
782 // If we are debited by the transaction, add the output as a "sent" entry
784 listSent.push_back(make_pair(address, txout.nValue));
786 // If we are receiving the output, add it as a "received" entry
787 if (fIsMine & filter)
788 listReceived.push_back(make_pair(address, txout.nValue));
793 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
794 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const
796 nGenerated = nReceived = nSent = nFee = 0;
798 int64_t allGeneratedImmature, allGeneratedMature, allFee;
799 allGeneratedImmature = allGeneratedMature = allFee = 0;
800 string strSentAccount;
801 list<pair<CTxDestination, int64_t> > listReceived;
802 list<pair<CTxDestination, int64_t> > listSent;
803 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
805 if (strAccount == "")
806 nGenerated = allGeneratedMature;
807 if (strAccount == strSentAccount)
809 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& s, listSent)
814 LOCK(pwallet->cs_wallet);
815 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived)
817 if (pwallet->mapAddressBook.count(r.first))
819 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
820 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
821 nReceived += r.second;
823 else if (strAccount.empty())
825 nReceived += r.second;
831 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
835 const int COPY_DEPTH = 3;
836 if (SetMerkleBranch() < COPY_DEPTH)
838 vector<uint256> vWorkQueue;
839 BOOST_FOREACH(const CTxIn& txin, vin)
840 vWorkQueue.push_back(txin.prevout.hash);
842 // This critsect is OK because txdb is already open
844 LOCK(pwallet->cs_wallet);
845 map<uint256, const CMerkleTx*> mapWalletPrev;
846 set<uint256> setAlreadyDone;
847 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
849 uint256 hash = vWorkQueue[i];
850 if (setAlreadyDone.count(hash))
852 setAlreadyDone.insert(hash);
855 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
856 if (mi != pwallet->mapWallet.end())
859 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
860 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
862 else if (mapWalletPrev.count(hash))
864 tx = *mapWalletPrev[hash];
866 else if (!fClient && txdb.ReadDiskTx(hash, tx))
872 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
876 int nDepth = tx.SetMerkleBranch();
877 vtxPrev.push_back(tx);
879 if (nDepth < COPY_DEPTH)
881 BOOST_FOREACH(const CTxIn& txin, tx.vin)
882 vWorkQueue.push_back(txin.prevout.hash);
888 reverse(vtxPrev.begin(), vtxPrev.end());
891 bool CWalletTx::WriteToDisk()
893 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
896 // Scan the block chain (starting in pindexStart) for transactions
897 // from or to us. If fUpdate is true, found transactions that already
898 // exist in the wallet will be updated.
899 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
903 CBlockIndex* pindex = pindexStart;
909 block.ReadFromDisk(pindex, true);
910 BOOST_FOREACH(CTransaction& tx, block.vtx)
912 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
915 pindex = pindex->pnext;
921 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
924 tx.ReadFromDisk(COutPoint(hashTx, 0));
925 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
930 void CWallet::ReacceptWalletTransactions()
938 vector<CDiskTxPos> vMissingTx;
939 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
941 CWalletTx& wtx = item.second;
942 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
946 bool fUpdated = false;
947 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
949 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
950 if (txindex.vSpent.size() != wtx.vout.size())
952 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
955 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
959 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
963 vMissingTx.push_back(txindex.vSpent[i]);
968 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
975 // Re-accept any txes of ours that aren't already in a block
976 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
977 wtx.AcceptWalletTransaction(txdb, false);
980 if (!vMissingTx.empty())
982 // TODO: optimize this to scan just part of the block chain?
983 if (ScanForWalletTransactions(pindexGenesisBlock))
984 fRepeat = true; // Found missing transactions: re-do re-accept.
989 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
991 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
993 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
995 uint256 hash = tx.GetHash();
996 if (!txdb.ContainsTx(hash))
997 RelayTransaction((CTransaction)tx, hash);
1000 if (!(IsCoinBase() || IsCoinStake()))
1002 uint256 hash = GetHash();
1003 if (!txdb.ContainsTx(hash))
1005 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
1006 RelayTransaction((CTransaction)*this, hash);
1011 void CWalletTx::RelayWalletTransaction()
1014 RelayWalletTransaction(txdb);
1017 void CWallet::ResendWalletTransactions()
1019 // Do this infrequently and randomly to avoid giving away
1020 // that these are our transactions.
1021 static int64_t nNextTime;
1022 if (GetTime() < nNextTime)
1024 bool fFirst = (nNextTime == 0);
1025 nNextTime = GetTime() + GetRand(30 * 60);
1029 // Only do it if there's been a new block since last time
1030 static int64_t nLastTime;
1031 if (nTimeBestReceived < nLastTime)
1033 nLastTime = GetTime();
1035 // Rebroadcast any of our txes that aren't in a block yet
1036 printf("ResendWalletTransactions()\n");
1040 // Sort them in chronological order
1041 multimap<unsigned int, CWalletTx*> mapSorted;
1042 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1044 CWalletTx& wtx = item.second;
1045 // Don't rebroadcast until it's had plenty of time that
1046 // it should have gotten in already by now.
1047 if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
1048 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1050 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1052 CWalletTx& wtx = *item.second;
1053 if (wtx.CheckTransaction())
1054 wtx.RelayWalletTransaction(txdb);
1056 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1066 //////////////////////////////////////////////////////////////////////////////
1072 int64_t CWallet::GetBalance() const
1077 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1079 const CWalletTx* pcoin = &(*it).second;
1080 if (pcoin->IsTrusted())
1081 nTotal += pcoin->GetAvailableCredit();
1088 int64_t CWallet::GetWatchOnlyBalance() const
1093 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1095 const CWalletTx* pcoin = &(*it).second;
1096 if (pcoin->IsTrusted())
1097 nTotal += pcoin->GetAvailableWatchCredit();
1104 int64_t CWallet::GetUnconfirmedBalance() const
1109 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1111 const CWalletTx* pcoin = &(*it).second;
1112 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1113 nTotal += pcoin->GetAvailableCredit();
1119 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1124 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1126 const CWalletTx* pcoin = &(*it).second;
1127 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1128 nTotal += pcoin->GetAvailableWatchCredit();
1134 int64_t CWallet::GetImmatureBalance() const
1139 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1141 const CWalletTx* pcoin = &(*it).second;
1142 nTotal += pcoin->GetImmatureCredit();
1148 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1153 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1155 const CWalletTx* pcoin = &(*it).second;
1156 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1162 // populate vCoins with vector of spendable COutputs
1163 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1169 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1171 const CWalletTx* pcoin = &(*it).second;
1173 if (!pcoin->IsFinal())
1176 if (fOnlyConfirmed && !pcoin->IsTrusted())
1179 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1182 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1185 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1186 isminetype mine = IsMine(pcoin->vout[i]);
1187 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1188 pcoin->vout[i].nValue >= nMinimumInputValue &&
1189 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1191 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1198 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1204 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1206 const CWalletTx* pcoin = &(*it).second;
1208 if (!pcoin->IsFinal())
1211 if(pcoin->GetDepthInMainChain() < nConf)
1214 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1215 isminetype mine = IsMine(pcoin->vout[i]);
1217 // ignore coin if it was already spent or we don't own it
1218 if (pcoin->IsSpent(i) || mine == MINE_NO)
1221 // if coin value is between required limits then add new item to vector
1222 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1223 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1229 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1230 vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1232 vector<char> vfIncluded;
1234 vfBest.assign(vValue.size(), true);
1235 nBest = nTotalLower;
1237 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1239 vfIncluded.assign(vValue.size(), false);
1241 bool fReachedTarget = false;
1242 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1244 for (unsigned int i = 0; i < vValue.size(); i++)
1246 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1248 nTotal += vValue[i].first;
1249 vfIncluded[i] = true;
1250 if (nTotal >= nTargetValue)
1252 fReachedTarget = true;
1256 vfBest = vfIncluded;
1258 nTotal -= vValue[i].first;
1259 vfIncluded[i] = false;
1267 int64_t CWallet::GetStake() const
1271 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1273 const CWalletTx* pcoin = &(*it).second;
1274 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1275 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1280 int64_t CWallet::GetWatchOnlyStake() const
1284 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1286 const CWalletTx* pcoin = &(*it).second;
1287 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1288 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1293 int64_t CWallet::GetNewMint() const
1297 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1299 const CWalletTx* pcoin = &(*it).second;
1300 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1301 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1306 int64_t CWallet::GetWatchOnlyNewMint() const
1310 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1312 const CWalletTx* pcoin = &(*it).second;
1313 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1314 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1319 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
1321 setCoinsRet.clear();
1324 // List of values less than target
1325 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1326 coinLowestLarger.first = std::numeric_limits<int64_t>::max();
1327 coinLowestLarger.second.first = NULL;
1328 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1329 int64_t nTotalLower = 0;
1331 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1333 BOOST_FOREACH(const COutput &output, vCoins)
1335 if (!output.fSpendable)
1338 const CWalletTx *pcoin = output.tx;
1340 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1345 // Follow the timestamp rules
1346 if (pcoin->nTime > nSpendTime)
1349 int64_t n = pcoin->vout[i].nValue;
1351 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1353 if (n == nTargetValue)
1355 setCoinsRet.insert(coin.second);
1356 nValueRet += coin.first;
1359 else if (n < nTargetValue + CENT)
1361 vValue.push_back(coin);
1364 else if (n < coinLowestLarger.first)
1366 coinLowestLarger = coin;
1370 if (nTotalLower == nTargetValue)
1372 for (unsigned int i = 0; i < vValue.size(); ++i)
1374 setCoinsRet.insert(vValue[i].second);
1375 nValueRet += vValue[i].first;
1380 if (nTotalLower < nTargetValue)
1382 if (coinLowestLarger.second.first == NULL)
1384 setCoinsRet.insert(coinLowestLarger.second);
1385 nValueRet += coinLowestLarger.first;
1389 // Solve subset sum by stochastic approximation
1390 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1391 vector<char> vfBest;
1394 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1395 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1396 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1398 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1399 // or the next bigger coin is closer), return the bigger coin
1400 if (coinLowestLarger.second.first &&
1401 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1403 setCoinsRet.insert(coinLowestLarger.second);
1404 nValueRet += coinLowestLarger.first;
1407 for (unsigned int i = 0; i < vValue.size(); i++)
1410 setCoinsRet.insert(vValue[i].second);
1411 nValueRet += vValue[i].first;
1414 if (fDebug && GetBoolArg("-printpriority"))
1417 printf("SelectCoins() best subset: ");
1418 for (unsigned int i = 0; i < vValue.size(); i++)
1420 printf("%s ", FormatMoney(vValue[i].first).c_str());
1421 printf("total %s\n", FormatMoney(nBest).c_str());
1428 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
1430 vector<COutput> vCoins;
1431 AvailableCoins(vCoins, true, coinControl);
1433 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1434 if (coinControl && coinControl->HasSelected())
1436 BOOST_FOREACH(const COutput& out, vCoins)
1440 nValueRet += out.tx->vout[out.i].nValue;
1441 setCoinsRet.insert(make_pair(out.tx, out.i));
1443 return (nValueRet >= nTargetValue);
1446 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1447 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1448 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1451 // Select some coins without random shuffle or best subset approximation
1452 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
1454 vector<COutput> vCoins;
1455 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1457 setCoinsRet.clear();
1460 BOOST_FOREACH(COutput output, vCoins)
1462 if(!output.fSpendable)
1464 const CWalletTx *pcoin = output.tx;
1467 // Ignore immature coins
1468 if (pcoin->GetBlocksToMaturity() > 0)
1471 // Stop if we've chosen enough inputs
1472 if (nValueRet >= nTargetValue)
1475 // Follow the timestamp rules
1476 if (pcoin->nTime > nSpendTime)
1479 int64_t n = pcoin->vout[i].nValue;
1481 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1483 if (n >= nTargetValue)
1485 // If input value is greater or equal to target then simply insert
1486 // it into the current subset and exit
1487 setCoinsRet.insert(coin.second);
1488 nValueRet += coin.first;
1491 else if (n < nTargetValue + CENT)
1493 setCoinsRet.insert(coin.second);
1494 nValueRet += coin.first;
1501 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1504 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1510 if (vecSend.empty() || nValue < 0)
1513 wtxNew.BindWallet(this);
1516 LOCK2(cs_main, cs_wallet);
1517 // txdb must be opened before the mapWallet lock
1520 nFeeRet = nTransactionFee;
1524 wtxNew.vout.clear();
1525 wtxNew.fFromMe = true;
1527 int64_t nTotalValue = nValue + nFeeRet;
1528 double dPriority = 0;
1529 // vouts to the payees
1530 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1531 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1533 // Choose coins to use
1534 set<pair<const CWalletTx*,unsigned int> > setCoins;
1535 int64_t nValueIn = 0;
1536 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1538 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1540 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1541 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1544 int64_t nChange = nValueIn - nValue - nFeeRet;
1547 // Fill a vout to ourself
1548 // TODO: pass in scriptChange instead of reservekey so
1549 // change transaction isn't always pay-to-bitcoin-address
1550 CScript scriptChange;
1552 // coin control: send change to custom address
1553 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1554 scriptChange.SetDestination(coinControl->destChange);
1556 // no coin control: send change to newly generated address
1559 // Note: We use a new key here to keep it from being obvious which side is the change.
1560 // The drawback is that by not reusing a previous key, the change may be lost if a
1561 // backup is restored, if the backup doesn't have the new private key for the change.
1562 // If we reused the old key, it would be possible to add code to look for and
1563 // rediscover unknown transactions that were written with keys of ours to recover
1564 // post-backup change.
1566 // Reserve a new key pair from key pool
1567 CPubKey vchPubKey = reservekey.GetReservedKey();
1569 scriptChange.SetDestination(vchPubKey.GetID());
1572 // Insert change txn at random position:
1573 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1574 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1577 reservekey.ReturnKey();
1580 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1581 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1585 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1586 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1590 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1591 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1593 dPriority /= nBytes;
1595 // Check that enough fee is included
1596 bool fAllowFree = CTransaction::AllowFree(dPriority);
1597 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
1598 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1600 if (nFeeRet < max(nPayFee, nMinFee))
1602 nFeeRet = max(nPayFee, nMinFee);
1606 // Fill vtxPrev by copying from previous transactions vtxPrev
1607 wtxNew.AddSupportingTransactions(txdb);
1608 wtxNew.fTimeReceivedIsTxTime = true;
1617 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1619 vector< pair<CScript, int64_t> > vecSend;
1620 vecSend.push_back(make_pair(scriptPubKey, nValue));
1621 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1624 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
1626 int64_t nTimeWeight = GetWeight(nTime, (int64_t)GetTime());
1628 // If time weight is lower or equal to zero then weight is zero.
1629 if (nTimeWeight <= 0)
1635 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1636 nWeight = bnCoinDayWeight.getuint64();
1640 // NovaCoin: get current stake miner statistics
1641 void CWallet::GetStakeStats(float &nKernelsRate, float &nCoinDaysRate)
1643 static uint64_t nLastKernels = 0, nLastCoinDays = 0;
1644 static float nLastKernelsRate = 0, nLastCoinDaysRate = 0;
1645 static int64_t nLastTime = GetTime();
1647 if (nKernelsTried < nLastKernels)
1652 nLastTime = GetTime();
1655 int64_t nInterval = GetTime() - nLastTime;
1656 //if (nKernelsTried > 1000 && nInterval > 5)
1659 nKernelsRate = nLastKernelsRate = ( nKernelsTried - nLastKernels ) / (float) nInterval;
1660 nCoinDaysRate = nLastCoinDaysRate = ( nCoinDaysTried - nLastCoinDays ) / (float) nInterval;
1662 nLastKernels = nKernelsTried;
1663 nLastCoinDays = nCoinDaysTried;
1664 nLastTime = GetTime();
1668 nKernelsRate = nLastKernelsRate;
1669 nCoinDaysRate = nLastCoinDaysRate;
1673 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
1675 int64_t nBalance = GetBalance();
1677 if (nAmount > nBalance)
1681 int64_t nValueIn = 0;
1682 set<pair<const CWalletTx*,unsigned int> > setCoins;
1684 // Simple coins selection - no randomization
1685 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
1688 if (setCoins.empty())
1692 vector<const CWalletTx*> vwtxPrev;
1694 // Reserve a new key pair from key pool
1695 CReserveKey reservekey(this);
1696 CPubKey vchPubKey = reservekey.GetReservedKey();
1699 CScript scriptOutput;
1700 scriptOutput.SetDestination(vchPubKey.GetID());
1703 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1706 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1708 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1710 // Add current coin to inputs list and add its credit to transaction output
1711 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1712 wtxNew.vout[0].nValue += nCredit;
1713 vwtxPrev.push_back(pcoin.first);
1716 // Replaced with estimation for performance purposes
1718 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1719 const CWalletTx *txin = vwtxPrev[i];
1721 // Sign scripts to get actual transaction size for fee calculation
1722 if (!SignSignature(*this, *txin, wtxNew, i))
1727 // Assuming that average scriptsig size is 110 bytes
1728 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1729 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1731 double dFinalPriority = dWeight /= nBytes;
1732 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1734 // Get actual transaction fee according to its estimated size and priority
1735 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1737 // Prepare transaction for commit if sum is enough ot its size is too big
1738 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1740 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1742 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1743 const CWalletTx *txin = vwtxPrev[i];
1746 if (!SignSignature(*this, *txin, wtxNew, i))
1750 // Try to commit, return false on failure
1751 if (!CommitTransaction(wtxNew, reservekey))
1754 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1756 dWeight = 0; // Reset all temporary values
1759 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1763 // Create transactions if there are some unhandled coins left
1764 if (wtxNew.vout[0].nValue > 0) {
1765 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1767 double dFinalPriority = dWeight /= nBytes;
1768 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1770 // Get actual transaction fee according to its size and priority
1771 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1773 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1775 if (wtxNew.vout[0].nValue <= 0)
1778 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1779 const CWalletTx *txin = vwtxPrev[i];
1781 // Sign all scripts again
1782 if (!SignSignature(*this, *txin, wtxNew, i))
1786 // Try to commit, return false on failure
1787 if (!CommitTransaction(wtxNew, reservekey))
1790 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1797 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, uint32_t nSearchInterval, CTransaction& txNew, CKey& key)
1799 // The following combine threshold is important to security
1800 // Should not be adjusted if you don't understand the consequences
1801 int64_t nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1803 CBigNum bnTargetPerCoinDay;
1804 bnTargetPerCoinDay.SetCompact(nBits);
1809 // Mark coin stake transaction
1810 CScript scriptEmpty;
1811 scriptEmpty.clear();
1812 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1814 // Choose coins to use
1815 int64_t nBalance = GetBalance();
1816 int64_t nReserveBalance = 0;
1818 if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1819 return error("CreateCoinStake : invalid reserve balance amount");
1821 if (nBalance <= nReserveBalance)
1824 vector<const CWalletTx*> vwtxPrev;
1828 LOCK2(cs_main, cs_wallet);
1829 // Cache outputs unless best block or wallet transaction set changed
1830 if (!fCoinsDataActual)
1833 int64_t nValueIn = 0;
1835 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1838 if (setCoins.empty())
1844 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1846 // Load transaction index item
1847 if (!txdb.ReadTxIndex(pcoin->first->GetHash(), txindex))
1850 // Read block header
1851 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1854 uint64_t nStakeModifier = 0;
1855 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
1859 // (txid, vout.n) => ((txindex, (tx, vout.n)), (block, modifier))
1860 mapMeta[make_pair(pcoin->first->GetHash(), pcoin->second)] = make_pair(make_pair(txindex, *pcoin), make_pair(block, nStakeModifier));
1863 printf("Load coin: %s\n", pcoin->first->GetHash().GetHex().c_str());
1868 printf("Stake miner: %" PRIszu " meta items loaded for %" PRIszu " coins\n", mapMeta.size(), setCoins.size());
1870 fCoinsDataActual = true;
1876 int64_t nCredit = 0;
1877 CScript scriptPubKeyKernel;
1879 unsigned int nTimeTx, nBlockTime;
1880 COutPoint prevoutStake;
1881 CoinsSet::value_type kernelcoin;
1883 if (ScanForStakeKernelHash(mapMeta, nBits, txNew.nTime, nSearchInterval, kernelcoin, nTimeTx, nBlockTime, nKernelsTried, nCoinDaysTried))
1886 if (fDebug && GetBoolArg("-printcoinstake"))
1887 printf("CreateCoinStake : kernel found\n");
1888 vector<valtype> vSolutions;
1889 txnouttype whichType;
1890 CScript scriptPubKeyOut;
1891 scriptPubKeyKernel = kernelcoin.first->vout[kernelcoin.second].scriptPubKey;
1892 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1894 if (fDebug && GetBoolArg("-printcoinstake"))
1895 printf("CreateCoinStake : failed to parse kernel\n");
1898 if (fDebug && GetBoolArg("-printcoinstake"))
1899 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1900 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1902 if (fDebug && GetBoolArg("-printcoinstake"))
1903 printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1904 return false; // only support pay to public key and pay to address
1906 if (whichType == TX_PUBKEYHASH) // pay to address type
1908 // convert to pay to public key type
1909 if (!keystore.GetKey(uint160(vSolutions[0]), key))
1911 if (fDebug && GetBoolArg("-printcoinstake"))
1912 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1913 return false; // unable to find corresponding public key
1915 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1917 if (whichType == TX_PUBKEY)
1919 valtype& vchPubKey = vSolutions[0];
1920 if (!keystore.GetKey(Hash160(vchPubKey), key))
1922 if (fDebug && GetBoolArg("-printcoinstake"))
1923 printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1924 return false; // unable to find corresponding public key
1926 if (key.GetPubKey() != vchPubKey)
1928 if (fDebug && GetBoolArg("-printcoinstake"))
1929 printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1930 return false; // keys mismatch
1933 scriptPubKeyOut = scriptPubKeyKernel;
1936 txNew.nTime = nTimeTx;
1937 txNew.vin.push_back(CTxIn(kernelcoin.first->GetHash(), kernelcoin.second));
1938 nCredit += kernelcoin.first->vout[kernelcoin.second].nValue;
1939 vwtxPrev.push_back(kernelcoin.first);
1940 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1942 if (GetWeight((int64_t)nBlockTime, (int64_t)txNew.nTime) < nStakeMaxAge)
1943 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1944 if (fDebug && GetBoolArg("-printcoinstake"))
1945 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1948 if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1951 // (txid, vout.n) => ((txindex, (tx, vout.n)), (block, modifier))
1952 for(MetaMap::const_iterator meta_item = mapMeta.begin(); meta_item != mapMeta.end(); meta_item++)
1955 CoinsSet::value_type pcoin = meta_item->second.first.second;
1957 // Attempt to add more inputs
1958 // Only add coins of the same key/address as kernel
1959 if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1960 && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1962 int64_t nTimeWeight = GetWeight((int64_t)pcoin.first->nTime, (int64_t)txNew.nTime);
1964 // Stop adding more inputs if already too many inputs
1965 if (txNew.vin.size() >= 100)
1967 // Stop adding more inputs if value is already pretty significant
1968 if (nCredit > nCombineThreshold)
1970 // Stop adding inputs if reached reserve limit
1971 if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1973 // Do not add additional significant input
1974 if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1976 // Do not add input that is still too young
1977 if (nTimeWeight < nStakeMaxAge)
1980 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1981 nCredit += pcoin.first->vout[pcoin.second].nValue;
1982 vwtxPrev.push_back(pcoin.first);
1986 // Calculate coin age reward
1990 if (!txNew.GetCoinAge(txdb, nCoinAge))
1991 return error("CreateCoinStake : failed to calculate coin age");
1993 int64_t nReward = GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1994 // Refuse to create mint that has zero or negative reward
2001 int64_t nMinFee = 0;
2004 // Set output amount
2005 if (txNew.vout.size() == 3)
2007 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2008 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2011 txNew.vout[1].nValue = nCredit - nMinFee;
2015 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2017 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2018 return error("CreateCoinStake : failed to sign coinstake");
2022 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2023 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2024 return error("CreateCoinStake : exceeded coinstake size limit");
2026 // Check enough fee is paid
2027 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2029 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2030 continue; // try signing again
2034 if (fDebug && GetBoolArg("-printfee"))
2035 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2040 // Successfully generated coinstake
2045 // Call after CreateTransaction unless you want to abort
2046 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2049 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2051 // Track how many getdata requests our transaction gets
2052 mapRequestCount[wtxNew.GetHash()] = 0;
2054 // Try to broadcast before saving
2055 if (!wtxNew.AcceptToMemoryPool())
2057 // This must not fail. The transaction has already been signed.
2058 printf("CommitTransaction() : Error: Transaction not valid");
2062 wtxNew.RelayWalletTransaction();
2065 LOCK2(cs_main, cs_wallet);
2067 // This is only to keep the database open to defeat the auto-flush for the
2068 // duration of this scope. This is the only place where this optimization
2069 // maybe makes sense; please don't do it anywhere else.
2070 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2072 // Take key pair from key pool so it won't be used again
2073 reservekey.KeepKey();
2075 // Add tx to wallet, because if it has change it's also ours,
2076 // otherwise just for transaction history.
2077 AddToWallet(wtxNew);
2079 // Mark old coins as spent
2080 set<CWalletTx*> setCoins;
2081 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2083 CWalletTx &coin = mapWallet[txin.prevout.hash];
2084 coin.BindWallet(this);
2085 coin.MarkSpent(txin.prevout.n);
2087 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2088 vMintingWalletUpdated.push_back(coin.GetHash());
2101 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2103 CReserveKey reservekey(this);
2104 int64_t nFeeRequired;
2108 string strError = _("Error: Wallet locked, unable to create transaction ");
2109 printf("SendMoney() : %s", strError.c_str());
2112 if (fWalletUnlockMintOnly)
2114 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2115 printf("SendMoney() : %s", strError.c_str());
2118 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2121 if (nValue + nFeeRequired > GetBalance())
2122 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());
2124 strError = _("Error: Transaction creation failed ");
2125 printf("SendMoney() : %s", strError.c_str());
2129 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2132 if (!CommitTransaction(wtxNew, reservekey))
2133 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.");
2140 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2144 return _("Invalid amount");
2145 if (nValue + nTransactionFee > GetBalance())
2146 return _("Insufficient funds");
2148 // Parse Bitcoin address
2149 CScript scriptPubKey;
2150 scriptPubKey.SetDestination(address);
2152 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2158 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2162 fFirstRunRet = false;
2163 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2164 if (nLoadWalletRet == DB_NEED_REWRITE)
2166 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2169 // Note: can't top-up keypool here, because wallet is locked.
2170 // User will be prompted to unlock wallet the next operation
2171 // the requires a new key.
2175 if (nLoadWalletRet != DB_LOAD_OK)
2176 return nLoadWalletRet;
2177 fFirstRunRet = !vchDefaultKey.IsValid();
2179 NewThread(ThreadFlushWalletDB, &strWalletFile);
2184 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2186 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2187 mapAddressBook[address] = strName;
2188 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2191 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2194 bool CWallet::DelAddressBookName(const CTxDestination& address)
2196 mapAddressBook.erase(address);
2197 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2200 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2204 void CWallet::PrintWallet(const CBlock& block)
2208 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2210 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2211 printf(" PoS: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2213 else if (mapWallet.count(block.vtx[0].GetHash()))
2215 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2216 printf(" PoW: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2222 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2226 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2227 if (mi != mapWallet.end())
2236 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2240 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2243 vchDefaultKey = vchPubKey;
2247 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2249 if (!pwallet->fFileBacked)
2251 strWalletFileOut = pwallet->strWalletFile;
2256 // Mark old keypool keys as used,
2257 // and generate all new keys
2259 bool CWallet::NewKeyPool()
2263 CWalletDB walletdb(strWalletFile);
2264 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2265 walletdb.ErasePool(nIndex);
2271 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
2272 for (int i = 0; i < nKeys; i++)
2274 int64_t nIndex = i+1;
2275 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2276 setKeyPool.insert(nIndex);
2278 printf("CWallet::NewKeyPool wrote %" PRId64 " new keys\n", nKeys);
2283 bool CWallet::TopUpKeyPool(unsigned int nSize)
2291 CWalletDB walletdb(strWalletFile);
2294 unsigned int nTargetSize;
2296 nTargetSize = nSize;
2298 nTargetSize = max<unsigned int>(GetArg("-keypool", 100), 0LL);
2300 while (setKeyPool.size() < (nTargetSize + 1))
2303 if (!setKeyPool.empty())
2304 nEnd = *(--setKeyPool.end()) + 1;
2305 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2306 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2307 setKeyPool.insert(nEnd);
2308 printf("keypool added key %" PRId64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2314 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2317 keypool.vchPubKey = CPubKey();
2324 // Get the oldest key
2325 if(setKeyPool.empty())
2328 CWalletDB walletdb(strWalletFile);
2330 nIndex = *(setKeyPool.begin());
2331 setKeyPool.erase(setKeyPool.begin());
2332 if (!walletdb.ReadPool(nIndex, keypool))
2333 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2334 if (!HaveKey(keypool.vchPubKey.GetID()))
2335 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2336 assert(keypool.vchPubKey.IsValid());
2337 if (fDebug && GetBoolArg("-printkeypool"))
2338 printf("keypool reserve %" PRId64 "\n", nIndex);
2342 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2345 LOCK2(cs_main, cs_wallet);
2346 CWalletDB walletdb(strWalletFile);
2348 int64_t nIndex = 1 + *(--setKeyPool.end());
2349 if (!walletdb.WritePool(nIndex, keypool))
2350 throw runtime_error("AddReserveKey() : writing added key failed");
2351 setKeyPool.insert(nIndex);
2357 void CWallet::KeepKey(int64_t nIndex)
2359 // Remove from key pool
2362 CWalletDB walletdb(strWalletFile);
2363 walletdb.ErasePool(nIndex);
2366 printf("keypool keep %" PRId64 "\n", nIndex);
2369 void CWallet::ReturnKey(int64_t nIndex)
2371 // Return to key pool
2374 setKeyPool.insert(nIndex);
2377 printf("keypool return %" PRId64 "\n", nIndex);
2380 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2386 ReserveKeyFromKeyPool(nIndex, keypool);
2389 if (fAllowReuse && vchDefaultKey.IsValid())
2391 result = vchDefaultKey;
2394 if (IsLocked()) return false;
2395 result = GenerateNewKey();
2399 result = keypool.vchPubKey;
2404 int64_t CWallet::GetOldestKeyPoolTime()
2408 ReserveKeyFromKeyPool(nIndex, keypool);
2412 return keypool.nTime;
2415 std::map<CTxDestination, int64_t> CWallet::GetAddressBalances()
2417 map<CTxDestination, int64_t> balances;
2421 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2423 CWalletTx *pcoin = &walletEntry.second;
2425 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2428 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2431 int nDepth = pcoin->GetDepthInMainChain();
2432 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2435 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2437 CTxDestination addr;
2438 if (!IsMine(pcoin->vout[i]))
2440 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2443 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2445 if (!balances.count(addr))
2447 balances[addr] += n;
2455 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2457 set< set<CTxDestination> > groupings;
2458 set<CTxDestination> grouping;
2460 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2462 CWalletTx *pcoin = &walletEntry.second;
2464 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2466 // group all input addresses with each other
2467 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2469 CTxDestination address;
2470 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2472 grouping.insert(address);
2475 // group change with input addresses
2476 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2477 if (IsChange(txout))
2479 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2480 CTxDestination txoutAddr;
2481 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2483 grouping.insert(txoutAddr);
2485 groupings.insert(grouping);
2489 // group lone addrs by themselves
2490 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2491 if (IsMine(pcoin->vout[i]))
2493 CTxDestination address;
2494 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2496 grouping.insert(address);
2497 groupings.insert(grouping);
2502 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2503 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2504 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2506 // make a set of all the groups hit by this new group
2507 set< set<CTxDestination>* > hits;
2508 map< CTxDestination, set<CTxDestination>* >::iterator it;
2509 BOOST_FOREACH(CTxDestination address, grouping)
2510 if ((it = setmap.find(address)) != setmap.end())
2511 hits.insert((*it).second);
2513 // merge all hit groups into a new single group and delete old groups
2514 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2515 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2517 merged->insert(hit->begin(), hit->end());
2518 uniqueGroupings.erase(hit);
2521 uniqueGroupings.insert(merged);
2524 BOOST_FOREACH(CTxDestination element, *merged)
2525 setmap[element] = merged;
2528 set< set<CTxDestination> > ret;
2529 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2531 ret.insert(*uniqueGrouping);
2532 delete uniqueGrouping;
2538 // ppcoin: check 'spent' consistency between wallet and txindex
2539 // ppcoin: fix wallet spent state according to txindex
2540 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
2543 nBalanceInQuestion = 0;
2546 vector<CWalletTx*> vCoins;
2547 vCoins.reserve(mapWallet.size());
2548 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2549 vCoins.push_back(&(*it).second);
2552 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2554 // Find the corresponding transaction index
2556 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2558 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2560 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2562 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2563 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2565 nBalanceInQuestion += pcoin->vout[n].nValue;
2568 pcoin->MarkUnspent(n);
2569 pcoin->WriteToDisk();
2572 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2574 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2575 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2577 nBalanceInQuestion += pcoin->vout[n].nValue;
2580 pcoin->MarkSpent(n);
2581 pcoin->WriteToDisk();
2587 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2589 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2592 EraseFromWallet(pcoin->GetHash());
2598 // ppcoin: disable transaction (only for coinstake)
2599 void CWallet::DisableTransaction(const CTransaction &tx)
2601 if (!tx.IsCoinStake() || !IsFromMe(tx))
2602 return; // only disconnecting coinstake requires marking input unspent
2605 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2607 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2608 if (mi != mapWallet.end())
2610 CWalletTx& prev = (*mi).second;
2611 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2613 prev.MarkUnspent(txin.prevout.n);
2620 CPubKey CReserveKey::GetReservedKey()
2625 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2627 vchPubKey = keypool.vchPubKey;
2630 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2631 vchPubKey = pwallet->vchDefaultKey;
2634 assert(vchPubKey.IsValid());
2638 void CReserveKey::KeepKey()
2641 pwallet->KeepKey(nIndex);
2643 vchPubKey = CPubKey();
2646 void CReserveKey::ReturnKey()
2649 pwallet->ReturnKey(nIndex);
2651 vchPubKey = CPubKey();
2654 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2658 CWalletDB walletdb(strWalletFile);
2660 LOCK2(cs_main, cs_wallet);
2661 BOOST_FOREACH(const int64_t& id, setKeyPool)
2664 if (!walletdb.ReadPool(id, keypool))
2665 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2666 assert(keypool.vchPubKey.IsValid());
2667 CKeyID keyID = keypool.vchPubKey.GetID();
2668 if (!HaveKey(keyID))
2669 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2670 setAddress.insert(keyID);
2674 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2678 // Only notify UI if this transaction is in this wallet
2679 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2680 if (mi != mapWallet.end())
2682 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2683 vMintingWalletUpdated.push_back(hashTx);
2688 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2689 mapKeyBirth.clear();
2691 // get birth times for keys with metadata
2692 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2693 if (it->second.nCreateTime)
2694 mapKeyBirth[it->first] = it->second.nCreateTime;
2696 // map in which we'll infer heights of other keys
2697 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2698 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2699 std::set<CKeyID> setKeys;
2701 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2702 if (mapKeyBirth.count(keyid) == 0)
2703 mapKeyFirstBlock[keyid] = pindexMax;
2707 // if there are no such keys, we're done
2708 if (mapKeyFirstBlock.empty())
2711 // find first block that affects those keys, if there are any left
2712 std::vector<CKeyID> vAffected;
2713 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2714 // iterate over all wallet transactions...
2715 const CWalletTx &wtx = (*it).second;
2716 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2717 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2718 // ... which are already in a block
2719 int nHeight = blit->second->nHeight;
2720 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2721 // iterate over all their outputs
2722 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2723 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2724 // ... and all their affected keys
2725 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2726 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2727 rit->second = blit->second;
2734 // Extract block timestamps for those keys
2735 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2736 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2739 void CWallet::ClearOrphans()
2741 list<uint256> orphans;
2744 for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2746 const CWalletTx *wtx = &(*it).second;
2747 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
2749 orphans.push_back(wtx->GetHash());
2753 for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
2754 EraseFromWallet(*it);