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 CMalleableKeyView CWallet::GenerateNewMalleableKey()
64 // Compressed public keys were introduced in version 0.6.0
65 SetMinVersion(FEATURE_MALLKEY);
69 const CMalleableKeyView &keyView(mKey);
71 // Create new metadata
72 int64_t nCreationTime = GetTime();
73 mapMalleableKeyMetadata[keyView] = CKeyMetadata(nCreationTime);
74 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
75 nTimeFirstKey = nCreationTime;
77 if (!AddMalleableKey(mKey))
78 throw std::runtime_error("CWallet::GenerateNewMalleableKey() : AddMalleableKey failed");
79 return CMalleableKeyView(mKey);
82 bool CWallet::AddKey(const CKey& key)
84 CPubKey pubkey = key.GetPubKey();
85 if (!CCryptoKeyStore::AddKey(key))
90 return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
94 bool CWallet::AddMalleableKey(const CMalleableKey& mKey)
96 CMalleableKeyView keyView = CMalleableKeyView(mKey);
97 if (!CCryptoKeyStore::AddMalleableKey(mKey))
102 return CWalletDB(strWalletFile).WriteMalleableKey(keyView, mKey, mapMalleableKeyMetadata[keyView]);
106 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
108 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
111 // check if we need to remove from watch-only
113 script.SetDestination(vchPubKey.GetID());
114 if (HaveWatchOnly(script))
115 RemoveWatchOnly(script);
121 if (pwalletdbEncryption)
122 return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
124 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
129 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
131 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
132 nTimeFirstKey = meta.nCreateTime;
134 mapKeyMetadata[pubkey.GetID()] = meta;
138 bool CWallet::LoadMalleableKeyMetadata(const CMalleableKeyView &keyView, const CKeyMetadata &metadata)
140 if (metadata.nCreateTime && (!nTimeFirstKey || metadata.nCreateTime < nTimeFirstKey))
141 nTimeFirstKey = metadata.nCreateTime;
143 mapMalleableKeyMetadata[keyView] = metadata;
147 bool CWallet::AddCScript(const CScript& redeemScript)
149 if (!CCryptoKeyStore::AddCScript(redeemScript))
153 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
156 bool CWallet::LoadCScript(const CScript& redeemScript)
158 /* A sanity check was added in commit 5ed0a2b to avoid adding redeemScripts
159 * that never can be redeemed. However, old wallets may still contain
160 * these. Do not add them to the wallet and warn. */
161 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
163 std::string strAddr = CBitcoinAddress(redeemScript.GetID()).ToString();
164 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",
165 redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr.c_str());
169 return CCryptoKeyStore::AddCScript(redeemScript);
173 bool CWallet::AddWatchOnly(const CScript &dest)
175 if (!CCryptoKeyStore::AddWatchOnly(dest))
177 nTimeFirstKey = 1; // No birthday information for watch-only keys.
178 NotifyWatchonlyChanged(true);
181 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
184 bool CWallet::RemoveWatchOnly(const CScript &dest)
187 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
189 if (!HaveWatchOnly())
190 NotifyWatchonlyChanged(false);
192 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
198 bool CWallet::LoadWatchOnly(const CScript &dest)
200 return CCryptoKeyStore::AddWatchOnly(dest);
203 // ppcoin: optional setting to unlock wallet for block minting only;
204 // serves to disable the trivial sendmoney when OS account compromised
205 bool fWalletUnlockMintOnly = false;
207 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
213 CKeyingMaterial vMasterKey;
217 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
219 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
221 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
223 if (CCryptoKeyStore::Unlock(vMasterKey))
230 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
232 bool fWasLocked = IsLocked();
239 CKeyingMaterial vMasterKey;
240 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
242 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
244 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
246 if (CCryptoKeyStore::Unlock(vMasterKey))
248 int64_t nStartTime = GetTimeMillis();
249 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
250 double nFirstMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
251 pMasterKey.second.nDeriveIterations = (uint32_t)(pMasterKey.second.nDeriveIterations *nFirstMultiplier);
253 nStartTime = GetTimeMillis();
254 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
255 double nSecondMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
256 pMasterKey.second.nDeriveIterations = (uint32_t)((pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * nSecondMultiplier) / 2);
258 if (pMasterKey.second.nDeriveIterations < 25000)
259 pMasterKey.second.nDeriveIterations = 25000;
261 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
263 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
265 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
267 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
278 void CWallet::SetBestChain(const CBlockLocator& loc)
280 CWalletDB walletdb(strWalletFile);
281 walletdb.WriteBestBlock(loc);
284 // This class implements an addrIncoming entry that causes pre-0.4
285 // clients to crash on startup if reading a private-key-encrypted wallet.
286 class CCorruptAddress
291 if (nType & SER_DISK)
296 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
298 if (nWalletVersion >= nVersion)
301 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
302 if (fExplicit && nVersion > nWalletMaxVersion)
303 nVersion = FEATURE_LATEST;
305 nWalletVersion = nVersion;
307 if (nVersion > nWalletMaxVersion)
308 nWalletMaxVersion = nVersion;
312 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
313 if (nWalletVersion > 40000)
314 pwalletdb->WriteMinVersion(nWalletVersion);
322 bool CWallet::SetMaxVersion(int nVersion)
324 // cannot downgrade below current version
325 if (nWalletVersion > nVersion)
328 nWalletMaxVersion = nVersion;
333 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
338 CKeyingMaterial vMasterKey;
339 RandAddSeedPerfmon();
341 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
342 RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
344 CMasterKey kMasterKey;
346 RandAddSeedPerfmon();
347 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
348 RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
351 int64_t nStartTime = GetTimeMillis();
352 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
353 int64_t nDivider = GetTimeMillis() - nStartTime;
354 kMasterKey.nDeriveIterations = (uint32_t)(25e5 / (double)(nDivider));
356 nStartTime = GetTimeMillis();
357 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
358 double nMultiplier = 1e2 / (GetTimeMillis() - nStartTime);
359 kMasterKey.nDeriveIterations = (uint32_t)((kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * nMultiplier) / 2);
361 if (kMasterKey.nDeriveIterations < 25000)
362 kMasterKey.nDeriveIterations = 25000;
364 printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
366 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
368 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
373 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
376 pwalletdbEncryption = new CWalletDB(strWalletFile);
377 if (!pwalletdbEncryption->TxnBegin())
379 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
382 if (!EncryptKeys(vMasterKey))
385 pwalletdbEncryption->TxnAbort();
386 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.
389 // Encryption was introduced in version 0.4.0
390 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
394 if (!pwalletdbEncryption->TxnCommit())
395 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.
397 delete pwalletdbEncryption;
398 pwalletdbEncryption = NULL;
402 Unlock(strWalletPassphrase);
406 // Need to completely rewrite the wallet file; if we don't, bdb might keep
407 // bits of the unencrypted private key in slack space in the database file.
408 CDB::Rewrite(strWalletFile);
411 NotifyStatusChanged(this);
416 bool CWallet::DecryptWallet(const SecureString& strWalletPassphrase)
422 CKeyingMaterial vMasterKey;
426 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
428 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
430 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
432 if (!CCryptoKeyStore::Unlock(vMasterKey))
438 pwalletdbDecryption = new CWalletDB(strWalletFile);
439 if (!pwalletdbDecryption->TxnBegin())
443 if (!DecryptKeys(vMasterKey))
446 pwalletdbDecryption->TxnAbort();
447 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.
452 // Overwrite crypted keys
453 KeyMap::const_iterator mi = mapKeys.begin();
454 while (mi != mapKeys.end())
457 key.SetSecret((*mi).second.first, (*mi).second.second);
458 pwalletdbDecryption->EraseCryptedKey(key.GetPubKey());
459 pwalletdbDecryption->WriteKey(key.GetPubKey(), key.GetPrivKey(), mapKeyMetadata[(*mi).first]);
464 MasterKeyMap::const_iterator mk = mapMasterKeys.begin();
465 while (mk != mapMasterKeys.end())
467 pwalletdbDecryption->EraseMasterKey((*mk).first);
471 if (!pwalletdbDecryption->TxnCommit())
472 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.
474 delete pwalletdbDecryption;
475 pwalletdbDecryption = NULL;
478 // Need to completely rewrite the wallet file; if we don't, bdb might keep
479 // encrypted private keys in the database file which can be a reason of consistency issues.
480 CDB::Rewrite(strWalletFile);
482 NotifyStatusChanged(this);
487 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
489 int64_t nRet = nOrderPosNext++;
491 pwalletdb->WriteOrderPosNext(nOrderPosNext);
493 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
498 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
500 CWalletDB walletdb(strWalletFile);
502 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
505 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
506 // would make this much faster for applications that do this a lot.
507 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
509 CWalletTx* wtx = &((*it).second);
510 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
513 walletdb.ListAccountCreditDebit(strAccount, acentries);
514 BOOST_FOREACH(CAccountingEntry& entry, acentries)
516 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
522 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
524 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
525 // Update the wallet spent flag if it doesn't know due to wallet.dat being
526 // restored from backup or the user making copies of wallet.dat.
529 BOOST_FOREACH(const CTxIn& txin, tx.vin)
531 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
532 if (mi != mapWallet.end())
534 CWalletTx& wtx = (*mi).second;
535 if (txin.prevout.n >= wtx.vout.size())
536 printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
537 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
539 printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
540 wtx.MarkSpent(txin.prevout.n);
542 NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
543 vMintingWalletUpdated.push_back(txin.prevout.hash);
550 uint256 hash = tx.GetHash();
551 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
552 CWalletTx& wtx = (*mi).second;
554 BOOST_FOREACH(const CTxOut& txout, tx.vout)
558 wtx.MarkUnspent(&txout - &tx.vout[0]);
560 NotifyTransactionChanged(this, hash, CT_UPDATED);
561 vMintingWalletUpdated.push_back(hash);
569 void CWallet::MarkDirty()
573 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
574 item.second.MarkDirty();
578 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
580 uint256 hash = wtxIn.GetHash();
583 // Inserts only if not already there, returns tx inserted or tx found
584 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
585 CWalletTx& wtx = (*ret.first).second;
586 wtx.BindWallet(this);
587 bool fInsertedNew = ret.second;
590 wtx.nTimeReceived = GetAdjustedTime();
591 wtx.nOrderPos = IncOrderPosNext();
593 wtx.nTimeSmart = wtx.nTimeReceived;
594 if (wtxIn.hashBlock != 0)
596 if (mapBlockIndex.count(wtxIn.hashBlock))
598 unsigned int latestNow = wtx.nTimeReceived;
599 unsigned int latestEntry = 0;
601 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
602 int64_t latestTolerated = latestNow + 300;
603 std::list<CAccountingEntry> acentries;
604 TxItems txOrdered = OrderedTxItems(acentries);
605 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
607 CWalletTx *const pwtx = (*it).second.first;
610 CAccountingEntry *const pacentry = (*it).second.second;
614 nSmartTime = pwtx->nTimeSmart;
616 nSmartTime = pwtx->nTimeReceived;
619 nSmartTime = pacentry->nTime;
620 if (nSmartTime <= latestTolerated)
622 latestEntry = nSmartTime;
623 if (nSmartTime > latestNow)
624 latestNow = nSmartTime;
630 unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
631 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
634 printf("AddToWallet() : found %s in block %s not in index\n",
635 wtxIn.GetHash().ToString().substr(0,10).c_str(),
636 wtxIn.hashBlock.ToString().c_str());
640 bool fUpdated = false;
644 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
646 wtx.hashBlock = wtxIn.hashBlock;
649 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
651 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
652 wtx.nIndex = wtxIn.nIndex;
655 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
657 wtx.fFromMe = wtxIn.fFromMe;
660 fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
664 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
667 if (fInsertedNew || fUpdated)
668 if (!wtx.WriteToDisk())
671 // If default receiving address gets used, replace it with a new one
672 CScript scriptDefaultKey;
673 scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
674 BOOST_FOREACH(const CTxOut& txout, wtx.vout)
676 if (txout.scriptPubKey == scriptDefaultKey)
678 CPubKey newDefaultKey;
679 if (GetKeyFromPool(newDefaultKey, false))
681 SetDefaultKey(newDefaultKey);
682 SetAddressBookName(vchDefaultKey.GetID(), "");
687 // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
688 WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
690 // Notify UI of new or updated transaction
691 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
692 vMintingWalletUpdated.push_back(hash);
693 // notify an external script when a wallet transaction comes in or is updated
694 std::string strCmd = GetArg("-walletnotify", "");
696 if ( !strCmd.empty())
698 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
699 boost::thread t(runCommand, strCmd); // thread runs free
706 // Add a transaction to the wallet, or update it.
707 // pblock is optional, but should be provided if the transaction is known to be in a block.
708 // If fUpdate is true, existing transactions will be updated.
709 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
711 uint256 hash = tx.GetHash();
714 bool fExisted = mapWallet.count(hash) != 0;
715 if (fExisted && !fUpdate) return false;
716 if (fExisted || IsMine(tx) || IsFromMe(tx))
718 CWalletTx wtx(this,tx);
719 // Get merkle branch if transaction was found in a block
721 wtx.SetMerkleBranch(pblock);
722 return AddToWallet(wtx);
725 WalletUpdateSpent(tx);
730 bool CWallet::EraseFromWallet(uint256 hash)
736 if (mapWallet.erase(hash))
737 CWalletDB(strWalletFile).EraseTx(hash);
743 isminetype CWallet::IsMine(const CTxIn &txin) const
747 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
748 if (mi != mapWallet.end())
750 const CWalletTx& prev = (*mi).second;
751 if (txin.prevout.n < prev.vout.size())
752 return IsMine(prev.vout[txin.prevout.n]);
758 int64_t CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
762 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
763 if (mi != mapWallet.end())
765 const CWalletTx& prev = (*mi).second;
766 if (txin.prevout.n < prev.vout.size())
767 if (IsMine(prev.vout[txin.prevout.n]) & filter)
768 return prev.vout[txin.prevout.n].nValue;
774 bool CWallet::IsChange(const CTxOut& txout) const
776 // TODO: fix handling of 'change' outputs. The assumption is that any
777 // payment to a script that is ours, but isn't in the address book
778 // is change. That assumption is likely to break when we implement multisignature
779 // wallets that return change back into a multi-signature-protected address;
780 // a better way of identifying which outputs are 'the send' and which are
781 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
782 // which output, if any, was change).
783 if (::IsMine(*this, txout.scriptPubKey))
785 CTxDestination address;
786 if (!ExtractDestination(txout.scriptPubKey, address))
790 if (!mapAddressBook.count(address))
796 int64_t CWalletTx::GetTxTime() const
801 int CWalletTx::GetRequestCount() const
803 // Returns -1 if it wasn't being tracked
806 LOCK(pwallet->cs_wallet);
807 if (IsCoinBase() || IsCoinStake())
812 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
813 if (mi != pwallet->mapRequestCount.end())
814 nRequests = (*mi).second;
819 // Did anyone request this transaction?
820 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
821 if (mi != pwallet->mapRequestCount.end())
823 nRequests = (*mi).second;
825 // How about the block it's in?
826 if (nRequests == 0 && hashBlock != 0)
828 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
829 if (mi != pwallet->mapRequestCount.end())
830 nRequests = (*mi).second;
832 nRequests = 1; // If it's in someone else's block it must have got out
840 void CWalletTx::GetAmounts(int64_t& nGeneratedImmature, int64_t& nGeneratedMature, list<pair<CTxDestination, int64_t> >& listReceived,
841 list<pair<CTxDestination, int64_t> >& listSent, int64_t& nFee, string& strSentAccount, const isminefilter& filter) const
843 nGeneratedImmature = nGeneratedMature = nFee = 0;
844 listReceived.clear();
846 strSentAccount = strFromAccount;
848 if (IsCoinBase() || IsCoinStake())
850 if (GetBlocksToMaturity() > 0)
851 nGeneratedImmature = pwallet->GetCredit(*this, filter);
853 nGeneratedMature = GetCredit(filter);
858 int64_t nDebit = GetDebit(filter);
859 if (nDebit > 0) // debit>0 means we signed/sent this transaction
861 int64_t nValueOut = GetValueOut();
862 nFee = nDebit - nValueOut;
866 BOOST_FOREACH(const CTxOut& txout, vout)
868 isminetype fIsMine = pwallet->IsMine(txout);
869 // Only need to handle txouts if AT LEAST one of these is true:
870 // 1) they debit from us (sent)
871 // 2) the output is to us (received)
874 // Don't report 'change' txouts
875 if (pwallet->IsChange(txout))
878 else if (!(fIsMine & filter))
881 // In either case, we need to get the destination address
882 CTxDestination address;
883 if (!ExtractDestination(txout.scriptPubKey, address))
885 printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
886 this->GetHash().ToString().c_str());
887 address = CNoDestination();
890 // If we are debited by the transaction, add the output as a "sent" entry
892 listSent.push_back(make_pair(address, txout.nValue));
894 // If we are receiving the output, add it as a "received" entry
895 if (fIsMine & filter)
896 listReceived.push_back(make_pair(address, txout.nValue));
901 void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nGenerated, int64_t& nReceived,
902 int64_t& nSent, int64_t& nFee, const isminefilter& filter) const
904 nGenerated = nReceived = nSent = nFee = 0;
906 int64_t allGeneratedImmature, allGeneratedMature, allFee;
907 allGeneratedImmature = allGeneratedMature = allFee = 0;
908 string strSentAccount;
909 list<pair<CTxDestination, int64_t> > listReceived;
910 list<pair<CTxDestination, int64_t> > listSent;
911 GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount, filter);
913 if (strAccount == "")
914 nGenerated = allGeneratedMature;
915 if (strAccount == strSentAccount)
917 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& s, listSent)
922 LOCK(pwallet->cs_wallet);
923 BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived)
925 if (pwallet->mapAddressBook.count(r.first))
927 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
928 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
929 nReceived += r.second;
931 else if (strAccount.empty())
933 nReceived += r.second;
939 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
943 const int COPY_DEPTH = 3;
944 if (SetMerkleBranch() < COPY_DEPTH)
946 vector<uint256> vWorkQueue;
947 BOOST_FOREACH(const CTxIn& txin, vin)
948 vWorkQueue.push_back(txin.prevout.hash);
950 // This critsect is OK because txdb is already open
952 LOCK(pwallet->cs_wallet);
953 map<uint256, const CMerkleTx*> mapWalletPrev;
954 set<uint256> setAlreadyDone;
955 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
957 uint256 hash = vWorkQueue[i];
958 if (setAlreadyDone.count(hash))
960 setAlreadyDone.insert(hash);
963 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
964 if (mi != pwallet->mapWallet.end())
967 BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
968 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
970 else if (mapWalletPrev.count(hash))
972 tx = *mapWalletPrev[hash];
974 else if (!fClient && txdb.ReadDiskTx(hash, tx))
980 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
984 int nDepth = tx.SetMerkleBranch();
985 vtxPrev.push_back(tx);
987 if (nDepth < COPY_DEPTH)
989 BOOST_FOREACH(const CTxIn& txin, tx.vin)
990 vWorkQueue.push_back(txin.prevout.hash);
996 reverse(vtxPrev.begin(), vtxPrev.end());
999 bool CWalletTx::WriteToDisk()
1001 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
1004 // Scan the block chain (starting in pindexStart) for transactions
1005 // from or to us. If fUpdate is true, found transactions that already
1006 // exist in the wallet will be updated.
1007 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1011 CBlockIndex* pindex = pindexStart;
1017 block.ReadFromDisk(pindex, true);
1018 BOOST_FOREACH(CTransaction& tx, block.vtx)
1020 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1023 pindex = pindex->pnext;
1029 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
1032 tx.ReadFromDisk(COutPoint(hashTx, 0));
1033 if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
1038 void CWallet::ReacceptWalletTransactions()
1041 bool fRepeat = true;
1046 vector<CDiskTxPos> vMissingTx;
1047 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1049 CWalletTx& wtx = item.second;
1050 if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
1054 bool fUpdated = false;
1055 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
1057 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
1058 if (txindex.vSpent.size() != wtx.vout.size())
1060 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
1063 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
1067 if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
1071 vMissingTx.push_back(txindex.vSpent[i]);
1076 printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(MINE_ALL)).c_str(), wtx.GetHash().ToString().c_str());
1083 // Re-accept any txes of ours that aren't already in a block
1084 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
1085 wtx.AcceptWalletTransaction(txdb, false);
1088 if (!vMissingTx.empty())
1090 // TODO: optimize this to scan just part of the block chain?
1091 if (ScanForWalletTransactions(pindexGenesisBlock))
1092 fRepeat = true; // Found missing transactions: re-do re-accept.
1097 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
1099 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
1101 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1103 uint256 hash = tx.GetHash();
1104 if (!txdb.ContainsTx(hash))
1105 RelayTransaction((CTransaction)tx, hash);
1108 if (!(IsCoinBase() || IsCoinStake()))
1110 uint256 hash = GetHash();
1111 if (!txdb.ContainsTx(hash))
1113 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
1114 RelayTransaction((CTransaction)*this, hash);
1119 void CWalletTx::RelayWalletTransaction()
1122 RelayWalletTransaction(txdb);
1125 void CWallet::ResendWalletTransactions()
1127 // Do this infrequently and randomly to avoid giving away
1128 // that these are our transactions.
1129 static int64_t nNextTime = GetRand(GetTime() + 30 * 60);
1130 if (GetTime() < nNextTime)
1132 bool fFirst = (nNextTime == 0);
1133 nNextTime = GetTime() + GetRand(30 * 60);
1137 // Only do it if there's been a new block since last time
1138 static int64_t nLastTime = 0;
1139 if (nTimeBestReceived < nLastTime)
1141 nLastTime = GetTime();
1143 // Rebroadcast any of our txes that aren't in a block yet
1144 printf("ResendWalletTransactions()\n");
1148 // Sort them in chronological order
1149 multimap<unsigned int, CWalletTx*> mapSorted;
1150 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1152 CWalletTx& wtx = item.second;
1153 // Don't rebroadcast until it's had plenty of time that
1154 // it should have gotten in already by now.
1155 if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
1156 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1158 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1160 CWalletTx& wtx = *item.second;
1161 if (wtx.CheckTransaction())
1162 wtx.RelayWalletTransaction(txdb);
1164 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1174 //////////////////////////////////////////////////////////////////////////////
1180 int64_t CWallet::GetBalance() const
1185 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1187 const CWalletTx* pcoin = &(*it).second;
1188 if (pcoin->IsTrusted())
1189 nTotal += pcoin->GetAvailableCredit();
1196 int64_t CWallet::GetWatchOnlyBalance() const
1201 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1203 const CWalletTx* pcoin = &(*it).second;
1204 if (pcoin->IsTrusted())
1205 nTotal += pcoin->GetAvailableWatchCredit();
1212 int64_t CWallet::GetUnconfirmedBalance() const
1217 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1219 const CWalletTx* pcoin = &(*it).second;
1220 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1221 nTotal += pcoin->GetAvailableCredit();
1227 int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const
1232 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1234 const CWalletTx* pcoin = &(*it).second;
1235 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
1236 nTotal += pcoin->GetAvailableWatchCredit();
1242 int64_t CWallet::GetImmatureBalance() const
1247 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1249 const CWalletTx* pcoin = &(*it).second;
1250 nTotal += pcoin->GetImmatureCredit();
1256 int64_t CWallet::GetImmatureWatchOnlyBalance() const
1261 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1263 const CWalletTx* pcoin = &(*it).second;
1264 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1270 // populate vCoins with vector of spendable COutputs
1271 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1277 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1279 const CWalletTx* pcoin = &(*it).second;
1281 if (!pcoin->IsFinal())
1284 if (fOnlyConfirmed && !pcoin->IsTrusted())
1287 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1290 if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1293 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1294 isminetype mine = IsMine(pcoin->vout[i]);
1295 if (!(pcoin->IsSpent(i)) && mine != MINE_NO &&
1296 pcoin->vout[i].nValue >= nMinimumInputValue &&
1297 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1299 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1306 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf, int64_t nMinValue, int64_t nMaxValue) const
1312 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1314 const CWalletTx* pcoin = &(*it).second;
1316 if (!pcoin->IsFinal())
1319 if(pcoin->GetDepthInMainChain() < nConf)
1322 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1323 isminetype mine = IsMine(pcoin->vout[i]);
1325 // ignore coin if it was already spent or we don't own it
1326 if (pcoin->IsSpent(i) || mine == MINE_NO)
1329 // if coin value is between required limits then add new item to vector
1330 if (pcoin->vout[i].nValue >= nMinValue && pcoin->vout[i].nValue < nMaxValue)
1331 vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1337 static void ApproximateBestSubset(vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > >vValue, int64_t nTotalLower, int64_t nTargetValue,
1338 vector<char>& vfBest, int64_t& nBest, int iterations = 1000)
1340 vector<char> vfIncluded;
1342 vfBest.assign(vValue.size(), true);
1343 nBest = nTotalLower;
1345 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1347 vfIncluded.assign(vValue.size(), false);
1349 bool fReachedTarget = false;
1350 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1352 for (unsigned int i = 0; i < vValue.size(); i++)
1354 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1356 nTotal += vValue[i].first;
1357 vfIncluded[i] = true;
1358 if (nTotal >= nTargetValue)
1360 fReachedTarget = true;
1364 vfBest = vfIncluded;
1366 nTotal -= vValue[i].first;
1367 vfIncluded[i] = false;
1375 int64_t CWallet::GetStake() const
1379 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1381 const CWalletTx* pcoin = &(*it).second;
1382 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1383 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1388 int64_t CWallet::GetWatchOnlyStake() const
1392 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1394 const CWalletTx* pcoin = &(*it).second;
1395 if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1396 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1401 int64_t CWallet::GetNewMint() const
1405 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1407 const CWalletTx* pcoin = &(*it).second;
1408 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1409 nTotal += CWallet::GetCredit(*pcoin, MINE_ALL);
1414 int64_t CWallet::GetWatchOnlyNewMint() const
1418 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1420 const CWalletTx* pcoin = &(*it).second;
1421 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1422 nTotal += CWallet::GetCredit(*pcoin, MINE_WATCH_ONLY);
1427 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
1429 setCoinsRet.clear();
1432 // List of values less than target
1433 pair<int64_t, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1434 coinLowestLarger.first = std::numeric_limits<int64_t>::max();
1435 coinLowestLarger.second.first = NULL;
1436 vector<pair<int64_t, pair<const CWalletTx*,unsigned int> > > vValue;
1437 int64_t nTotalLower = 0;
1439 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1441 BOOST_FOREACH(const COutput &output, vCoins)
1443 if (!output.fSpendable)
1446 const CWalletTx *pcoin = output.tx;
1448 if (output.nDepth < (pcoin->IsFromMe(MINE_ALL) ? nConfMine : nConfTheirs))
1453 // Follow the timestamp rules
1454 if (pcoin->nTime > nSpendTime)
1457 int64_t n = pcoin->vout[i].nValue;
1459 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1461 if (n == nTargetValue)
1463 setCoinsRet.insert(coin.second);
1464 nValueRet += coin.first;
1467 else if (n < nTargetValue + CENT)
1469 vValue.push_back(coin);
1472 else if (n < coinLowestLarger.first)
1474 coinLowestLarger = coin;
1478 if (nTotalLower == nTargetValue)
1480 for (unsigned int i = 0; i < vValue.size(); ++i)
1482 setCoinsRet.insert(vValue[i].second);
1483 nValueRet += vValue[i].first;
1488 if (nTotalLower < nTargetValue)
1490 if (coinLowestLarger.second.first == NULL)
1492 setCoinsRet.insert(coinLowestLarger.second);
1493 nValueRet += coinLowestLarger.first;
1497 // Solve subset sum by stochastic approximation
1498 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1499 vector<char> vfBest;
1502 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1503 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1504 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1506 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1507 // or the next bigger coin is closer), return the bigger coin
1508 if (coinLowestLarger.second.first &&
1509 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1511 setCoinsRet.insert(coinLowestLarger.second);
1512 nValueRet += coinLowestLarger.first;
1515 for (unsigned int i = 0; i < vValue.size(); i++)
1518 setCoinsRet.insert(vValue[i].second);
1519 nValueRet += vValue[i].first;
1522 if (fDebug && GetBoolArg("-printpriority"))
1525 printf("SelectCoins() best subset: ");
1526 for (unsigned int i = 0; i < vValue.size(); i++)
1528 printf("%s ", FormatMoney(vValue[i].first).c_str());
1529 printf("total %s\n", FormatMoney(nBest).c_str());
1536 bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const
1538 vector<COutput> vCoins;
1539 AvailableCoins(vCoins, true, coinControl);
1541 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1542 if (coinControl && coinControl->HasSelected())
1544 BOOST_FOREACH(const COutput& out, vCoins)
1548 nValueRet += out.tx->vout[out.i].nValue;
1549 setCoinsRet.insert(make_pair(out.tx, out.i));
1551 return (nValueRet >= nTargetValue);
1554 return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1555 SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1556 SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1559 // Select some coins without random shuffle or best subset approximation
1560 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
1562 vector<COutput> vCoins;
1563 AvailableCoinsMinConf(vCoins, nMinConf, nMinValue, nMaxValue);
1565 setCoinsRet.clear();
1568 BOOST_FOREACH(COutput output, vCoins)
1570 if(!output.fSpendable)
1572 const CWalletTx *pcoin = output.tx;
1575 // Ignore immature coins
1576 if (pcoin->GetBlocksToMaturity() > 0)
1579 // Stop if we've chosen enough inputs
1580 if (nValueRet >= nTargetValue)
1583 // Follow the timestamp rules
1584 if (pcoin->nTime > nSpendTime)
1587 int64_t n = pcoin->vout[i].nValue;
1589 pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1591 if (n >= nTargetValue)
1593 // If input value is greater or equal to target then simply insert
1594 // it into the current subset and exit
1595 setCoinsRet.insert(coin.second);
1596 nValueRet += coin.first;
1599 else if (n < nTargetValue + CENT)
1601 setCoinsRet.insert(coin.second);
1602 nValueRet += coin.first;
1609 bool CWallet::CreateTransaction(const vector<pair<CScript, int64_t> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1612 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1618 if (vecSend.empty() || nValue < 0)
1621 wtxNew.BindWallet(this);
1624 LOCK2(cs_main, cs_wallet);
1625 // txdb must be opened before the mapWallet lock
1628 nFeeRet = nTransactionFee;
1632 wtxNew.vout.clear();
1633 wtxNew.fFromMe = true;
1635 int64_t nTotalValue = nValue + nFeeRet;
1636 double dPriority = 0;
1637 // vouts to the payees
1638 BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend)
1639 wtxNew.vout.push_back(CTxOut(s.second, s.first));
1641 // Choose coins to use
1642 set<pair<const CWalletTx*,unsigned int> > setCoins;
1643 int64_t nValueIn = 0;
1644 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1646 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1648 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1649 dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1652 int64_t nChange = nValueIn - nValue - nFeeRet;
1655 // Fill a vout to ourself
1656 // TODO: pass in scriptChange instead of reservekey so
1657 // change transaction isn't always pay-to-bitcoin-address
1658 CScript scriptChange;
1660 // coin control: send change to custom address
1661 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1662 scriptChange.SetDestination(coinControl->destChange);
1664 // no coin control: send change to newly generated address
1667 // Note: We use a new key here to keep it from being obvious which side is the change.
1668 // The drawback is that by not reusing a previous key, the change may be lost if a
1669 // backup is restored, if the backup doesn't have the new private key for the change.
1670 // If we reused the old key, it would be possible to add code to look for and
1671 // rediscover unknown transactions that were written with keys of ours to recover
1672 // post-backup change.
1674 // Reserve a new key pair from key pool
1675 CPubKey vchPubKey = reservekey.GetReservedKey();
1677 scriptChange.SetDestination(vchPubKey.GetID());
1680 // Insert change txn at random position:
1681 vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1682 wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1685 reservekey.ReturnKey();
1688 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1689 wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1693 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1694 if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1698 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1699 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1701 dPriority /= nBytes;
1703 // Check that enough fee is included
1704 bool fAllowFree = CTransaction::AllowFree(dPriority);
1705 int64_t nPayFee = nTransactionFee * (1 + (int64_t)nBytes / 1000);
1706 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1708 if (nFeeRet < max(nPayFee, nMinFee))
1710 nFeeRet = max(nPayFee, nMinFee);
1714 // Fill vtxPrev by copying from previous transactions vtxPrev
1715 wtxNew.AddSupportingTransactions(txdb);
1716 wtxNew.fTimeReceivedIsTxTime = true;
1725 bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl)
1727 vector< pair<CScript, int64_t> > vecSend;
1728 vecSend.push_back(make_pair(scriptPubKey, nValue));
1729 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1732 void CWallet::GetStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight)
1734 int64_t nTimeWeight = GetWeight(nTime, GetTime());
1736 // If time weight is lower or equal to zero then weight is zero.
1737 if (nTimeWeight <= 0)
1743 CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / nOneDay;
1744 nWeight = bnCoinDayWeight.getuint64();
1747 bool CWallet::MergeCoins(const int64_t& nAmount, const int64_t& nMinValue, const int64_t& nOutputValue, list<uint256>& listMerged)
1749 int64_t nBalance = GetBalance();
1751 if (nAmount > nBalance)
1755 int64_t nValueIn = 0;
1756 set<pair<const CWalletTx*,unsigned int> > setCoins;
1758 // Simple coins selection - no randomization
1759 if (!SelectCoinsSimple(nAmount, nMinValue, nOutputValue, GetTime(), 1, setCoins, nValueIn))
1762 if (setCoins.empty())
1766 vector<const CWalletTx*> vwtxPrev;
1768 // Reserve a new key pair from key pool
1769 CReserveKey reservekey(this);
1770 CPubKey vchPubKey = reservekey.GetReservedKey();
1773 CScript scriptOutput;
1774 scriptOutput.SetDestination(vchPubKey.GetID());
1777 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1780 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1782 int64_t nCredit = pcoin.first->vout[pcoin.second].nValue;
1784 // Add current coin to inputs list and add its credit to transaction output
1785 wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1786 wtxNew.vout[0].nValue += nCredit;
1787 vwtxPrev.push_back(pcoin.first);
1790 // Replaced with estimation for performance purposes
1792 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1793 const CWalletTx *txin = vwtxPrev[i];
1795 // Sign scripts to get actual transaction size for fee calculation
1796 if (!SignSignature(*this, *txin, wtxNew, i))
1801 // Assuming that average scriptsig size is 110 bytes
1802 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1803 dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1805 double dFinalPriority = dWeight /= nBytes;
1806 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1808 // Get actual transaction fee according to its estimated size and priority
1809 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1811 // Prepare transaction for commit if sum is enough ot its size is too big
1812 if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1814 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1816 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1817 const CWalletTx *txin = vwtxPrev[i];
1820 if (!SignSignature(*this, *txin, wtxNew, i))
1824 // Try to commit, return false on failure
1825 if (!CommitTransaction(wtxNew, reservekey))
1828 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1830 dWeight = 0; // Reset all temporary values
1833 wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1837 // Create transactions if there are some unhandled coins left
1838 if (wtxNew.vout[0].nValue > 0) {
1839 int64_t nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1841 double dFinalPriority = dWeight /= nBytes;
1842 bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1844 // Get actual transaction fee according to its size and priority
1845 int64_t nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1847 wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1849 if (wtxNew.vout[0].nValue <= 0)
1852 for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1853 const CWalletTx *txin = vwtxPrev[i];
1855 // Sign all scripts again
1856 if (!SignSignature(*this, *txin, wtxNew, i))
1860 // Try to commit, return false on failure
1861 if (!CommitTransaction(wtxNew, reservekey))
1864 listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1870 bool CWallet::CreateCoinStake(uint256 &hashTx, uint32_t nOut, uint32_t nGenerationTime, uint32_t nBits, CTransaction &txNew, CKey& key)
1873 if (!GetTransaction(hashTx, wtx))
1874 return error("Transaction %s is not found\n", hashTx.GetHex().c_str());
1876 vector<valtype> vSolutions;
1877 txnouttype whichType;
1878 CScript scriptPubKeyOut;
1879 CScript scriptPubKeyKernel = wtx.vout[nOut].scriptPubKey;
1880 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1881 return error("CreateCoinStake : failed to parse kernel\n");
1883 if (fDebug && GetBoolArg("-printcoinstake"))
1884 printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1886 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1887 return error("CreateCoinStake : no support for kernel type=%d\n", whichType);
1889 if (whichType == TX_PUBKEYHASH) // pay to address type
1891 // convert to pay to public key type
1892 if (!GetKey(uint160(vSolutions[0]), key))
1893 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1895 scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1897 if (whichType == TX_PUBKEY)
1899 valtype& vchPubKey = vSolutions[0];
1900 if (!GetKey(Hash160(vchPubKey), key))
1901 return error("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1902 if (key.GetPubKey() != vchPubKey)
1903 return error("CreateCoinStake : invalid key for kernel type=%d\n", whichType); // keys mismatch
1904 scriptPubKeyOut = scriptPubKeyKernel;
1907 // The following combine threshold is important to security
1908 // Should not be adjusted if you don't understand the consequences
1909 int64_t nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1911 int64_t nBalance = GetBalance();
1912 int64_t nCredit = wtx.vout[nOut].nValue;
1917 // List of constake dependencies
1918 vector<const CWalletTx*> vwtxPrev;
1919 vwtxPrev.push_back(&wtx);
1921 // Set generation time, and kernel input
1922 txNew.nTime = nGenerationTime;
1923 txNew.vin.push_back(CTxIn(hashTx, nOut));
1925 // Mark coin stake transaction with empty vout[0]
1926 CScript scriptEmpty;
1927 scriptEmpty.clear();
1928 txNew.vout.push_back(CTxOut(0, scriptEmpty));
1930 if (fDebug && GetBoolArg("-printcoinstake"))
1931 printf("CreateCoinStake : added kernel type=%d\n", whichType);
1933 int64_t nValueIn = 0;
1935 if (!SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, nGenerationTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1938 if (setCoins.empty())
1941 bool fMaxTimeWeight = false;
1942 if (GetWeight((int64_t)wtx.nTime, (int64_t)nGenerationTime) == nStakeMaxAge)
1944 // Only one output for old kernel inputs
1945 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1947 // Iterate through set of (wtx*, nout) in order to find some additional inputs for our new coinstake transaction.
1949 // * Value is higher than 0.01 NVC;
1950 // * Only add inputs of the same key/address as kernel;
1951 // * Input hash and kernel parent hash should be different.
1952 for(CoinsSet::iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
1954 // Stop adding more inputs if already too many inputs
1955 if (txNew.vin.size() >= 100)
1957 // Stop adding more inputs if value is already pretty significant
1958 if (nCredit > nCombineThreshold)
1960 // Stop adding inputs if reached reserve limit
1961 if (nCredit + pcoin->first->vout[pcoin->second].nValue > nBalance - nReserveBalance)
1964 int64_t nTimeWeight = GetWeight((int64_t)pcoin->first->nTime, (int64_t)nGenerationTime);
1966 // Do not add input that is still too young
1967 if (nTimeWeight < nStakeMaxAge)
1969 // Do not add input if key/address is not the same as kernel
1970 if (pcoin->first->vout[pcoin->second].scriptPubKey != scriptPubKeyKernel && pcoin->first->vout[pcoin->second].scriptPubKey != txNew.vout[1].scriptPubKey)
1972 // Do not add input if parents are the same
1973 if (pcoin->first->GetHash() != txNew.vin[0].prevout.hash)
1975 // Do not add additional significant input
1976 if (pcoin->first->vout[pcoin->second].nValue > nCombineThreshold)
1979 txNew.vin.push_back(CTxIn(pcoin->first->GetHash(), pcoin->second));
1980 nCredit += pcoin->first->vout[pcoin->second].nValue;
1981 vwtxPrev.push_back(pcoin->first);
1984 fMaxTimeWeight = true;
1988 // Split stake input if maximum weight isn't reached yet
1989 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1990 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1992 if (fDebug && GetBoolArg("-printcoinstake"))
1993 printf("CreateCoinStake : maximum time weight isn't reached, splitting coinstake\n");
1996 // Calculate coin age reward
1999 if (!txNew.GetCoinAge(txdb, nCoinAge))
2000 return error("CreateCoinStake : failed to calculate coin age\n");
2001 nCredit += GetProofOfStakeReward(nCoinAge, nBits, nGenerationTime);
2003 int64_t nMinFee = 0;
2006 // Set output amount
2008 txNew.vout[1].nValue = nCredit - nMinFee;
2011 txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2012 txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2017 BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2019 if (!SignSignature(*this, *pcoin, txNew, nIn++))
2020 return error("CreateCoinStake : failed to sign coinstake\n");
2024 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2025 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2026 return error("CreateCoinStake : exceeded coinstake size limit\n");
2028 // Check enough fee is paid
2029 if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2031 nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2032 continue; // try signing again
2036 if (fDebug && GetBoolArg("-printfee"))
2037 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2042 // Successfully created coinstake
2046 // Call after CreateTransaction unless you want to abort
2047 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2050 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2052 // Track how many getdata requests our transaction gets
2053 mapRequestCount[wtxNew.GetHash()] = 0;
2055 // Try to broadcast before saving
2056 if (!wtxNew.AcceptToMemoryPool())
2058 // This must not fail. The transaction has already been signed.
2059 printf("CommitTransaction() : Error: Transaction not valid");
2063 wtxNew.RelayWalletTransaction();
2066 LOCK2(cs_main, cs_wallet);
2068 // This is only to keep the database open to defeat the auto-flush for the
2069 // duration of this scope. This is the only place where this optimization
2070 // maybe makes sense; please don't do it anywhere else.
2071 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2073 // Take key pair from key pool so it won't be used again
2074 reservekey.KeepKey();
2076 // Add tx to wallet, because if it has change it's also ours,
2077 // otherwise just for transaction history.
2078 AddToWallet(wtxNew);
2080 // Mark old coins as spent
2081 set<CWalletTx*> setCoins;
2082 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2084 CWalletTx &coin = mapWallet[txin.prevout.hash];
2085 coin.BindWallet(this);
2086 coin.MarkSpent(txin.prevout.n);
2088 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2089 vMintingWalletUpdated.push_back(coin.GetHash());
2102 string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2104 CReserveKey reservekey(this);
2105 int64_t nFeeRequired;
2109 string strError = _("Error: Wallet locked, unable to create transaction ");
2110 printf("SendMoney() : %s", strError.c_str());
2113 if (fWalletUnlockMintOnly)
2115 string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2116 printf("SendMoney() : %s", strError.c_str());
2119 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2122 if (nValue + nFeeRequired > GetBalance())
2123 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());
2125 strError = _("Error: Transaction creation failed ");
2126 printf("SendMoney() : %s", strError.c_str());
2130 if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2133 if (!CommitTransaction(wtxNew, reservekey))
2134 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.");
2141 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64_t nValue, CWalletTx& wtxNew, bool fAskFee)
2145 return _("Invalid amount");
2146 if (nValue + nTransactionFee > GetBalance())
2147 return _("Insufficient funds");
2149 // Parse Bitcoin address
2150 CScript scriptPubKey;
2151 scriptPubKey.SetDestination(address);
2153 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2159 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2163 fFirstRunRet = false;
2164 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2165 if (nLoadWalletRet == DB_NEED_REWRITE)
2167 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2170 // Note: can't top-up keypool here, because wallet is locked.
2171 // User will be prompted to unlock wallet the next operation
2172 // the requires a new key.
2176 if (nLoadWalletRet != DB_LOAD_OK)
2177 return nLoadWalletRet;
2178 fFirstRunRet = !vchDefaultKey.IsValid();
2180 NewThread(ThreadFlushWalletDB, &strWalletFile);
2184 DBErrors CWallet::ZapWalletTx()
2188 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this);
2189 if (nZapWalletTxRet == DB_NEED_REWRITE)
2191 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2195 // Note: can't top-up keypool here, because wallet is locked.
2196 // User will be prompted to unlock wallet the next operation
2197 // the requires a new key.
2201 if (nZapWalletTxRet != DB_LOAD_OK)
2202 return nZapWalletTxRet;
2207 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2209 std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2210 mapAddressBook[address] = strName;
2211 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != MINE_NO, (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2214 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2217 bool CWallet::DelAddressBookName(const CTxDestination& address)
2219 mapAddressBook.erase(address);
2220 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != MINE_NO, CT_DELETED);
2223 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2227 void CWallet::PrintWallet(const CBlock& block)
2231 if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2233 CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2234 printf(" PoS: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2236 else if (mapWallet.count(block.vtx[0].GetHash()))
2238 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2239 printf(" PoW: %d %d %" PRId64 "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(MINE_ALL));
2245 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2249 map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2250 if (mi != mapWallet.end())
2259 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2263 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2266 vchDefaultKey = vchPubKey;
2270 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2272 if (!pwallet->fFileBacked)
2274 strWalletFileOut = pwallet->strWalletFile;
2279 // Mark old keypool keys as used,
2280 // and generate all new keys
2282 bool CWallet::NewKeyPool(unsigned int nSize)
2286 CWalletDB walletdb(strWalletFile);
2287 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2288 walletdb.ErasePool(nIndex);
2298 nKeys = max<uint64_t>(GetArg("-keypool", 100), 0);
2300 for (uint64_t i = 0; i < nKeys; i++)
2302 uint64_t nIndex = i+1;
2303 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2304 setKeyPool.insert(nIndex);
2306 printf("CWallet::NewKeyPool wrote %" PRIu64 " new keys\n", nKeys);
2311 bool CWallet::TopUpKeyPool(unsigned int nSize)
2319 CWalletDB walletdb(strWalletFile);
2322 uint64_t nTargetSize;
2324 nTargetSize = nSize;
2326 nTargetSize = max<uint64_t>(GetArg("-keypool", 100), 0);
2328 while (setKeyPool.size() < (nTargetSize + 1))
2331 if (!setKeyPool.empty())
2332 nEnd = *(--setKeyPool.end()) + 1;
2333 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2334 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2335 setKeyPool.insert(nEnd);
2336 printf("keypool added key %" PRIu64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
2342 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2345 keypool.vchPubKey = CPubKey();
2352 // Get the oldest key
2353 if(setKeyPool.empty())
2356 CWalletDB walletdb(strWalletFile);
2358 nIndex = *(setKeyPool.begin());
2359 setKeyPool.erase(setKeyPool.begin());
2360 if (!walletdb.ReadPool(nIndex, keypool))
2361 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2362 if (!HaveKey(keypool.vchPubKey.GetID()))
2363 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2364 assert(keypool.vchPubKey.IsValid());
2365 if (fDebug && GetBoolArg("-printkeypool"))
2366 printf("keypool reserve %" PRId64 "\n", nIndex);
2370 int64_t CWallet::AddReserveKey(const CKeyPool& keypool)
2373 LOCK2(cs_main, cs_wallet);
2374 CWalletDB walletdb(strWalletFile);
2376 int64_t nIndex = 1 + *(--setKeyPool.end());
2377 if (!walletdb.WritePool(nIndex, keypool))
2378 throw runtime_error("AddReserveKey() : writing added key failed");
2379 setKeyPool.insert(nIndex);
2385 void CWallet::KeepKey(int64_t nIndex)
2387 // Remove from key pool
2390 CWalletDB walletdb(strWalletFile);
2391 walletdb.ErasePool(nIndex);
2394 printf("keypool keep %" PRId64 "\n", nIndex);
2397 void CWallet::ReturnKey(int64_t nIndex)
2399 // Return to key pool
2402 setKeyPool.insert(nIndex);
2405 printf("keypool return %" PRId64 "\n", nIndex);
2408 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2414 ReserveKeyFromKeyPool(nIndex, keypool);
2417 if (fAllowReuse && vchDefaultKey.IsValid())
2419 result = vchDefaultKey;
2422 if (IsLocked()) return false;
2423 result = GenerateNewKey();
2427 result = keypool.vchPubKey;
2432 int64_t CWallet::GetOldestKeyPoolTime()
2436 ReserveKeyFromKeyPool(nIndex, keypool);
2440 return keypool.nTime;
2443 std::map<CTxDestination, int64_t> CWallet::GetAddressBalances()
2445 map<CTxDestination, int64_t> balances;
2449 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2451 CWalletTx *pcoin = &walletEntry.second;
2453 if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2456 if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2459 int nDepth = pcoin->GetDepthInMainChain();
2460 if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2463 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2465 CTxDestination addr;
2466 if (!IsMine(pcoin->vout[i]))
2468 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2471 int64_t n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2473 if (!balances.count(addr))
2475 balances[addr] += n;
2483 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2485 set< set<CTxDestination> > groupings;
2486 set<CTxDestination> grouping;
2488 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2490 CWalletTx *pcoin = &walletEntry.second;
2492 if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2494 // group all input addresses with each other
2495 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2497 CTxDestination address;
2498 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2500 grouping.insert(address);
2503 // group change with input addresses
2504 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2505 if (IsChange(txout))
2507 CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2508 CTxDestination txoutAddr;
2509 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2511 grouping.insert(txoutAddr);
2513 groupings.insert(grouping);
2517 // group lone addrs by themselves
2518 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2519 if (IsMine(pcoin->vout[i]))
2521 CTxDestination address;
2522 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2524 grouping.insert(address);
2525 groupings.insert(grouping);
2530 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2531 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2532 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2534 // make a set of all the groups hit by this new group
2535 set< set<CTxDestination>* > hits;
2536 map< CTxDestination, set<CTxDestination>* >::iterator it;
2537 BOOST_FOREACH(CTxDestination address, grouping)
2538 if ((it = setmap.find(address)) != setmap.end())
2539 hits.insert((*it).second);
2541 // merge all hit groups into a new single group and delete old groups
2542 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2543 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2545 merged->insert(hit->begin(), hit->end());
2546 uniqueGroupings.erase(hit);
2549 uniqueGroupings.insert(merged);
2552 BOOST_FOREACH(CTxDestination element, *merged)
2553 setmap[element] = merged;
2556 set< set<CTxDestination> > ret;
2557 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2559 ret.insert(*uniqueGrouping);
2560 delete uniqueGrouping;
2566 // ppcoin: check 'spent' consistency between wallet and txindex
2567 // ppcoin: fix wallet spent state according to txindex
2568 void CWallet::FixSpentCoins(int& nMismatchFound, int64_t& nBalanceInQuestion, bool fCheckOnly)
2571 nBalanceInQuestion = 0;
2574 vector<CWalletTx*> vCoins;
2575 vCoins.reserve(mapWallet.size());
2576 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2577 vCoins.push_back(&(*it).second);
2580 BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2582 // Find the corresponding transaction index
2584 if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2586 for (unsigned int n=0; n < pcoin->vout.size(); n++)
2588 if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2590 printf("FixSpentCoins found lost coin %sppc %s[%u], %s\n",
2591 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2593 nBalanceInQuestion += pcoin->vout[n].nValue;
2596 pcoin->MarkUnspent(n);
2597 pcoin->WriteToDisk();
2600 else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2602 printf("FixSpentCoins found spent coin %sppc %s[%u], %s\n",
2603 FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2605 nBalanceInQuestion += pcoin->vout[n].nValue;
2608 pcoin->MarkSpent(n);
2609 pcoin->WriteToDisk();
2615 if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2617 printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2620 EraseFromWallet(pcoin->GetHash());
2626 // ppcoin: disable transaction (only for coinstake)
2627 void CWallet::DisableTransaction(const CTransaction &tx)
2629 if (!tx.IsCoinStake() || !IsFromMe(tx))
2630 return; // only disconnecting coinstake requires marking input unspent
2633 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2635 map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2636 if (mi != mapWallet.end())
2638 CWalletTx& prev = (*mi).second;
2639 if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2641 prev.MarkUnspent(txin.prevout.n);
2648 CPubKey CReserveKey::GetReservedKey()
2653 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2655 vchPubKey = keypool.vchPubKey;
2658 printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2659 vchPubKey = pwallet->vchDefaultKey;
2662 assert(vchPubKey.IsValid());
2666 void CReserveKey::KeepKey()
2669 pwallet->KeepKey(nIndex);
2671 vchPubKey = CPubKey();
2674 void CReserveKey::ReturnKey()
2677 pwallet->ReturnKey(nIndex);
2679 vchPubKey = CPubKey();
2682 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2686 CWalletDB walletdb(strWalletFile);
2688 LOCK2(cs_main, cs_wallet);
2689 BOOST_FOREACH(const int64_t& id, setKeyPool)
2692 if (!walletdb.ReadPool(id, keypool))
2693 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2694 assert(keypool.vchPubKey.IsValid());
2695 CKeyID keyID = keypool.vchPubKey.GetID();
2696 if (!HaveKey(keyID))
2697 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2698 setAddress.insert(keyID);
2702 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2706 // Only notify UI if this transaction is in this wallet
2707 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2708 if (mi != mapWallet.end())
2710 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2711 vMintingWalletUpdated.push_back(hashTx);
2716 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2717 mapKeyBirth.clear();
2719 // get birth times for keys with metadata
2720 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2721 if (it->second.nCreateTime)
2722 mapKeyBirth[it->first] = it->second.nCreateTime;
2724 // map in which we'll infer heights of other keys
2725 CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2726 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2727 std::set<CKeyID> setKeys;
2729 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2730 if (mapKeyBirth.count(keyid) == 0)
2731 mapKeyFirstBlock[keyid] = pindexMax;
2735 // if there are no such keys, we're done
2736 if (mapKeyFirstBlock.empty())
2739 // find first block that affects those keys, if there are any left
2740 std::vector<CKeyID> vAffected;
2741 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2742 // iterate over all wallet transactions...
2743 const CWalletTx &wtx = (*it).second;
2744 std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2745 if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2746 // ... which are already in a block
2747 int nHeight = blit->second->nHeight;
2748 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2749 // iterate over all their outputs
2750 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2751 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2752 // ... and all their affected keys
2753 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2754 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2755 rit->second = blit->second;
2762 // Extract block timestamps for those keys
2763 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2764 mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2767 void CWallet::ClearOrphans()
2769 list<uint256> orphans;
2772 for(map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2774 const CWalletTx *wtx = &(*it).second;
2775 if((wtx->IsCoinBase() || wtx->IsCoinStake()) && !wtx->IsInMainChain())
2777 orphans.push_back(wtx->GetHash());
2781 for(list<uint256>::const_iterator it = orphans.begin(); it != orphans.end(); ++it)
2782 EraseFromWallet(*it);