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>
19 extern int64_t nReserveBalance;
21 //////////////////////////////////////////////////////////////////////////////
26 struct CompareValueOnly
28 bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1,
29 const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const
31 return t1.first < t2.first;
35 CPubKey CWallet::GenerateNewKey()
37 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
41 key.MakeNewKey(fCompressed);
43 // Compressed public keys were introduced in version 0.6.0
45 SetMinVersion(FEATURE_COMPRPUBKEY);
47 CPubKey pubkey = key.GetPubKey();
49 // Create new metadata
50 int64_t nCreationTime = GetTime();
51 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
52 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
53 nTimeFirstKey = nCreationTime;
56 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
57 return key.GetPubKey();
60 bool CWallet::AddKey(const CKey& key)
62 CPubKey pubkey = key.GetPubKey();
63 if (!CCryptoKeyStore::AddKey(key))
68 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
72 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
74 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
77 // check if we need to remove from watch-only
79 script.SetDestination(vchPubKey.GetID());
80 if (HaveWatchOnly(script))
81 RemoveWatchOnly(script);
87 if (pwalletdbEncryption)
88 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
90 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
95 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
97 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
98 nTimeFirstKey = meta.nCreateTime;
100 mapKeyMetadata[pubkey.GetID()] = meta;
104 bool CWallet::AddCScript(const CScript& redeemScript)
106 if (!CCryptoKeyStore::AddCScript(redeemScript))
110 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
113 bool CWallet::LoadCScript(const CScript& redeemScript)
115 /* A sanity check was added in commit 5ed0a2b to avoid adding redeemScripts
116 * that never can be redeemed. However, old wallets may still contain
117 * these. Do not add them to the wallet and warn. */
118 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
120 std::string strAddr = CBitcoinAddress(redeemScript.GetID()).ToString();
121 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",
122 redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr.c_str());
126 return CCryptoKeyStore::AddCScript(redeemScript);
130 bool CWallet::AddWatchOnly(const CScript &dest)
132 if (!CCryptoKeyStore::AddWatchOnly(dest))
134 nTimeFirstKey = 1; // No birthday information for watch-only keys.
135 NotifyWatchonlyChanged(true);
138 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
141 bool CWallet::RemoveWatchOnly(const CScript &dest)
144 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
146 if (!HaveWatchOnly())
147 NotifyWatchonlyChanged(false);
149 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
155 bool CWallet::LoadWatchOnly(const CScript &dest)
157 return CCryptoKeyStore::AddWatchOnly(dest);
160 // ppcoin: optional setting to unlock wallet for block minting only;
161 // serves to disable the trivial sendmoney when OS account compromised
162 bool fWalletUnlockMintOnly = false;
164 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
170 CKeyingMaterial vMasterKey;
174 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
176 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
178 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
180 if (CCryptoKeyStore::Unlock(vMasterKey))
187 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
189 bool fWasLocked = IsLocked();
196 CKeyingMaterial vMasterKey;
197 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
199 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
201 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
203 if (CCryptoKeyStore::Unlock(vMasterKey))
205 int64_t nStartTime = GetTimeMillis();
206 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
207 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
209 nStartTime = GetTimeMillis();
210 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
211 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
213 if (pMasterKey.second.nDeriveIterations < 25000)
214 pMasterKey.second.nDeriveIterations = 25000;
216 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
218 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
220 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
222 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
233 void CWallet::SetBestChain(const CBlockLocator& loc)
235 CWalletDB walletdb(strWalletFile);
236 walletdb.WriteBestBlock(loc);
239 // This class implements an addrIncoming entry that causes pre-0.4
240 // clients to crash on startup if reading a private-key-encrypted wallet.
241 class CCorruptAddress
246 if (nType & SER_DISK)
251 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
253 if (nWalletVersion >= nVersion)
256 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
257 if (fExplicit && nVersion > nWalletMaxVersion)
258 nVersion = FEATURE_LATEST;
260 nWalletVersion = nVersion;
262 if (nVersion > nWalletMaxVersion)
263 nWalletMaxVersion = nVersion;
267 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
268 if (nWalletVersion > 40000)
269 pwalletdb->WriteMinVersion(nWalletVersion);
277 bool CWallet::SetMaxVersion(int nVersion)
279 // cannot downgrade below current version
280 if (nWalletVersion > nVersion)
283 nWalletMaxVersion = nVersion;
288 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
293 CKeyingMaterial vMasterKey;
294 RandAddSeedPerfmon();
296 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
297 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
299 CMasterKey kMasterKey;
301 RandAddSeedPerfmon();
302 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
303 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
306 int64_t nStartTime = GetTimeMillis();
307 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
308 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
310 nStartTime = GetTimeMillis();
311 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
312 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
314 if (kMasterKey.nDeriveIterations < 25000)
315 kMasterKey.nDeriveIterations = 25000;
317 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
319 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
321 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
326 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
329 pwalletdbEncryption = new CWalletDB(strWalletFile);
330 if (!pwalletdbEncryption->TxnBegin())
332 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
335 if (!EncryptKeys(vMasterKey))
338 pwalletdbEncryption->TxnAbort();
339 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.
342 // Encryption was introduced in version 0.4.0
343 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
347 if (!pwalletdbEncryption->TxnCommit())
348 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.
350 delete pwalletdbEncryption;
351 pwalletdbEncryption = NULL;
355 Unlock(strWalletPassphrase);
359 // Need to completely rewrite the wallet file; if we don't, bdb might keep
360 // bits of the unencrypted private key in slack space in the database file.
361 CDB::Rewrite(strWalletFile);
364 NotifyStatusChanged(this);
369 bool CWallet::DecryptWallet(const SecureString& strWalletPassphrase)
375 CKeyingMaterial vMasterKey;
379 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
381 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
383 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
385 if (!CCryptoKeyStore::Unlock(vMasterKey))
391 pwalletdbDecryption = new CWalletDB(strWalletFile);
392 if (!pwalletdbDecryption->TxnBegin())
396 if (!DecryptKeys(vMasterKey))
399 pwalletdbDecryption->TxnAbort();
400 exit(1); //We now probably have half of our keys decrypted in memory, and half not...die and let the user reload their encrypted wallet.
405 // Overwrite crypted keys
406 KeyMap::const_iterator mi = mapKeys.begin();
407 while (mi != mapKeys.end())
410 key.SetSecret((*mi).second.first, (*mi).second.second);
411 pwalletdbDecryption->EraseCryptedKey(key.GetPubKey());
412 pwalletdbDecryption->WriteKey(key.GetPubKey(), key.GetPrivKey(), mapKeyMetadata[(*mi).first]);
417 MasterKeyMap::const_iterator mk = mapMasterKeys.begin();
418 while (mk != mapMasterKeys.end())
420 pwalletdbDecryption->EraseMasterKey((*mk).first);
424 if (!pwalletdbDecryption->TxnCommit())
425 exit(1); //We now have keys decrypted in memory, but no on disk...die to avoid confusion and let the user reload their encrypted wallet.
427 delete pwalletdbDecryption;
428 pwalletdbDecryption = NULL;
431 // Need to completely rewrite the wallet file; if we don't, bdb might keep
432 // encrypted private keys in the database file which can be a reason of consistency issues.
433 CDB::Rewrite(strWalletFile);
435 NotifyStatusChanged(this);
440 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
442 int64_t nRet = nOrderPosNext++;
444 pwalletdb->WriteOrderPosNext(nOrderPosNext);
446 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
451 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
453 CWalletDB walletdb(strWalletFile);
455 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
458 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
459 // would make this much faster for applications that do this a lot.
460 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
462 CWalletTx* wtx = &((*it).second);
463 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
466 walletdb.ListAccountCreditDebit(strAccount, acentries);
467 BOOST_FOREACH(CAccountingEntry& entry, acentries)
469 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
475 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
477 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
478 // Update the wallet spent flag if it doesn't know due to wallet.dat being
479 // restored from backup or the user making copies of wallet.dat.
482 BOOST_FOREACH(const CTxIn& txin, tx.vin)
484 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
485 if (mi != mapWallet.end())
487 CWalletTx& wtx = (*mi).second;
488 if (txin.prevout.n >= wtx.vout.size())
489 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
490 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
492 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
493 wtx.MarkSpent(txin.prevout.n);
495 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
496 vMintingWalletUpdated.push_back(txin.prevout.hash);
503 uint256 hash = tx.GetHash();
504 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
505 CWalletTx& wtx = (*mi).second;
507 BOOST_FOREACH(const CTxOut& txout, tx.vout)
511 wtx.MarkUnspent(&txout - &tx.vout[0]);
513 NotifyTransactionChanged(this, hash, CT_UPDATED);
514 vMintingWalletUpdated.push_back(hash);
522 void CWallet::MarkDirty()
526 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
527 item.second.MarkDirty();
531 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
533 uint256 hash = wtxIn.GetHash();
536 // Inserts only if not already there, returns tx inserted or tx found
537 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
538 CWalletTx& wtx = (*ret.first).second;
539 wtx.BindWallet(this);
540 bool fInsertedNew = ret.second;
543 wtx.nTimeReceived = GetAdjustedTime();
544 wtx.nOrderPos = IncOrderPosNext();
546 wtx.nTimeSmart = wtx.nTimeReceived;
547 if (wtxIn.hashBlock != 0)
549 if (mapBlockIndex.count(wtxIn.hashBlock))
551 unsigned int latestNow = wtx.nTimeReceived;
552 unsigned int latestEntry = 0;
554 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
555 int64_t latestTolerated = latestNow + 300;
556 std::list<CAccountingEntry> acentries;
557 TxItems txOrdered = OrderedTxItems(acentries);
558 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
560 CWalletTx *const pwtx = (*it).second.first;
563 CAccountingEntry *const pacentry = (*it).second.second;
567 nSmartTime = pwtx->nTimeSmart;
569 nSmartTime = pwtx->nTimeReceived;
572 nSmartTime = pacentry->nTime;
573 if (nSmartTime <= latestTolerated)
575 latestEntry = nSmartTime;
576 if (nSmartTime > latestNow)
577 latestNow = nSmartTime;
583 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
584 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
587 printf("AddToWallet() : found %s in block %s not in index\n",
588 wtxIn.GetHash().ToString().substr(0,10).c_str(),
589 wtxIn.hashBlock.ToString().c_str());
593 bool fUpdated = false;
597 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
599 wtx.hashBlock = wtxIn.hashBlock;
602 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
604 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
605 wtx.nIndex = wtxIn.nIndex;
608 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
610 wtx.fFromMe = wtxIn.fFromMe;
613 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
617 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
620 if (fInsertedNew || fUpdated)
621 if (!wtx.WriteToDisk())
624 // If default receiving address gets used, replace it with a new one
625 CScript scriptDefaultKey;
626 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
627 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
629 if (txout.scriptPubKey == scriptDefaultKey)
631 CPubKey newDefaultKey;
632 if (GetKeyFromPool(newDefaultKey, false))
634 SetDefaultKey(newDefaultKey);
635 SetAddressBookName(vchDefaultKey.GetID(), "");
640 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
641 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
643 // Notify UI of new or updated transaction
644 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
645 vMintingWalletUpdated.push_back(hash);
646 // notify an external script when a wallet transaction comes in or is updated
647 std::string strCmd = GetArg("-walletnotify", "");
649 if ( !strCmd.empty())
651 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
652 boost::thread t(runCommand, strCmd); // thread runs free
659 // Add a transaction to the wallet, or update it.
660 // pblock is optional, but should be provided if the transaction is known to be in a block.
661 // If fUpdate is true, existing transactions will be updated.
662 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
664 uint256 hash = tx.GetHash();
667 bool fExisted = mapWallet.count(hash);
668 if (fExisted && !fUpdate) return false;
669 if (fExisted || IsMine(tx) || IsFromMe(tx))
671 CWalletTx wtx(this,tx);
672 // Get merkle branch if transaction was found in a block
674 wtx.SetMerkleBranch(pblock);
675 return AddToWallet(wtx);
678 WalletUpdateSpent(tx);
683 bool CWallet::EraseFromWallet(uint256 hash)
689 if (mapWallet.erase(hash))
690 CWalletDB(strWalletFile).EraseTx(hash);
696 isminetype CWallet::IsMine(const CTxIn &txin) const
700 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
701 if (mi != mapWallet.end())
703 const CWalletTx& prev = (*mi).second;
704 if (txin.prevout.n < prev.vout.size())
705 return IsMine(prev.vout[txin.prevout.n]);
711 int64_t CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
715 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
716 if (mi != mapWallet.end())
718 const CWalletTx& prev = (*mi).second;
719 if (txin.prevout.n < prev.vout.size())
720 if (IsMine(prev.vout[txin.prevout.n]) & filter)
721 return prev.vout[txin.prevout.n].nValue;
727 bool CWallet::IsChange(const CTxOut& txout) const
729 // TODO: fix handling of 'change' outputs. The assumption is that any
730 // payment to a script that is ours, but isn't in the address book
731 // is change. That assumption is likely to break when we implement multisignature
732 // wallets that return change back into a multi-signature-protected address;
733 // a better way of identifying which outputs are 'the send' and which are
734 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
735 // which output, if any, was change).
736 if (::IsMine(*this, txout.scriptPubKey))
738 CTxDestination address;
739 if (!ExtractDestination(txout.scriptPubKey, address))
743 if (!mapAddressBook.count(address))
749 int64_t CWalletTx::GetTxTime() const
754 int CWalletTx::GetRequestCount() const
756 // Returns -1 if it wasn't being tracked
759 LOCK(pwallet->cs_wallet);
760 if (IsCoinBase() || IsCoinStake())
765 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
766 if (mi != pwallet->mapRequestCount.end())
767 nRequests = (*mi).second;
772 // Did anyone request this transaction?
773 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
774 if (mi != pwallet->mapRequestCount.end())
776 nRequests = (*mi).second;
778 // How about the block it's in?
779 if (nRequests == 0 && hashBlock != 0)
781 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
782 if (mi != pwallet->mapRequestCount.end())
783 nRequests = (*mi).second;
785 nRequests = 1; // If it's in someone else's block it must have got out
793 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CTxDestination, int64_t> >& listReceived,
794 list<pair<CTxDestination, int64_t> >& listSent, int64_t& nFee, string& strSentAccount, const isminefilter& filter) const
796 nGeneratedImmature = nGeneratedMature = nFee = 0;
797 listReceived.clear();
799 strSentAccount = strFromAccount;
801 if (IsCoinBase() || IsCoinStake())
803 if (GetBlocksToMaturity() > 0)
804 nGeneratedImmature = pwallet->GetCredit(*this, filter);
806 nGeneratedMature = GetCredit(filter);
811 int64_t nDebit = GetDebit(filter);
812 if (nDebit > 0) // debit>0 means we signed/sent this transaction
814 int64_t nValueOut = GetValueOut();
815 nFee = nDebit - nValueOut;
819 BOOST_FOREACH(const CTxOut& txout, vout)
821 isminetype fIsMine = pwallet->IsMine(txout);
822 // Only need to handle txouts if AT LEAST one of these is true:
823 // 1) they debit from us (sent)
824 // 2) the output is to us (received)
827 // Don't report 'change' txouts
828 if (pwallet->IsChange(txout))
831 else if (!(fIsMine & filter))
834 // In either case, we need to get the destination address
835 CTxDestination address;
836 if (!ExtractDestination(txout.scriptPubKey, address))
838 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
839 this->GetHash().ToString().c_str());
840 address = CNoDestination();
843 // If we are debited by the transaction, add the output as a "sent" entry
845 listSent.push_back(make_pair(address, txout.nValue));
847 // If we are receiving the output, add it as a "received" entry
848 if (fIsMine & filter)
849 listReceived.push_back(make_pair(address, txout.nValue));
854 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
855 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const
857 nGenerated = nReceived = nSent = nFee = 0;
859 int64_t allGeneratedImmature, allGeneratedMature, allFee;
860 allGeneratedImmature = allGeneratedMature = allFee = 0;
861 string strSentAccount;
862 list<pair<CTxDestination, int64_t> > listReceived;
863 list<pair<CTxDestination, int64_t> > listSent;
864 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
866 if (strAccount == "")
867 nGenerated = allGeneratedMature;
868 if (strAccount == strSentAccount)
870 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& s, listSent)
875 LOCK(pwallet->cs_wallet);
876 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived)
878 if (pwallet->mapAddressBook.count(r.first))
880 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
881 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
882 nReceived += r.second;
884 else if (strAccount.empty())
886 nReceived += r.second;
892 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
896 const int COPY_DEPTH = 3;
897 if (SetMerkleBranch() < COPY_DEPTH)
899 vector<uint256> vWorkQueue;
900 BOOST_FOREACH(const CTxIn& txin, vin)
901 vWorkQueue.push_back(txin.prevout.hash);
903 // This critsect is OK because txdb is already open
905 LOCK(pwallet->cs_wallet);
906 map<uint256, const CMerkleTx*> mapWalletPrev;
907 set<uint256> setAlreadyDone;
908 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
910 uint256 hash = vWorkQueue[i];
911 if (setAlreadyDone.count(hash))
913 setAlreadyDone.insert(hash);
916 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
917 if (mi != pwallet->mapWallet.end())
920 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
921 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
923 else if (mapWalletPrev.count(hash))
925 tx = *mapWalletPrev[hash];
927 else if (!fClient && txdb.ReadDiskTx(hash, tx))
933 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
937 int nDepth = tx.SetMerkleBranch();
938 vtxPrev.push_back(tx);
940 if (nDepth < COPY_DEPTH)
942 BOOST_FOREACH(const CTxIn& txin, tx.vin)
943 vWorkQueue.push_back(txin.prevout.hash);
949 reverse(vtxPrev.begin(), vtxPrev.end());
952 bool CWalletTx::WriteToDisk()
954 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
957 // Scan the block chain (starting in pindexStart) for transactions
958 // from or to us. If fUpdate is true, found transactions that already
959 // exist in the wallet will be updated.
960 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
964 CBlockIndex* pindex = pindexStart;
970 block.ReadFromDisk(pindex, true);
971 BOOST_FOREACH(CTransaction& tx, block.vtx)
973 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
976 pindex = pindex->pnext;
982 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
985 tx.ReadFromDisk(COutPoint(hashTx, 0));
986 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
991 void CWallet::ReacceptWalletTransactions()
999 vector<CDiskTxPos> vMissingTx;
1000 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1002 CWalletTx& wtx = item.second;
1003 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
1007 bool fUpdated = false;
1008 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
1010 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
1011 if (txindex.vSpent.size() != wtx.vout.size())
1013 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
1016 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
1020 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
1024 vMissingTx.push_back(txindex.vSpent[i]);
1029 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
1036 // Re-accept any txes of ours that aren't already in a block
1037 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
1038 wtx.AcceptWalletTransaction(txdb, false);
1041 if (!vMissingTx.empty())
1043 // TODO: optimize this to scan just part of the block chain?
1044 if (ScanForWalletTransactions(pindexGenesisBlock))
1045 fRepeat = true; // Found missing transactions: re-do re-accept.
1050 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
1052 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
1054 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1056 uint256 hash = tx.GetHash();
1057 if (!txdb.ContainsTx(hash))
1058 RelayTransaction((CTransaction)tx, hash);
1061 if (!(IsCoinBase() || IsCoinStake()))
1063 uint256 hash = GetHash();
1064 if (!txdb.ContainsTx(hash))
1066 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
1067 RelayTransaction((CTransaction)*this, hash);
1072 void CWalletTx::RelayWalletTransaction()
1075 RelayWalletTransaction(txdb);
1078 void CWallet::ResendWalletTransactions()
1080 // Do this infrequently and randomly to avoid giving away
1081 // that these are our transactions.
1082 static int64_t nNextTime = GetRand(GetTime() + 30 * 60);
1083 if (GetTime() < nNextTime)
1085 bool fFirst = (nNextTime == 0);
1086 nNextTime = GetTime() + GetRand(30 * 60);
1090 // Only do it if there's been a new block since last time
1091 static int64_t nLastTime = 0;
1092 if (nTimeBestReceived < nLastTime)
1094 nLastTime = GetTime();
1096 // Rebroadcast any of our txes that aren't in a block yet
1097 printf("ResendWalletTransactions()\n");
1101 // Sort them in chronological order
1102 multimap<unsigned int, CWalletTx*> mapSorted;
1103 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1105 CWalletTx& wtx = item.second;
1106 // Don't rebroadcast until it's had plenty of time that
1107 // it should have gotten in already by now.
1108 if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
1109 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1111 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1113 CWalletTx& wtx = *item.second;
1114 if (wtx.CheckTransaction())
1115 wtx.RelayWalletTransaction(txdb);
1117 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1127 //////////////////////////////////////////////////////////////////////////////
1133 int64_t CWallet::GetBalance() const
1138 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1140 const CWalletTx* pcoin = &(*it).second;
1141 if (pcoin->IsTrusted())
1142 nTotal += pcoin->GetAvailableCredit();
1149 int64_t CWallet::GetWatchOnlyBalance() const
1154 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1156 const CWalletTx* pcoin = &(*it).second;
1157 if (pcoin->IsTrusted())
1158 nTotal += pcoin->GetAvailableWatchCredit();
1165 int64_t CWallet::GetUnconfirmedBalance() const
1170 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1172 const CWalletTx* pcoin = &(*it).second;
1173 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1174 nTotal += pcoin->GetAvailableCredit();
1180 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1185 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1187 const CWalletTx* pcoin = &(*it).second;
1188 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1189 nTotal += pcoin->GetAvailableWatchCredit();
1195 int64_t CWallet::GetImmatureBalance() const
1200 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1202 const CWalletTx* pcoin = &(*it).second;
1203 nTotal += pcoin->GetImmatureCredit();
1209 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1214 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1216 const CWalletTx* pcoin = &(*it).second;
1217 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1223 // populate vCoins with vector of spendable COutputs
1224 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1230 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1232 const CWalletTx* pcoin = &(*it).second;
1234 if (!pcoin->IsFinal())
1237 if (fOnlyConfirmed && !pcoin->IsTrusted())
1240 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1243 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1246 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1247 isminetype mine = IsMine(pcoin->vout[i]);
1248 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1249 pcoin->vout[i].nValue >= nMinimumInputValue &&
1250 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1252 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1259 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1265 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1267 const CWalletTx* pcoin = &(*it).second;
1269 if (!pcoin->IsFinal())
1272 if(pcoin->GetDepthInMainChain() < nConf)
1275 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1276 isminetype mine = IsMine(pcoin->vout[i]);
1278 // ignore coin if it was already spent or we don't own it
1279 if (pcoin->IsSpent(i) || mine == MINE_NO)
1282 // if coin value is between required limits then add new item to vector
1283 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1284 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1290 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1291 vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1293 vector<char> vfIncluded;
1295 vfBest.assign(vValue.size(), true);
1296 nBest = nTotalLower;
1298 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1300 vfIncluded.assign(vValue.size(), false);
1302 bool fReachedTarget = false;
1303 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1305 for (unsigned int i = 0; i < vValue.size(); i++)
1307 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1309 nTotal += vValue[i].first;
1310 vfIncluded[i] = true;
1311 if (nTotal >= nTargetValue)
1313 fReachedTarget = true;
1317 vfBest = vfIncluded;
1319 nTotal -= vValue[i].first;
1320 vfIncluded[i] = false;
1328 int64_t CWallet::GetStake() const
1332 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1334 const CWalletTx* pcoin = &(*it).second;
1335 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1336 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1341 int64_t CWallet::GetWatchOnlyStake() const
1345 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1347 const CWalletTx* pcoin = &(*it).second;
1348 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1349 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1354 int64_t CWallet::GetNewMint() const
1358 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1360 const CWalletTx* pcoin = &(*it).second;
1361 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1362 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1367 int64_t CWallet::GetWatchOnlyNewMint() const
1371 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1373 const CWalletTx* pcoin = &(*it).second;
1374 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1375 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1380 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
1382 setCoinsRet.clear();
1385 // List of values less than target
1386 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1387 coinLowestLarger.first = std::numeric_limits<int64_t>::max();
1388 coinLowestLarger.second.first = NULL;
1389 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1390 int64_t nTotalLower = 0;
1392 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1394 BOOST_FOREACH(const COutput &output, vCoins)
1396 if (!output.fSpendable)
1399 const CWalletTx *pcoin = output.tx;
1401 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1406 // Follow the timestamp rules
1407 if (pcoin->nTime > nSpendTime)
1410 int64_t n = pcoin->vout[i].nValue;
1412 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1414 if (n == nTargetValue)
1416 setCoinsRet.insert(coin.second);
1417 nValueRet += coin.first;
1420 else if (n < nTargetValue + CENT)
1422 vValue.push_back(coin);
1425 else if (n < coinLowestLarger.first)
1427 coinLowestLarger = coin;
1431 if (nTotalLower == nTargetValue)
1433 for (unsigned int i = 0; i < vValue.size(); ++i)
1435 setCoinsRet.insert(vValue[i].second);
1436 nValueRet += vValue[i].first;
1441 if (nTotalLower < nTargetValue)
1443 if (coinLowestLarger.second.first == NULL)
1445 setCoinsRet.insert(coinLowestLarger.second);
1446 nValueRet += coinLowestLarger.first;
1450 // Solve subset sum by stochastic approximation
1451 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1452 vector<char> vfBest;
1455 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1456 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1457 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1459 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1460 // or the next bigger coin is closer), return the bigger coin
1461 if (coinLowestLarger.second.first &&
1462 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1464 setCoinsRet.insert(coinLowestLarger.second);
1465 nValueRet += coinLowestLarger.first;
1468 for (unsigned int i = 0; i < vValue.size(); i++)
1471 setCoinsRet.insert(vValue[i].second);
1472 nValueRet += vValue[i].first;
1475 if (fDebug && GetBoolArg("-printpriority"))
1478 printf("SelectCoins() best subset: ");
1479 for (unsigned int i = 0; i < vValue.size(); i++)
1481 printf("%s ", FormatMoney(vValue[i].first).c_str());
1482 printf("total %s\n", FormatMoney(nBest).c_str());
1489 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
1491 vector<COutput> vCoins;
1492 AvailableCoins(vCoins, true, coinControl);
1494 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1495 if (coinControl && coinControl->HasSelected())
1497 BOOST_FOREACH(const COutput& out, vCoins)
1501 nValueRet += out.tx->vout[out.i].nValue;
1502 setCoinsRet.insert(make_pair(out.tx, out.i));
1504 return (nValueRet >= nTargetValue);
1507 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1508 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1509 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1512 // Select some coins without random shuffle or best subset approximation
1513 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
1515 vector<COutput> vCoins;
1516 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1518 setCoinsRet.clear();
1521 BOOST_FOREACH(COutput output, vCoins)
1523 if(!output.fSpendable)
1525 const CWalletTx *pcoin = output.tx;
1528 // Ignore immature coins
1529 if (pcoin->GetBlocksToMaturity() > 0)
1532 // Stop if we've chosen enough inputs
1533 if (nValueRet >= nTargetValue)
1536 // Follow the timestamp rules
1537 if (pcoin->nTime > nSpendTime)
1540 int64_t n = pcoin->vout[i].nValue;
1542 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1544 if (n >= nTargetValue)
1546 // If input value is greater or equal to target then simply insert
1547 // it into the current subset and exit
1548 setCoinsRet.insert(coin.second);
1549 nValueRet += coin.first;
1552 else if (n < nTargetValue + CENT)
1554 setCoinsRet.insert(coin.second);
1555 nValueRet += coin.first;
1562 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1565 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1571 if (vecSend.empty() || nValue < 0)
1574 wtxNew.BindWallet(this);
1577 LOCK2(cs_main, cs_wallet);
1578 // txdb must be opened before the mapWallet lock
1581 nFeeRet = nTransactionFee;
1585 wtxNew.vout.clear();
1586 wtxNew.fFromMe = true;
1588 int64_t nTotalValue = nValue + nFeeRet;
1589 double dPriority = 0;
1590 // vouts to the payees
1591 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1592 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1594 // Choose coins to use
1595 set<pair<const CWalletTx*,unsigned int> > setCoins;
1596 int64_t nValueIn = 0;
1597 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1599 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1601 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1602 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1605 int64_t nChange = nValueIn - nValue - nFeeRet;
1608 // Fill a vout to ourself
1609 // TODO: pass in scriptChange instead of reservekey so
1610 // change transaction isn't always pay-to-bitcoin-address
1611 CScript scriptChange;
1613 // coin control: send change to custom address
1614 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1615 scriptChange.SetDestination(coinControl->destChange);
1617 // no coin control: send change to newly generated address
1620 // Note: We use a new key here to keep it from being obvious which side is the change.
1621 // The drawback is that by not reusing a previous key, the change may be lost if a
1622 // backup is restored, if the backup doesn't have the new private key for the change.
1623 // If we reused the old key, it would be possible to add code to look for and
1624 // rediscover unknown transactions that were written with keys of ours to recover
1625 // post-backup change.
1627 // Reserve a new key pair from key pool
1628 CPubKey vchPubKey = reservekey.GetReservedKey();
1630 scriptChange.SetDestination(vchPubKey.GetID());
1633 // Insert change txn at random position:
1634 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1635 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1638 reservekey.ReturnKey();
1641 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1642 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1646 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1647 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1651 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1652 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1654 dPriority /= nBytes;
1656 // Check that enough fee is included
1657 bool fAllowFree = CTransaction::AllowFree(dPriority);
1658 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
1659 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1661 if (nFeeRet < max(nPayFee, nMinFee))
1663 nFeeRet = max(nPayFee, nMinFee);
1667 // Fill vtxPrev by copying from previous transactions vtxPrev
1668 wtxNew.AddSupportingTransactions(txdb);
1669 wtxNew.fTimeReceivedIsTxTime = true;
1678 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1680 vector< pair<CScript, int64_t> > vecSend;
1681 vecSend.push_back(make_pair(scriptPubKey, nValue));
1682 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1685 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
1687 int64_t nTimeWeight = GetWeight(nTime, (int64_t)GetTime());
1689 // If time weight is lower or equal to zero then weight is zero.
1690 if (nTimeWeight <= 0)
1696 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1697 nWeight = bnCoinDayWeight.getuint64();
1700 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
1702 int64_t nBalance = GetBalance();
1704 if (nAmount > nBalance)
1708 int64_t nValueIn = 0;
1709 set<pair<const CWalletTx*,unsigned int> > setCoins;
1711 // Simple coins selection - no randomization
1712 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
1715 if (setCoins.empty())
1719 vector<const CWalletTx*> vwtxPrev;
1721 // Reserve a new key pair from key pool
1722 CReserveKey reservekey(this);
1723 CPubKey vchPubKey = reservekey.GetReservedKey();
1726 CScript scriptOutput;
1727 scriptOutput.SetDestination(vchPubKey.GetID());
1730 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1733 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1735 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1737 // Add current coin to inputs list and add its credit to transaction output
1738 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1739 wtxNew.vout[0].nValue += nCredit;
1740 vwtxPrev.push_back(pcoin.first);
1743 // Replaced with estimation for performance purposes
1745 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1746 const CWalletTx *txin = vwtxPrev[i];
1748 // Sign scripts to get actual transaction size for fee calculation
1749 if (!SignSignature(*this, *txin, wtxNew, i))
1754 // Assuming that average scriptsig size is 110 bytes
1755 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1756 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1758 double dFinalPriority = dWeight /= nBytes;
1759 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1761 // Get actual transaction fee according to its estimated size and priority
1762 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1764 // Prepare transaction for commit if sum is enough ot its size is too big
1765 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1767 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1769 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1770 const CWalletTx *txin = vwtxPrev[i];
1773 if (!SignSignature(*this, *txin, wtxNew, i))
1777 // Try to commit, return false on failure
1778 if (!CommitTransaction(wtxNew, reservekey))
1781 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1783 dWeight = 0; // Reset all temporary values
1786 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1790 // Create transactions if there are some unhandled coins left
1791 if (wtxNew.vout[0].nValue > 0) {
1792 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1794 double dFinalPriority = dWeight /= nBytes;
1795 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1797 // Get actual transaction fee according to its size and priority
1798 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1800 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1802 if (wtxNew.vout[0].nValue <= 0)
1805 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1806 const CWalletTx *txin = vwtxPrev[i];
1808 // Sign all scripts again
1809 if (!SignSignature(*this, *txin, wtxNew, i))
1813 // Try to commit, return false on failure
1814 if (!CommitTransaction(wtxNew, reservekey))
1817 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1823 bool CWallet::CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nGenerationTime, uint32_t nBits, CTransaction &txNew, CKey& key)
1826 if (!GetTransaction(hashTx, wtx))
1827 return error("Transaction %s is not found\n", hashTx.GetHex().c_str());
1829 vector<valtype> vSolutions;
1830 txnouttype whichType;
1831 CScript scriptPubKeyOut;
1832 CScript scriptPubKeyKernel = wtx.vout[nOut].scriptPubKey;
1833 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1834 return error("CreateCoinStake : failed to parse kernel\n");
1836 if (fDebug && GetBoolArg("-printcoinstake"))
1837 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1839 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1840 return error("CreateCoinStake : no support for kernel type=%d\n", whichType);
1842 if (whichType == TX_PUBKEYHASH) // pay to address type
1844 // convert to pay to public key type
1845 if (!GetKey(uint160(vSolutions[0]), key))
1846 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1848 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1850 if (whichType == TX_PUBKEY)
1852 valtype& vchPubKey = vSolutions[0];
1853 if (!GetKey(Hash160(vchPubKey), key))
1854 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1855 if (key.GetPubKey() != vchPubKey)
1856 return error("CreateCoinStake : invalid key for kernel type=%d\n", whichType); // keys mismatch
1857 scriptPubKeyOut = scriptPubKeyKernel;
1860 // The following combine threshold is important to security
1861 // Should not be adjusted if you don't understand the consequences
1862 int64_t nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1864 int64_t nBalance = GetBalance();
1865 int64_t nCredit = wtx.vout[nOut].nValue;
1870 // List of constake dependencies
1871 vector<const CWalletTx*> vwtxPrev;
1872 vwtxPrev.push_back(&wtx);
1874 // Set generation time, and kernel input
1875 txNew.nTime = nGenerationTime;
1876 txNew.vin.push_back(CTxIn(hashTx, nOut));
1878 // Mark coin stake transaction with empty vout[0]
1879 CScript scriptEmpty;
1880 scriptEmpty.clear();
1881 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1883 if (fDebug && GetBoolArg("-printcoinstake"))
1884 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1886 int64_t nValueIn = 0;
1888 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, nGenerationTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1891 if (setCoins.empty())
1894 bool fMaxTimeWeight = false;
1895 if (GetWeight((int64_t)wtx.nTime, (int64_t)nGenerationTime) == nStakeMaxAge)
1897 // Only one output for old kernel inputs
1898 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1900 // Iterate through set of (wtx*, nout) in order to find some additional inputs for our new coinstake transaction.
1902 // * Value is higher than 0.01 NVC;
1903 // * Only add inputs of the same key/address as kernel;
1904 // * Input hash and kernel parent hash should be different.
1905 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1907 // Stop adding more inputs if already too many inputs
1908 if (txNew.vin.size() >= 100)
1910 // Stop adding more inputs if value is already pretty significant
1911 if (nCredit > nCombineThreshold)
1913 // Stop adding inputs if reached reserve limit
1914 if (nCredit + pcoin->first->vout[pcoin->second].nValue > nBalance - nReserveBalance)
1917 int64_t nTimeWeight = GetWeight((int64_t)pcoin->first->nTime, (int64_t)nGenerationTime);
1919 // Do not add input that is still too young
1920 if (nTimeWeight < nStakeMaxAge)
1922 // Do not add input if key/address is not the same as kernel
1923 if (pcoin->first->vout[pcoin->second].scriptPubKey != scriptPubKeyKernel && pcoin->first->vout[pcoin->second].scriptPubKey != txNew.vout[1].scriptPubKey)
1925 // Do not add input if parents are the same
1926 if (pcoin->first->GetHash() != txNew.vin[0].prevout.hash)
1928 // Do not add additional significant input
1929 if (pcoin->first->vout[pcoin->second].nValue > nCombineThreshold)
1932 txNew.vin.push_back(CTxIn(pcoin->first->GetHash(), pcoin->second));
1933 nCredit += pcoin->first->vout[pcoin->second].nValue;
1934 vwtxPrev.push_back(pcoin->first);
1937 fMaxTimeWeight = true;
1941 // Split stake input if maximum weight isn't reached yet
1942 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1943 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1945 if (fDebug && GetBoolArg("-printcoinstake"))
1946 printf("CreateCoinStake : maximum time weight isn't reached, splitting coinstake\n");
1949 // Calculate coin age reward
1952 if (!txNew.GetCoinAge(txdb, nCoinAge))
1953 return error("CreateCoinStake : failed to calculate coin age\n");
1954 nCredit += GetProofOfStakeReward(nCoinAge, nBits, nGenerationTime);
1956 int64_t nMinFee = 0;
1959 // Set output amount
1961 txNew.vout[1].nValue = nCredit - nMinFee;
1964 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1965 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1970 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1972 if (!SignSignature(*this, *pcoin, txNew, nIn++))
1973 return error("CreateCoinStake : failed to sign coinstake\n");
1977 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1978 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1979 return error("CreateCoinStake : exceeded coinstake size limit\n");
1981 // Check enough fee is paid
1982 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
1984 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
1985 continue; // try signing again
1989 if (fDebug && GetBoolArg("-printfee"))
1990 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1995 // Successfully created coinstake
1999 // Call after CreateTransaction unless you want to abort
2000 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2003 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2005 // Track how many getdata requests our transaction gets
2006 mapRequestCount[wtxNew.GetHash()] = 0;
2008 // Try to broadcast before saving
2009 if (!wtxNew.AcceptToMemoryPool())
2011 // This must not fail. The transaction has already been signed.
2012 printf("CommitTransaction() : Error: Transaction not valid");
2016 wtxNew.RelayWalletTransaction();
2019 LOCK2(cs_main, cs_wallet);
2021 // This is only to keep the database open to defeat the auto-flush for the
2022 // duration of this scope. This is the only place where this optimization
2023 // maybe makes sense; please don't do it anywhere else.
2024 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2026 // Take key pair from key pool so it won't be used again
2027 reservekey.KeepKey();
2029 // Add tx to wallet, because if it has change it's also ours,
2030 // otherwise just for transaction history.
2031 AddToWallet(wtxNew);
2033 // Mark old coins as spent
2034 set<CWalletTx*> setCoins;
2035 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2037 CWalletTx &coin = mapWallet[txin.prevout.hash];
2038 coin.BindWallet(this);
2039 coin.MarkSpent(txin.prevout.n);
2041 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2042 vMintingWalletUpdated.push_back(coin.GetHash());
2055 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2057 CReserveKey reservekey(this);
2058 int64_t nFeeRequired;
2062 string strError = _("Error: Wallet locked, unable to create transaction ");
2063 printf("SendMoney() : %s", strError.c_str());
2066 if (fWalletUnlockMintOnly)
2068 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2069 printf("SendMoney() : %s", strError.c_str());
2072 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2075 if (nValue + nFeeRequired > GetBalance())
2076 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());
2078 strError = _("Error: Transaction creation failed ");
2079 printf("SendMoney() : %s", strError.c_str());
2083 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2086 if (!CommitTransaction(wtxNew, reservekey))
2087 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.");
2094 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2098 return _("Invalid amount");
2099 if (nValue + nTransactionFee > GetBalance())
2100 return _("Insufficient funds");
2102 // Parse Bitcoin address
2103 CScript scriptPubKey;
2104 scriptPubKey.SetDestination(address);
2106 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2112 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2116 fFirstRunRet = false;
2117 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2118 if (nLoadWalletRet == DB_NEED_REWRITE)
2120 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2123 // Note: can't top-up keypool here, because wallet is locked.
2124 // User will be prompted to unlock wallet the next operation
2125 // the requires a new key.
2129 if (nLoadWalletRet != DB_LOAD_OK)
2130 return nLoadWalletRet;
2131 fFirstRunRet = !vchDefaultKey.IsValid();
2133 NewThread(ThreadFlushWalletDB, &strWalletFile);
2137 DBErrors CWallet::ZapWalletTx()
2141 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this);
2142 if (nZapWalletTxRet == DB_NEED_REWRITE)
2144 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2148 // Note: can't top-up keypool here, because wallet is locked.
2149 // User will be prompted to unlock wallet the next operation
2150 // the requires a new key.
2154 if (nZapWalletTxRet != DB_LOAD_OK)
2155 return nZapWalletTxRet;
2160 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2162 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2163 mapAddressBook[address] = strName;
2164 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2167 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2170 bool CWallet::DelAddressBookName(const CTxDestination& address)
2172 mapAddressBook.erase(address);
2173 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2176 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2180 void CWallet::PrintWallet(const CBlock& block)
2184 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2186 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2187 printf(" PoS: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2189 else if (mapWallet.count(block.vtx[0].GetHash()))
2191 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2192 printf(" PoW: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2198 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2202 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2203 if (mi != mapWallet.end())
2212 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2216 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2219 vchDefaultKey = vchPubKey;
2223 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2225 if (!pwallet->fFileBacked)
2227 strWalletFileOut = pwallet->strWalletFile;
2232 // Mark old keypool keys as used,
2233 // and generate all new keys
2235 bool CWallet::NewKeyPool(unsigned int nSize)
2239 CWalletDB walletdb(strWalletFile);
2240 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2241 walletdb.ErasePool(nIndex);
2251 nKeys = max<uint64_t>(GetArg("-keypool", 100), 0);
2253 for (uint64_t i = 0; i < nKeys; i++)
2255 uint64_t nIndex = i+1;
2256 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2257 setKeyPool.insert(nIndex);
2259 printf("CWallet::NewKeyPool wrote %" PRIu64 " new keys\n", nKeys);
2264 bool CWallet::TopUpKeyPool(unsigned int nSize)
2272 CWalletDB walletdb(strWalletFile);
2275 uint64_t nTargetSize;
2277 nTargetSize = nSize;
2279 nTargetSize = max<uint64_t>(GetArg("-keypool", 100), 0);
2281 while (setKeyPool.size() < (nTargetSize + 1))
2284 if (!setKeyPool.empty())
2285 nEnd = *(--setKeyPool.end()) + 1;
2286 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2287 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2288 setKeyPool.insert(nEnd);
2289 printf("keypool added key %" PRIu64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2295 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2298 keypool.vchPubKey = CPubKey();
2305 // Get the oldest key
2306 if(setKeyPool.empty())
2309 CWalletDB walletdb(strWalletFile);
2311 nIndex = *(setKeyPool.begin());
2312 setKeyPool.erase(setKeyPool.begin());
2313 if (!walletdb.ReadPool(nIndex, keypool))
2314 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2315 if (!HaveKey(keypool.vchPubKey.GetID()))
2316 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2317 assert(keypool.vchPubKey.IsValid());
2318 if (fDebug && GetBoolArg("-printkeypool"))
2319 printf("keypool reserve %" PRId64 "\n", nIndex);
2323 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2326 LOCK2(cs_main, cs_wallet);
2327 CWalletDB walletdb(strWalletFile);
2329 int64_t nIndex = 1 + *(--setKeyPool.end());
2330 if (!walletdb.WritePool(nIndex, keypool))
2331 throw runtime_error("AddReserveKey() : writing added key failed");
2332 setKeyPool.insert(nIndex);
2338 void CWallet::KeepKey(int64_t nIndex)
2340 // Remove from key pool
2343 CWalletDB walletdb(strWalletFile);
2344 walletdb.ErasePool(nIndex);
2347 printf("keypool keep %" PRId64 "\n", nIndex);
2350 void CWallet::ReturnKey(int64_t nIndex)
2352 // Return to key pool
2355 setKeyPool.insert(nIndex);
2358 printf("keypool return %" PRId64 "\n", nIndex);
2361 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2367 ReserveKeyFromKeyPool(nIndex, keypool);
2370 if (fAllowReuse && vchDefaultKey.IsValid())
2372 result = vchDefaultKey;
2375 if (IsLocked()) return false;
2376 result = GenerateNewKey();
2380 result = keypool.vchPubKey;
2385 int64_t CWallet::GetOldestKeyPoolTime()
2389 ReserveKeyFromKeyPool(nIndex, keypool);
2393 return keypool.nTime;
2396 std::map<CTxDestination, int64_t> CWallet::GetAddressBalances()
2398 map<CTxDestination, int64_t> balances;
2402 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2404 CWalletTx *pcoin = &walletEntry.second;
2406 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2409 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2412 int nDepth = pcoin->GetDepthInMainChain();
2413 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2416 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2418 CTxDestination addr;
2419 if (!IsMine(pcoin->vout[i]))
2421 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2424 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2426 if (!balances.count(addr))
2428 balances[addr] += n;
2436 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2438 set< set<CTxDestination> > groupings;
2439 set<CTxDestination> grouping;
2441 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2443 CWalletTx *pcoin = &walletEntry.second;
2445 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2447 // group all input addresses with each other
2448 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2450 CTxDestination address;
2451 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2453 grouping.insert(address);
2456 // group change with input addresses
2457 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2458 if (IsChange(txout))
2460 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2461 CTxDestination txoutAddr;
2462 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2464 grouping.insert(txoutAddr);
2466 groupings.insert(grouping);
2470 // group lone addrs by themselves
2471 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2472 if (IsMine(pcoin->vout[i]))
2474 CTxDestination address;
2475 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2477 grouping.insert(address);
2478 groupings.insert(grouping);
2483 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2484 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2485 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2487 // make a set of all the groups hit by this new group
2488 set< set<CTxDestination>* > hits;
2489 map< CTxDestination, set<CTxDestination>* >::iterator it;
2490 BOOST_FOREACH(CTxDestination address, grouping)
2491 if ((it = setmap.find(address)) != setmap.end())
2492 hits.insert((*it).second);
2494 // merge all hit groups into a new single group and delete old groups
2495 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2496 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2498 merged->insert(hit->begin(), hit->end());
2499 uniqueGroupings.erase(hit);
2502 uniqueGroupings.insert(merged);
2505 BOOST_FOREACH(CTxDestination element, *merged)
2506 setmap[element] = merged;
2509 set< set<CTxDestination> > ret;
2510 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2512 ret.insert(*uniqueGrouping);
2513 delete uniqueGrouping;
2519 // ppcoin: check 'spent' consistency between wallet and txindex
2520 // ppcoin: fix wallet spent state according to txindex
2521 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
2524 nBalanceInQuestion = 0;
2527 vector<CWalletTx*> vCoins;
2528 vCoins.reserve(mapWallet.size());
2529 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2530 vCoins.push_back(&(*it).second);
2533 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2535 // Find the corresponding transaction index
2537 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2539 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2541 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2543 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2544 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2546 nBalanceInQuestion += pcoin->vout[n].nValue;
2549 pcoin->MarkUnspent(n);
2550 pcoin->WriteToDisk();
2553 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2555 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2556 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2558 nBalanceInQuestion += pcoin->vout[n].nValue;
2561 pcoin->MarkSpent(n);
2562 pcoin->WriteToDisk();
2568 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2570 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2573 EraseFromWallet(pcoin->GetHash());
2579 // ppcoin: disable transaction (only for coinstake)
2580 void CWallet::DisableTransaction(const CTransaction &tx)
2582 if (!tx.IsCoinStake() || !IsFromMe(tx))
2583 return; // only disconnecting coinstake requires marking input unspent
2586 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2588 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2589 if (mi != mapWallet.end())
2591 CWalletTx& prev = (*mi).second;
2592 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2594 prev.MarkUnspent(txin.prevout.n);
2601 CPubKey CReserveKey::GetReservedKey()
2606 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2608 vchPubKey = keypool.vchPubKey;
2611 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2612 vchPubKey = pwallet->vchDefaultKey;
2615 assert(vchPubKey.IsValid());
2619 void CReserveKey::KeepKey()
2622 pwallet->KeepKey(nIndex);
2624 vchPubKey = CPubKey();
2627 void CReserveKey::ReturnKey()
2630 pwallet->ReturnKey(nIndex);
2632 vchPubKey = CPubKey();
2635 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2639 CWalletDB walletdb(strWalletFile);
2641 LOCK2(cs_main, cs_wallet);
2642 BOOST_FOREACH(const int64_t& id, setKeyPool)
2645 if (!walletdb.ReadPool(id, keypool))
2646 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2647 assert(keypool.vchPubKey.IsValid());
2648 CKeyID keyID = keypool.vchPubKey.GetID();
2649 if (!HaveKey(keyID))
2650 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2651 setAddress.insert(keyID);
2655 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2659 // Only notify UI if this transaction is in this wallet
2660 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2661 if (mi != mapWallet.end())
2663 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2664 vMintingWalletUpdated.push_back(hashTx);
2669 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2670 mapKeyBirth.clear();
2672 // get birth times for keys with metadata
2673 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2674 if (it->second.nCreateTime)
2675 mapKeyBirth[it->first] = it->second.nCreateTime;
2677 // map in which we'll infer heights of other keys
2678 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2679 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2680 std::set<CKeyID> setKeys;
2682 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2683 if (mapKeyBirth.count(keyid) == 0)
2684 mapKeyFirstBlock[keyid] = pindexMax;
2688 // if there are no such keys, we're done
2689 if (mapKeyFirstBlock.empty())
2692 // find first block that affects those keys, if there are any left
2693 std::vector<CKeyID> vAffected;
2694 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2695 // iterate over all wallet transactions...
2696 const CWalletTx &wtx = (*it).second;
2697 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2698 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2699 // ... which are already in a block
2700 int nHeight = blit->second->nHeight;
2701 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2702 // iterate over all their outputs
2703 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2704 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2705 // ... and all their affected keys
2706 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2707 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2708 rit->second = blit->second;
2715 // Extract block timestamps for those keys
2716 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2717 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2720 void CWallet::ClearOrphans()
2722 list<uint256> orphans;
2725 for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2727 const CWalletTx *wtx = &(*it).second;
2728 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
2730 orphans.push_back(wtx->GetHash());
2734 for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
2735 EraseFromWallet(*it);