1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "wallet/wallet.h"
9 #include "checkpoints.h"
10 #include "coincontrol.h"
11 #include "consensus/consensus.h"
12 #include "consensus/validation.h"
15 #include "script/script.h"
16 #include "script/sign.h"
19 #include "utilmoneystr.h"
23 #include <boost/algorithm/string/replace.hpp>
24 #include <boost/filesystem.hpp>
25 #include <boost/thread.hpp>
32 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
33 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
34 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
35 bool bSpendZeroConfChange = true;
36 bool fSendFreeTransactions = false;
37 bool fPayAtLeastCustomFee = true;
40 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
41 * Override with -mintxfee
43 CFeeRate CWallet::minTxFee = CFeeRate(1000);
45 /** @defgroup mapWallet
50 struct CompareValueOnly
52 bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
53 const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
55 return t1.first < t2.first;
59 std::string COutput::ToString() const
61 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
64 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
67 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
68 if (it == mapWallet.end())
73 CPubKey CWallet::GenerateNewKey()
75 AssertLockHeld(cs_wallet); // mapKeyMetadata
76 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
79 secret.MakeNewKey(fCompressed);
81 // Compressed public keys were introduced in version 0.6.0
83 SetMinVersion(FEATURE_COMPRPUBKEY);
85 CPubKey pubkey = secret.GetPubKey();
86 assert(secret.VerifyPubKey(pubkey));
88 // Create new metadata
89 int64_t nCreationTime = GetTime();
90 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
91 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
92 nTimeFirstKey = nCreationTime;
94 if (!AddKeyPubKey(secret, pubkey))
95 throw std::runtime_error("CWallet::GenerateNewKey(): AddKey failed");
99 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
101 AssertLockHeld(cs_wallet); // mapKeyMetadata
102 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
105 // check if we need to remove from watch-only
107 script = GetScriptForDestination(pubkey.GetID());
108 if (HaveWatchOnly(script))
109 RemoveWatchOnly(script);
114 return CWalletDB(strWalletFile).WriteKey(pubkey,
116 mapKeyMetadata[pubkey.GetID()]);
121 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
122 const vector<unsigned char> &vchCryptedSecret)
124 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
130 if (pwalletdbEncryption)
131 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
133 mapKeyMetadata[vchPubKey.GetID()]);
135 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
137 mapKeyMetadata[vchPubKey.GetID()]);
142 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
144 AssertLockHeld(cs_wallet); // mapKeyMetadata
145 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
146 nTimeFirstKey = meta.nCreateTime;
148 mapKeyMetadata[pubkey.GetID()] = meta;
152 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
154 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
157 bool CWallet::AddCScript(const CScript& redeemScript)
159 if (!CCryptoKeyStore::AddCScript(redeemScript))
163 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
166 bool CWallet::LoadCScript(const CScript& redeemScript)
168 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
169 * that never can be redeemed. However, old wallets may still contain
170 * these. Do not add them to the wallet and warn. */
171 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
173 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
174 LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
175 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
179 return CCryptoKeyStore::AddCScript(redeemScript);
182 bool CWallet::AddWatchOnly(const CScript &dest)
184 if (!CCryptoKeyStore::AddWatchOnly(dest))
186 nTimeFirstKey = 1; // No birthday information for watch-only keys.
187 NotifyWatchonlyChanged(true);
190 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
193 bool CWallet::RemoveWatchOnly(const CScript &dest)
195 AssertLockHeld(cs_wallet);
196 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
198 if (!HaveWatchOnly())
199 NotifyWatchonlyChanged(false);
201 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
207 bool CWallet::LoadWatchOnly(const CScript &dest)
209 return CCryptoKeyStore::AddWatchOnly(dest);
212 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
215 CKeyingMaterial vMasterKey;
219 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
221 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
223 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
224 continue; // try another master key
225 if (CCryptoKeyStore::Unlock(vMasterKey))
232 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
234 bool fWasLocked = IsLocked();
241 CKeyingMaterial vMasterKey;
242 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
244 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
246 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
248 if (CCryptoKeyStore::Unlock(vMasterKey))
250 int64_t nStartTime = GetTimeMillis();
251 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
252 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
254 nStartTime = GetTimeMillis();
255 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
256 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
258 if (pMasterKey.second.nDeriveIterations < 25000)
259 pMasterKey.second.nDeriveIterations = 25000;
261 LogPrintf("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 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
286 LOCK(cs_wallet); // nWalletVersion
287 if (nWalletVersion >= nVersion)
290 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
291 if (fExplicit && nVersion > nWalletMaxVersion)
292 nVersion = FEATURE_LATEST;
294 nWalletVersion = nVersion;
296 if (nVersion > nWalletMaxVersion)
297 nWalletMaxVersion = nVersion;
301 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
302 if (nWalletVersion > 40000)
303 pwalletdb->WriteMinVersion(nWalletVersion);
311 bool CWallet::SetMaxVersion(int nVersion)
313 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
314 // cannot downgrade below current version
315 if (nWalletVersion > nVersion)
318 nWalletMaxVersion = nVersion;
323 set<uint256> CWallet::GetConflicts(const uint256& txid) const
326 AssertLockHeld(cs_wallet);
328 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
329 if (it == mapWallet.end())
331 const CWalletTx& wtx = it->second;
333 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
335 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
337 if (mapTxSpends.count(txin.prevout) <= 1)
338 continue; // No conflict if zero or one spends
339 range = mapTxSpends.equal_range(txin.prevout);
340 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
341 result.insert(it->second);
346 void CWallet::Flush(bool shutdown)
348 bitdb.Flush(shutdown);
351 bool CWallet::Verify(const string& walletFile, string& warningString, string& errorString)
353 if (!bitdb.Open(GetDataDir()))
355 // try moving the database env out of the way
356 boost::filesystem::path pathDatabase = GetDataDir() / "database";
357 boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
359 boost::filesystem::rename(pathDatabase, pathDatabaseBak);
360 LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
361 } catch (const boost::filesystem::filesystem_error&) {
362 // failure is ok (well, not really, but it's not worse than what we started with)
366 if (!bitdb.Open(GetDataDir())) {
367 // if it still fails, it probably means we can't even create the database env
368 string msg = strprintf(_("Error initializing wallet database environment %s!"), GetDataDir());
374 if (GetBoolArg("-salvagewallet", false))
376 // Recover readable keypairs:
377 if (!CWalletDB::Recover(bitdb, walletFile, true))
381 if (boost::filesystem::exists(GetDataDir() / walletFile))
383 CDBEnv::VerifyResult r = bitdb.Verify(walletFile, CWalletDB::Recover);
384 if (r == CDBEnv::RECOVER_OK)
386 warningString += strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
387 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
388 " your balance or transactions are incorrect you should"
389 " restore from a backup."), GetDataDir());
391 if (r == CDBEnv::RECOVER_FAIL)
392 errorString += _("wallet.dat corrupt, salvage failed");
398 void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range)
400 // We want all the wallet transactions in range to have the same metadata as
401 // the oldest (smallest nOrderPos).
402 // So: find smallest nOrderPos:
404 int nMinOrderPos = std::numeric_limits<int>::max();
405 const CWalletTx* copyFrom = NULL;
406 for (TxSpends::iterator it = range.first; it != range.second; ++it)
408 const uint256& hash = it->second;
409 int n = mapWallet[hash].nOrderPos;
410 if (n < nMinOrderPos)
413 copyFrom = &mapWallet[hash];
416 // Now copy data from copyFrom to rest:
417 for (TxSpends::iterator it = range.first; it != range.second; ++it)
419 const uint256& hash = it->second;
420 CWalletTx* copyTo = &mapWallet[hash];
421 if (copyFrom == copyTo) continue;
422 copyTo->mapValue = copyFrom->mapValue;
423 copyTo->vOrderForm = copyFrom->vOrderForm;
424 // fTimeReceivedIsTxTime not copied on purpose
425 // nTimeReceived not copied on purpose
426 copyTo->nTimeSmart = copyFrom->nTimeSmart;
427 copyTo->fFromMe = copyFrom->fFromMe;
428 copyTo->strFromAccount = copyFrom->strFromAccount;
429 // nOrderPos not copied on purpose
430 // cached members not copied on purpose
435 * Outpoint is spent if any non-conflicted transaction
438 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
440 const COutPoint outpoint(hash, n);
441 pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
442 range = mapTxSpends.equal_range(outpoint);
444 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
446 const uint256& wtxid = it->second;
447 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
448 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
449 return true; // Spent
454 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
456 mapTxSpends.insert(make_pair(outpoint, wtxid));
458 pair<TxSpends::iterator, TxSpends::iterator> range;
459 range = mapTxSpends.equal_range(outpoint);
464 void CWallet::AddToSpends(const uint256& wtxid)
466 assert(mapWallet.count(wtxid));
467 CWalletTx& thisTx = mapWallet[wtxid];
468 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
471 BOOST_FOREACH(const CTxIn& txin, thisTx.vin)
472 AddToSpends(txin.prevout, wtxid);
475 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
480 CKeyingMaterial vMasterKey;
481 RandAddSeedPerfmon();
483 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
484 GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
486 CMasterKey kMasterKey;
487 RandAddSeedPerfmon();
489 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
490 GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
493 int64_t nStartTime = GetTimeMillis();
494 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
495 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
497 nStartTime = GetTimeMillis();
498 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
499 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
501 if (kMasterKey.nDeriveIterations < 25000)
502 kMasterKey.nDeriveIterations = 25000;
504 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
506 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
508 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
513 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
516 assert(!pwalletdbEncryption);
517 pwalletdbEncryption = new CWalletDB(strWalletFile);
518 if (!pwalletdbEncryption->TxnBegin()) {
519 delete pwalletdbEncryption;
520 pwalletdbEncryption = NULL;
523 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
526 if (!EncryptKeys(vMasterKey))
529 pwalletdbEncryption->TxnAbort();
530 delete pwalletdbEncryption;
532 // We now probably have half of our keys encrypted in memory, and half not...
533 // die and let the user reload the unencrypted wallet.
537 // Encryption was introduced in version 0.4.0
538 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
542 if (!pwalletdbEncryption->TxnCommit()) {
543 delete pwalletdbEncryption;
544 // We now have keys encrypted in memory, but not on disk...
545 // die to avoid confusion and let the user reload the unencrypted wallet.
549 delete pwalletdbEncryption;
550 pwalletdbEncryption = NULL;
554 Unlock(strWalletPassphrase);
558 // Need to completely rewrite the wallet file; if we don't, bdb might keep
559 // bits of the unencrypted private key in slack space in the database file.
560 CDB::Rewrite(strWalletFile);
563 NotifyStatusChanged(this);
568 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
570 AssertLockHeld(cs_wallet); // nOrderPosNext
571 int64_t nRet = nOrderPosNext++;
573 pwalletdb->WriteOrderPosNext(nOrderPosNext);
575 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
580 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
582 AssertLockHeld(cs_wallet); // mapWallet
583 CWalletDB walletdb(strWalletFile);
585 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
588 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
589 // would make this much faster for applications that do this a lot.
590 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
592 CWalletTx* wtx = &((*it).second);
593 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
596 walletdb.ListAccountCreditDebit(strAccount, acentries);
597 BOOST_FOREACH(CAccountingEntry& entry, acentries)
599 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
605 void CWallet::MarkDirty()
609 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
610 item.second.MarkDirty();
614 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb)
616 uint256 hash = wtxIn.GetHash();
620 mapWallet[hash] = wtxIn;
621 mapWallet[hash].BindWallet(this);
627 // Inserts only if not already there, returns tx inserted or tx found
628 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
629 CWalletTx& wtx = (*ret.first).second;
630 wtx.BindWallet(this);
631 bool fInsertedNew = ret.second;
634 wtx.nTimeReceived = GetAdjustedTime();
635 wtx.nOrderPos = IncOrderPosNext(pwalletdb);
637 wtx.nTimeSmart = wtx.nTimeReceived;
638 if (!wtxIn.hashBlock.IsNull())
640 if (mapBlockIndex.count(wtxIn.hashBlock))
642 int64_t latestNow = wtx.nTimeReceived;
643 int64_t latestEntry = 0;
645 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
646 int64_t latestTolerated = latestNow + 300;
647 std::list<CAccountingEntry> acentries;
648 TxItems txOrdered = OrderedTxItems(acentries);
649 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
651 CWalletTx *const pwtx = (*it).second.first;
654 CAccountingEntry *const pacentry = (*it).second.second;
658 nSmartTime = pwtx->nTimeSmart;
660 nSmartTime = pwtx->nTimeReceived;
663 nSmartTime = pacentry->nTime;
664 if (nSmartTime <= latestTolerated)
666 latestEntry = nSmartTime;
667 if (nSmartTime > latestNow)
668 latestNow = nSmartTime;
674 int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
675 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
678 LogPrintf("AddToWallet(): found %s in block %s not in index\n",
679 wtxIn.GetHash().ToString(),
680 wtxIn.hashBlock.ToString());
685 bool fUpdated = false;
689 if (!wtxIn.hashBlock.IsNull() && wtxIn.hashBlock != wtx.hashBlock)
691 wtx.hashBlock = wtxIn.hashBlock;
694 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
696 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
697 wtx.nIndex = wtxIn.nIndex;
700 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
702 wtx.fFromMe = wtxIn.fFromMe;
708 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
711 if (fInsertedNew || fUpdated)
712 if (!wtx.WriteToDisk(pwalletdb))
715 // Break debit/credit balance caches:
718 // Notify UI of new or updated transaction
719 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
721 // notify an external script when a wallet transaction comes in or is updated
722 std::string strCmd = GetArg("-walletnotify", "");
724 if ( !strCmd.empty())
726 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
727 boost::thread t(runCommand, strCmd); // thread runs free
735 * Add a transaction to the wallet, or update it.
736 * pblock is optional, but should be provided if the transaction is known to be in a block.
737 * If fUpdate is true, existing transactions will be updated.
739 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
742 AssertLockHeld(cs_wallet);
743 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
744 if (fExisted && !fUpdate) return false;
745 if (fExisted || IsMine(tx) || IsFromMe(tx))
747 CWalletTx wtx(this,tx);
749 // Get merkle branch if transaction was found in a block
751 wtx.SetMerkleBranch(*pblock);
753 // Do not flush the wallet here for performance reasons
754 // this is safe, as in case of a crash, we rescan the necessary blocks on startup through our SetBestChain-mechanism
755 CWalletDB walletdb(strWalletFile, "r+", false);
757 return AddToWallet(wtx, false, &walletdb);
763 void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
765 LOCK2(cs_main, cs_wallet);
766 if (!AddToWalletIfInvolvingMe(tx, pblock, true))
767 return; // Not one of ours
769 // If a transaction changes 'conflicted' state, that changes the balance
770 // available of the outputs it spends. So force those to be
772 BOOST_FOREACH(const CTxIn& txin, tx.vin)
774 if (mapWallet.count(txin.prevout.hash))
775 mapWallet[txin.prevout.hash].MarkDirty();
779 void CWallet::EraseFromWallet(const uint256 &hash)
785 if (mapWallet.erase(hash))
786 CWalletDB(strWalletFile).EraseTx(hash);
792 isminetype CWallet::IsMine(const CTxIn &txin) const
796 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
797 if (mi != mapWallet.end())
799 const CWalletTx& prev = (*mi).second;
800 if (txin.prevout.n < prev.vout.size())
801 return IsMine(prev.vout[txin.prevout.n]);
807 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
811 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
812 if (mi != mapWallet.end())
814 const CWalletTx& prev = (*mi).second;
815 if (txin.prevout.n < prev.vout.size())
816 if (IsMine(prev.vout[txin.prevout.n]) & filter)
817 return prev.vout[txin.prevout.n].nValue;
823 isminetype CWallet::IsMine(const CTxOut& txout) const
825 return ::IsMine(*this, txout.scriptPubKey);
828 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
830 if (!MoneyRange(txout.nValue))
831 throw std::runtime_error("CWallet::GetCredit(): value out of range");
832 return ((IsMine(txout) & filter) ? txout.nValue : 0);
835 bool CWallet::IsChange(const CTxOut& txout) const
837 // TODO: fix handling of 'change' outputs. The assumption is that any
838 // payment to a script that is ours, but is not in the address book
839 // is change. That assumption is likely to break when we implement multisignature
840 // wallets that return change back into a multi-signature-protected address;
841 // a better way of identifying which outputs are 'the send' and which are
842 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
843 // which output, if any, was change).
844 if (::IsMine(*this, txout.scriptPubKey))
846 CTxDestination address;
847 if (!ExtractDestination(txout.scriptPubKey, address))
851 if (!mapAddressBook.count(address))
857 CAmount CWallet::GetChange(const CTxOut& txout) const
859 if (!MoneyRange(txout.nValue))
860 throw std::runtime_error("CWallet::GetChange(): value out of range");
861 return (IsChange(txout) ? txout.nValue : 0);
864 bool CWallet::IsMine(const CTransaction& tx) const
866 BOOST_FOREACH(const CTxOut& txout, tx.vout)
872 bool CWallet::IsFromMe(const CTransaction& tx) const
874 return (GetDebit(tx, ISMINE_ALL) > 0);
877 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
880 BOOST_FOREACH(const CTxIn& txin, tx.vin)
882 nDebit += GetDebit(txin, filter);
883 if (!MoneyRange(nDebit))
884 throw std::runtime_error("CWallet::GetDebit(): value out of range");
889 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
892 BOOST_FOREACH(const CTxOut& txout, tx.vout)
894 nCredit += GetCredit(txout, filter);
895 if (!MoneyRange(nCredit))
896 throw std::runtime_error("CWallet::GetCredit(): value out of range");
901 CAmount CWallet::GetChange(const CTransaction& tx) const
904 BOOST_FOREACH(const CTxOut& txout, tx.vout)
906 nChange += GetChange(txout);
907 if (!MoneyRange(nChange))
908 throw std::runtime_error("CWallet::GetChange(): value out of range");
913 int64_t CWalletTx::GetTxTime() const
915 int64_t n = nTimeSmart;
916 return n ? n : nTimeReceived;
919 int CWalletTx::GetRequestCount() const
921 // Returns -1 if it wasn't being tracked
924 LOCK(pwallet->cs_wallet);
928 if (!hashBlock.IsNull())
930 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
931 if (mi != pwallet->mapRequestCount.end())
932 nRequests = (*mi).second;
937 // Did anyone request this transaction?
938 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
939 if (mi != pwallet->mapRequestCount.end())
941 nRequests = (*mi).second;
943 // How about the block it's in?
944 if (nRequests == 0 && !hashBlock.IsNull())
946 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
947 if (mi != pwallet->mapRequestCount.end())
948 nRequests = (*mi).second;
950 nRequests = 1; // If it's in someone else's block it must have got out
958 void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
959 list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
962 listReceived.clear();
964 strSentAccount = strFromAccount;
967 CAmount nDebit = GetDebit(filter);
968 if (nDebit > 0) // debit>0 means we signed/sent this transaction
970 CAmount nValueOut = GetValueOut();
971 nFee = nDebit - nValueOut;
975 for (unsigned int i = 0; i < vout.size(); ++i)
977 const CTxOut& txout = vout[i];
978 isminetype fIsMine = pwallet->IsMine(txout);
979 // Only need to handle txouts if AT LEAST one of these is true:
980 // 1) they debit from us (sent)
981 // 2) the output is to us (received)
984 // Don't report 'change' txouts
985 if (pwallet->IsChange(txout))
988 else if (!(fIsMine & filter))
991 // In either case, we need to get the destination address
992 CTxDestination address;
993 if (!ExtractDestination(txout.scriptPubKey, address))
995 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
996 this->GetHash().ToString());
997 address = CNoDestination();
1000 COutputEntry output = {address, txout.nValue, (int)i};
1002 // If we are debited by the transaction, add the output as a "sent" entry
1004 listSent.push_back(output);
1006 // If we are receiving the output, add it as a "received" entry
1007 if (fIsMine & filter)
1008 listReceived.push_back(output);
1013 void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
1014 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
1016 nReceived = nSent = nFee = 0;
1019 string strSentAccount;
1020 list<COutputEntry> listReceived;
1021 list<COutputEntry> listSent;
1022 GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
1024 if (strAccount == strSentAccount)
1026 BOOST_FOREACH(const COutputEntry& s, listSent)
1031 LOCK(pwallet->cs_wallet);
1032 BOOST_FOREACH(const COutputEntry& r, listReceived)
1034 if (pwallet->mapAddressBook.count(r.destination))
1036 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
1037 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
1038 nReceived += r.amount;
1040 else if (strAccount.empty())
1042 nReceived += r.amount;
1049 bool CWalletTx::WriteToDisk(CWalletDB *pwalletdb)
1051 return pwalletdb->WriteTx(GetHash(), *this);
1055 * Scan the block chain (starting in pindexStart) for transactions
1056 * from or to us. If fUpdate is true, found transactions that already
1057 * exist in the wallet will be updated.
1059 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1062 int64_t nNow = GetTime();
1063 const CChainParams& chainParams = Params();
1065 CBlockIndex* pindex = pindexStart;
1067 LOCK2(cs_main, cs_wallet);
1069 // no need to read and scan block, if block was created before
1070 // our wallet birthday (as adjusted for block time variability)
1071 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
1072 pindex = chainActive.Next(pindex);
1074 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1075 double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
1076 double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip(), false);
1079 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1080 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1083 ReadBlockFromDisk(block, pindex);
1084 BOOST_FOREACH(CTransaction& tx, block.vtx)
1086 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1089 pindex = chainActive.Next(pindex);
1090 if (GetTime() >= nNow + 60) {
1092 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex));
1095 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1100 void CWallet::ReacceptWalletTransactions()
1102 // If transactions aren't being broadcasted, don't let them into local mempool either
1103 if (!fBroadcastTransactions)
1105 LOCK2(cs_main, cs_wallet);
1106 std::map<int64_t, CWalletTx*> mapSorted;
1108 // Sort pending wallet transactions based on their initial wallet insertion order
1109 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1111 const uint256& wtxid = item.first;
1112 CWalletTx& wtx = item.second;
1113 assert(wtx.GetHash() == wtxid);
1115 int nDepth = wtx.GetDepthInMainChain();
1117 if (!wtx.IsCoinBase() && nDepth < 0) {
1118 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1122 // Try to add wallet transactions to memory pool
1123 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1125 CWalletTx& wtx = *(item.second);
1128 wtx.AcceptToMemoryPool(false);
1132 bool CWalletTx::RelayWalletTransaction()
1134 assert(pwallet->GetBroadcastTransactions());
1137 if (GetDepthInMainChain() == 0) {
1138 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1139 RelayTransaction((CTransaction)*this);
1146 set<uint256> CWalletTx::GetConflicts() const
1148 set<uint256> result;
1149 if (pwallet != NULL)
1151 uint256 myHash = GetHash();
1152 result = pwallet->GetConflicts(myHash);
1153 result.erase(myHash);
1158 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1164 if(filter & ISMINE_SPENDABLE)
1167 debit += nDebitCached;
1170 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1171 fDebitCached = true;
1172 debit += nDebitCached;
1175 if(filter & ISMINE_WATCH_ONLY)
1177 if(fWatchDebitCached)
1178 debit += nWatchDebitCached;
1181 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1182 fWatchDebitCached = true;
1183 debit += nWatchDebitCached;
1189 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1191 // Must wait until coinbase is safely deep enough in the chain before valuing it
1192 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1196 if (filter & ISMINE_SPENDABLE)
1198 // GetBalance can assume transactions in mapWallet won't change
1200 credit += nCreditCached;
1203 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1204 fCreditCached = true;
1205 credit += nCreditCached;
1208 if (filter & ISMINE_WATCH_ONLY)
1210 if (fWatchCreditCached)
1211 credit += nWatchCreditCached;
1214 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1215 fWatchCreditCached = true;
1216 credit += nWatchCreditCached;
1222 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1224 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1226 if (fUseCache && fImmatureCreditCached)
1227 return nImmatureCreditCached;
1228 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1229 fImmatureCreditCached = true;
1230 return nImmatureCreditCached;
1236 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1241 // Must wait until coinbase is safely deep enough in the chain before valuing it
1242 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1245 if (fUseCache && fAvailableCreditCached)
1246 return nAvailableCreditCached;
1248 CAmount nCredit = 0;
1249 uint256 hashTx = GetHash();
1250 for (unsigned int i = 0; i < vout.size(); i++)
1252 if (!pwallet->IsSpent(hashTx, i))
1254 const CTxOut &txout = vout[i];
1255 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1256 if (!MoneyRange(nCredit))
1257 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1261 nAvailableCreditCached = nCredit;
1262 fAvailableCreditCached = true;
1266 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1268 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1270 if (fUseCache && fImmatureWatchCreditCached)
1271 return nImmatureWatchCreditCached;
1272 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1273 fImmatureWatchCreditCached = true;
1274 return nImmatureWatchCreditCached;
1280 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1285 // Must wait until coinbase is safely deep enough in the chain before valuing it
1286 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1289 if (fUseCache && fAvailableWatchCreditCached)
1290 return nAvailableWatchCreditCached;
1292 CAmount nCredit = 0;
1293 for (unsigned int i = 0; i < vout.size(); i++)
1295 if (!pwallet->IsSpent(GetHash(), i))
1297 const CTxOut &txout = vout[i];
1298 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1299 if (!MoneyRange(nCredit))
1300 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1304 nAvailableWatchCreditCached = nCredit;
1305 fAvailableWatchCreditCached = true;
1309 CAmount CWalletTx::GetChange() const
1312 return nChangeCached;
1313 nChangeCached = pwallet->GetChange(*this);
1314 fChangeCached = true;
1315 return nChangeCached;
1318 bool CWalletTx::IsTrusted() const
1320 // Quick answer in most cases
1321 if (!CheckFinalTx(*this))
1323 int nDepth = GetDepthInMainChain();
1328 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1331 // Trusted if all inputs are from us and are in the mempool:
1332 BOOST_FOREACH(const CTxIn& txin, vin)
1334 // Transactions not sent by us: not trusted
1335 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1338 const CTxOut& parentOut = parent->vout[txin.prevout.n];
1339 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1345 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
1347 std::vector<uint256> result;
1350 // Sort them in chronological order
1351 multimap<unsigned int, CWalletTx*> mapSorted;
1352 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1354 CWalletTx& wtx = item.second;
1355 // Don't rebroadcast if newer than nTime:
1356 if (wtx.nTimeReceived > nTime)
1358 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1360 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1362 CWalletTx& wtx = *item.second;
1363 if (wtx.RelayWalletTransaction())
1364 result.push_back(wtx.GetHash());
1369 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
1371 // Do this infrequently and randomly to avoid giving away
1372 // that these are our transactions.
1373 if (GetTime() < nNextResend || !fBroadcastTransactions)
1375 bool fFirst = (nNextResend == 0);
1376 nNextResend = GetTime() + GetRand(30 * 60);
1380 // Only do it if there's been a new block since last time
1381 if (nBestBlockTime < nLastResend)
1383 nLastResend = GetTime();
1385 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1387 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60);
1388 if (!relayed.empty())
1389 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1392 /** @} */ // end of mapWallet
1397 /** @defgroup Actions
1403 CAmount CWallet::GetBalance() const
1407 LOCK2(cs_main, cs_wallet);
1408 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1410 const CWalletTx* pcoin = &(*it).second;
1411 if (pcoin->IsTrusted())
1412 nTotal += pcoin->GetAvailableCredit();
1419 CAmount CWallet::GetUnconfirmedBalance() const
1423 LOCK2(cs_main, cs_wallet);
1424 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1426 const CWalletTx* pcoin = &(*it).second;
1427 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
1428 nTotal += pcoin->GetAvailableCredit();
1434 CAmount CWallet::GetImmatureBalance() const
1438 LOCK2(cs_main, cs_wallet);
1439 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1441 const CWalletTx* pcoin = &(*it).second;
1442 nTotal += pcoin->GetImmatureCredit();
1448 CAmount CWallet::GetWatchOnlyBalance() const
1452 LOCK2(cs_main, cs_wallet);
1453 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1455 const CWalletTx* pcoin = &(*it).second;
1456 if (pcoin->IsTrusted())
1457 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1464 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
1468 LOCK2(cs_main, cs_wallet);
1469 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1471 const CWalletTx* pcoin = &(*it).second;
1472 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
1473 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1479 CAmount CWallet::GetImmatureWatchOnlyBalance() const
1483 LOCK2(cs_main, cs_wallet);
1484 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1486 const CWalletTx* pcoin = &(*it).second;
1487 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1494 * populate vCoins with vector of available COutputs.
1496 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue) const
1501 LOCK2(cs_main, cs_wallet);
1502 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1504 const uint256& wtxid = it->first;
1505 const CWalletTx* pcoin = &(*it).second;
1507 if (!CheckFinalTx(*pcoin))
1510 if (fOnlyConfirmed && !pcoin->IsTrusted())
1513 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1516 int nDepth = pcoin->GetDepthInMainChain();
1520 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1521 isminetype mine = IsMine(pcoin->vout[i]);
1522 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
1523 !IsLockedCoin((*it).first, i) && (pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
1524 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1525 vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO));
1531 static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
1532 vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
1534 vector<char> vfIncluded;
1536 vfBest.assign(vValue.size(), true);
1537 nBest = nTotalLower;
1539 seed_insecure_rand();
1541 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1543 vfIncluded.assign(vValue.size(), false);
1545 bool fReachedTarget = false;
1546 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1548 for (unsigned int i = 0; i < vValue.size(); i++)
1550 //The solver here uses a randomized algorithm,
1551 //the randomness serves no real security purpose but is just
1552 //needed to prevent degenerate behavior and it is important
1553 //that the rng is fast. We do not use a constant random sequence,
1554 //because there may be some privacy improvement by making
1555 //the selection random.
1556 if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
1558 nTotal += vValue[i].first;
1559 vfIncluded[i] = true;
1560 if (nTotal >= nTargetValue)
1562 fReachedTarget = true;
1566 vfBest = vfIncluded;
1568 nTotal -= vValue[i].first;
1569 vfIncluded[i] = false;
1577 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
1578 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
1580 setCoinsRet.clear();
1583 // List of values less than target
1584 pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1585 coinLowestLarger.first = std::numeric_limits<CAmount>::max();
1586 coinLowestLarger.second.first = NULL;
1587 vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
1588 CAmount nTotalLower = 0;
1590 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1592 BOOST_FOREACH(const COutput &output, vCoins)
1594 if (!output.fSpendable)
1597 const CWalletTx *pcoin = output.tx;
1599 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
1603 CAmount n = pcoin->vout[i].nValue;
1605 pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1607 if (n == nTargetValue)
1609 setCoinsRet.insert(coin.second);
1610 nValueRet += coin.first;
1613 else if (n < nTargetValue + CENT)
1615 vValue.push_back(coin);
1618 else if (n < coinLowestLarger.first)
1620 coinLowestLarger = coin;
1624 if (nTotalLower == nTargetValue)
1626 for (unsigned int i = 0; i < vValue.size(); ++i)
1628 setCoinsRet.insert(vValue[i].second);
1629 nValueRet += vValue[i].first;
1634 if (nTotalLower < nTargetValue)
1636 if (coinLowestLarger.second.first == NULL)
1638 setCoinsRet.insert(coinLowestLarger.second);
1639 nValueRet += coinLowestLarger.first;
1643 // Solve subset sum by stochastic approximation
1644 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1645 vector<char> vfBest;
1648 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1649 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1650 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1652 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1653 // or the next bigger coin is closer), return the bigger coin
1654 if (coinLowestLarger.second.first &&
1655 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1657 setCoinsRet.insert(coinLowestLarger.second);
1658 nValueRet += coinLowestLarger.first;
1661 for (unsigned int i = 0; i < vValue.size(); i++)
1664 setCoinsRet.insert(vValue[i].second);
1665 nValueRet += vValue[i].first;
1668 LogPrint("selectcoins", "SelectCoins() best subset: ");
1669 for (unsigned int i = 0; i < vValue.size(); i++)
1671 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
1672 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
1678 bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
1680 vector<COutput> vCoins;
1681 AvailableCoins(vCoins, true, coinControl);
1683 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1684 if (coinControl && coinControl->HasSelected())
1686 BOOST_FOREACH(const COutput& out, vCoins)
1690 nValueRet += out.tx->vout[out.i].nValue;
1691 setCoinsRet.insert(make_pair(out.tx, out.i));
1693 return (nValueRet >= nTargetValue);
1696 return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1697 SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1698 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet)));
1701 bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend,
1702 CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosRet, std::string& strFailReason, const CCoinControl* coinControl)
1705 unsigned int nSubtractFeeFromAmount = 0;
1706 BOOST_FOREACH (const CRecipient& recipient, vecSend)
1708 if (nValue < 0 || recipient.nAmount < 0)
1710 strFailReason = _("Transaction amounts must be positive");
1713 nValue += recipient.nAmount;
1715 if (recipient.fSubtractFeeFromAmount)
1716 nSubtractFeeFromAmount++;
1718 if (vecSend.empty() || nValue < 0)
1720 strFailReason = _("Transaction amounts must be positive");
1724 wtxNew.fTimeReceivedIsTxTime = true;
1725 wtxNew.BindWallet(this);
1726 CMutableTransaction txNew;
1728 // Discourage fee sniping.
1730 // However because of a off-by-one-error in previous versions we need to
1731 // neuter it by setting nLockTime to at least one less than nBestHeight.
1732 // Secondly currently propagation of transactions created for block heights
1733 // corresponding to blocks that were just mined may be iffy - transactions
1734 // aren't re-accepted into the mempool - we additionally neuter the code by
1735 // going ten blocks back. Doesn't yet do anything for sniping, but does act
1736 // to shake out wallet bugs like not showing nLockTime'd transactions at
1738 txNew.nLockTime = std::max(0, chainActive.Height() - 10);
1740 // Secondly occasionally randomly pick a nLockTime even further back, so
1741 // that transactions that are delayed after signing for whatever reason,
1742 // e.g. high-latency mix networks and some CoinJoin implementations, have
1744 if (GetRandInt(10) == 0)
1745 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
1747 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
1748 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
1751 LOCK2(cs_main, cs_wallet);
1758 wtxNew.fFromMe = true;
1762 CAmount nTotalValue = nValue;
1763 if (nSubtractFeeFromAmount == 0)
1764 nTotalValue += nFeeRet;
1765 double dPriority = 0;
1766 // vouts to the payees
1767 BOOST_FOREACH (const CRecipient& recipient, vecSend)
1769 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
1771 if (recipient.fSubtractFeeFromAmount)
1773 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
1775 if (fFirst) // first receiver pays the remainder not divisible by output count
1778 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
1782 if (txout.IsDust(::minRelayTxFee))
1784 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
1786 if (txout.nValue < 0)
1787 strFailReason = _("The transaction amount is too small to pay the fee");
1789 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
1792 strFailReason = _("Transaction amount too small");
1795 txNew.vout.push_back(txout);
1798 // Choose coins to use
1799 set<pair<const CWalletTx*,unsigned int> > setCoins;
1800 CAmount nValueIn = 0;
1801 if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl))
1803 strFailReason = _("Insufficient funds");
1806 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1808 CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
1809 //The coin age after the next block (depth+1) is used instead of the current,
1810 //reflecting an assumption the user would accept a bit more delay for
1811 //a chance at a free transaction.
1812 //But mempool inputs might still be in the mempool, so their age stays 0
1813 int age = pcoin.first->GetDepthInMainChain();
1816 dPriority += (double)nCredit * age;
1819 CAmount nChange = nValueIn - nValue;
1820 if (nSubtractFeeFromAmount == 0)
1825 // Fill a vout to ourself
1826 // TODO: pass in scriptChange instead of reservekey so
1827 // change transaction isn't always pay-to-bitcoin-address
1828 CScript scriptChange;
1830 // coin control: send change to custom address
1831 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1832 scriptChange = GetScriptForDestination(coinControl->destChange);
1834 // no coin control: send change to newly generated address
1837 // Note: We use a new key here to keep it from being obvious which side is the change.
1838 // The drawback is that by not reusing a previous key, the change may be lost if a
1839 // backup is restored, if the backup doesn't have the new private key for the change.
1840 // If we reused the old key, it would be possible to add code to look for and
1841 // rediscover unknown transactions that were written with keys of ours to recover
1842 // post-backup change.
1844 // Reserve a new key pair from key pool
1847 ret = reservekey.GetReservedKey(vchPubKey);
1848 assert(ret); // should never fail, as we just unlocked
1850 scriptChange = GetScriptForDestination(vchPubKey.GetID());
1853 CTxOut newTxOut(nChange, scriptChange);
1855 // We do not move dust-change to fees, because the sender would end up paying more than requested.
1856 // This would be against the purpose of the all-inclusive feature.
1857 // So instead we raise the change and deduct from the recipient.
1858 if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust(::minRelayTxFee))
1860 CAmount nDust = newTxOut.GetDustThreshold(::minRelayTxFee) - newTxOut.nValue;
1861 newTxOut.nValue += nDust; // raise change until no more dust
1862 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
1864 if (vecSend[i].fSubtractFeeFromAmount)
1866 txNew.vout[i].nValue -= nDust;
1867 if (txNew.vout[i].IsDust(::minRelayTxFee))
1869 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
1877 // Never create dust outputs; if we would, just
1878 // add the dust to the fee.
1879 if (newTxOut.IsDust(::minRelayTxFee))
1882 reservekey.ReturnKey();
1886 // Insert change txn at random position:
1887 nChangePosRet = GetRandInt(txNew.vout.size()+1);
1888 vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosRet;
1889 txNew.vout.insert(position, newTxOut);
1893 reservekey.ReturnKey();
1897 // Note how the sequence number is set to max()-1 so that the
1898 // nLockTime set above actually works.
1899 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1900 txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
1901 std::numeric_limits<unsigned int>::max()-1));
1905 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1906 if (!SignSignature(*this, *coin.first, txNew, nIn++))
1908 strFailReason = _("Signing transaction failed");
1912 // Embed the constructed transaction data in wtxNew.
1913 *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
1916 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1917 if (nBytes >= MAX_STANDARD_TX_SIZE)
1919 strFailReason = _("Transaction too large");
1922 dPriority = wtxNew.ComputePriority(dPriority, nBytes);
1924 // Can we complete this as a free transaction?
1925 if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
1927 // Not enough fee: enough priority?
1928 double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
1929 // Not enough mempool history to estimate: use hard-coded AllowFree.
1930 if (dPriorityNeeded <= 0 && AllowFree(dPriority))
1933 // Small enough, and priority high enough, to send for free
1934 if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
1938 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
1940 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
1941 // because we must be at the maximum allowed fee.
1942 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
1944 strFailReason = _("Transaction too large for fee policy");
1948 if (nFeeRet >= nFeeNeeded)
1949 break; // Done, enough fee included.
1951 // Include more fee and try again.
1952 nFeeRet = nFeeNeeded;
1962 * Call after CreateTransaction unless you want to abort
1964 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1967 LOCK2(cs_main, cs_wallet);
1968 LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
1970 // This is only to keep the database open to defeat the auto-flush for the
1971 // duration of this scope. This is the only place where this optimization
1972 // maybe makes sense; please don't do it anywhere else.
1973 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r+") : NULL;
1975 // Take key pair from key pool so it won't be used again
1976 reservekey.KeepKey();
1978 // Add tx to wallet, because if it has change it's also ours,
1979 // otherwise just for transaction history.
1980 AddToWallet(wtxNew, false, pwalletdb);
1982 // Notify that old coins are spent
1983 set<CWalletTx*> setCoins;
1984 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1986 CWalletTx &coin = mapWallet[txin.prevout.hash];
1987 coin.BindWallet(this);
1988 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1995 // Track how many getdata requests our transaction gets
1996 mapRequestCount[wtxNew.GetHash()] = 0;
1998 if (fBroadcastTransactions)
2001 if (!wtxNew.AcceptToMemoryPool(false))
2003 // This must not fail. The transaction has already been signed and recorded.
2004 LogPrintf("CommitTransaction(): Error: Transaction not valid\n");
2007 wtxNew.RelayWalletTransaction();
2013 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
2015 // payTxFee is user-set "I want to pay this much"
2016 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
2017 // user selected total at least (default=true)
2018 if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
2019 nFeeNeeded = payTxFee.GetFeePerK();
2020 // User didn't set: use -txconfirmtarget to estimate...
2021 if (nFeeNeeded == 0)
2022 nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
2023 // ... unless we don't have enough mempool data, in which case fall
2024 // back to a hard-coded fee
2025 if (nFeeNeeded == 0)
2026 nFeeNeeded = minTxFee.GetFee(nTxBytes);
2027 // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
2028 if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
2029 nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
2030 // But always obey the maximum
2031 if (nFeeNeeded > maxTxFee)
2032 nFeeNeeded = maxTxFee;
2039 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2043 fFirstRunRet = false;
2044 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2045 if (nLoadWalletRet == DB_NEED_REWRITE)
2047 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2051 // Note: can't top-up keypool here, because wallet is locked.
2052 // User will be prompted to unlock wallet the next operation
2053 // that requires a new key.
2057 if (nLoadWalletRet != DB_LOAD_OK)
2058 return nLoadWalletRet;
2059 fFirstRunRet = !vchDefaultKey.IsValid();
2061 uiInterface.LoadWallet(this);
2067 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
2071 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
2072 if (nZapWalletTxRet == DB_NEED_REWRITE)
2074 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2078 // Note: can't top-up keypool here, because wallet is locked.
2079 // User will be prompted to unlock wallet the next operation
2080 // that requires a new key.
2084 if (nZapWalletTxRet != DB_LOAD_OK)
2085 return nZapWalletTxRet;
2091 bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
2093 bool fUpdated = false;
2095 LOCK(cs_wallet); // mapAddressBook
2096 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
2097 fUpdated = mi != mapAddressBook.end();
2098 mapAddressBook[address].name = strName;
2099 if (!strPurpose.empty()) /* update purpose only if requested */
2100 mapAddressBook[address].purpose = strPurpose;
2102 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
2103 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
2106 if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
2108 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2111 bool CWallet::DelAddressBook(const CTxDestination& address)
2114 LOCK(cs_wallet); // mapAddressBook
2118 // Delete destdata tuples associated with address
2119 std::string strAddress = CBitcoinAddress(address).ToString();
2120 BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
2122 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
2125 mapAddressBook.erase(address);
2128 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
2132 CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
2133 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2136 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2140 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2143 vchDefaultKey = vchPubKey;
2148 * Mark old keypool keys as used,
2149 * and generate all new keys
2151 bool CWallet::NewKeyPool()
2155 CWalletDB walletdb(strWalletFile);
2156 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2157 walletdb.ErasePool(nIndex);
2163 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
2164 for (int i = 0; i < nKeys; i++)
2166 int64_t nIndex = i+1;
2167 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2168 setKeyPool.insert(nIndex);
2170 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
2175 bool CWallet::TopUpKeyPool(unsigned int kpSize)
2183 CWalletDB walletdb(strWalletFile);
2186 unsigned int nTargetSize;
2188 nTargetSize = kpSize;
2190 nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0);
2192 while (setKeyPool.size() < (nTargetSize + 1))
2195 if (!setKeyPool.empty())
2196 nEnd = *(--setKeyPool.end()) + 1;
2197 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2198 throw runtime_error("TopUpKeyPool(): writing generated key failed");
2199 setKeyPool.insert(nEnd);
2200 LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
2206 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2209 keypool.vchPubKey = CPubKey();
2216 // Get the oldest key
2217 if(setKeyPool.empty())
2220 CWalletDB walletdb(strWalletFile);
2222 nIndex = *(setKeyPool.begin());
2223 setKeyPool.erase(setKeyPool.begin());
2224 if (!walletdb.ReadPool(nIndex, keypool))
2225 throw runtime_error("ReserveKeyFromKeyPool(): read failed");
2226 if (!HaveKey(keypool.vchPubKey.GetID()))
2227 throw runtime_error("ReserveKeyFromKeyPool(): unknown key in key pool");
2228 assert(keypool.vchPubKey.IsValid());
2229 LogPrintf("keypool reserve %d\n", nIndex);
2233 void CWallet::KeepKey(int64_t nIndex)
2235 // Remove from key pool
2238 CWalletDB walletdb(strWalletFile);
2239 walletdb.ErasePool(nIndex);
2241 LogPrintf("keypool keep %d\n", nIndex);
2244 void CWallet::ReturnKey(int64_t nIndex)
2246 // Return to key pool
2249 setKeyPool.insert(nIndex);
2251 LogPrintf("keypool return %d\n", nIndex);
2254 bool CWallet::GetKeyFromPool(CPubKey& result)
2260 ReserveKeyFromKeyPool(nIndex, keypool);
2263 if (IsLocked()) return false;
2264 result = GenerateNewKey();
2268 result = keypool.vchPubKey;
2273 int64_t CWallet::GetOldestKeyPoolTime()
2277 ReserveKeyFromKeyPool(nIndex, keypool);
2281 return keypool.nTime;
2284 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
2286 map<CTxDestination, CAmount> balances;
2290 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2292 CWalletTx *pcoin = &walletEntry.second;
2294 if (!CheckFinalTx(*pcoin) || !pcoin->IsTrusted())
2297 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2300 int nDepth = pcoin->GetDepthInMainChain();
2301 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
2304 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2306 CTxDestination addr;
2307 if (!IsMine(pcoin->vout[i]))
2309 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2312 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
2314 if (!balances.count(addr))
2316 balances[addr] += n;
2324 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2326 AssertLockHeld(cs_wallet); // mapWallet
2327 set< set<CTxDestination> > groupings;
2328 set<CTxDestination> grouping;
2330 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2332 CWalletTx *pcoin = &walletEntry.second;
2334 if (pcoin->vin.size() > 0)
2336 bool any_mine = false;
2337 // group all input addresses with each other
2338 BOOST_FOREACH(CTxIn txin, pcoin->vin)
2340 CTxDestination address;
2341 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
2343 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2345 grouping.insert(address);
2349 // group change with input addresses
2352 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2353 if (IsChange(txout))
2355 CTxDestination txoutAddr;
2356 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2358 grouping.insert(txoutAddr);
2361 if (grouping.size() > 0)
2363 groupings.insert(grouping);
2368 // group lone addrs by themselves
2369 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2370 if (IsMine(pcoin->vout[i]))
2372 CTxDestination address;
2373 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2375 grouping.insert(address);
2376 groupings.insert(grouping);
2381 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2382 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2383 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2385 // make a set of all the groups hit by this new group
2386 set< set<CTxDestination>* > hits;
2387 map< CTxDestination, set<CTxDestination>* >::iterator it;
2388 BOOST_FOREACH(CTxDestination address, grouping)
2389 if ((it = setmap.find(address)) != setmap.end())
2390 hits.insert((*it).second);
2392 // merge all hit groups into a new single group and delete old groups
2393 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2394 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2396 merged->insert(hit->begin(), hit->end());
2397 uniqueGroupings.erase(hit);
2400 uniqueGroupings.insert(merged);
2403 BOOST_FOREACH(CTxDestination element, *merged)
2404 setmap[element] = merged;
2407 set< set<CTxDestination> > ret;
2408 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2410 ret.insert(*uniqueGrouping);
2411 delete uniqueGrouping;
2417 set<CTxDestination> CWallet::GetAccountAddresses(string strAccount) const
2420 set<CTxDestination> result;
2421 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
2423 const CTxDestination& address = item.first;
2424 const string& strName = item.second.name;
2425 if (strName == strAccount)
2426 result.insert(address);
2431 bool CReserveKey::GetReservedKey(CPubKey& pubkey)
2436 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2438 vchPubKey = keypool.vchPubKey;
2443 assert(vchPubKey.IsValid());
2448 void CReserveKey::KeepKey()
2451 pwallet->KeepKey(nIndex);
2453 vchPubKey = CPubKey();
2456 void CReserveKey::ReturnKey()
2459 pwallet->ReturnKey(nIndex);
2461 vchPubKey = CPubKey();
2464 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2468 CWalletDB walletdb(strWalletFile);
2470 LOCK2(cs_main, cs_wallet);
2471 BOOST_FOREACH(const int64_t& id, setKeyPool)
2474 if (!walletdb.ReadPool(id, keypool))
2475 throw runtime_error("GetAllReserveKeyHashes(): read failed");
2476 assert(keypool.vchPubKey.IsValid());
2477 CKeyID keyID = keypool.vchPubKey.GetID();
2478 if (!HaveKey(keyID))
2479 throw runtime_error("GetAllReserveKeyHashes(): unknown key in key pool");
2480 setAddress.insert(keyID);
2484 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2488 // Only notify UI if this transaction is in this wallet
2489 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2490 if (mi != mapWallet.end())
2491 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2495 void CWallet::LockCoin(COutPoint& output)
2497 AssertLockHeld(cs_wallet); // setLockedCoins
2498 setLockedCoins.insert(output);
2501 void CWallet::UnlockCoin(COutPoint& output)
2503 AssertLockHeld(cs_wallet); // setLockedCoins
2504 setLockedCoins.erase(output);
2507 void CWallet::UnlockAllCoins()
2509 AssertLockHeld(cs_wallet); // setLockedCoins
2510 setLockedCoins.clear();
2513 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
2515 AssertLockHeld(cs_wallet); // setLockedCoins
2516 COutPoint outpt(hash, n);
2518 return (setLockedCoins.count(outpt) > 0);
2521 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
2523 AssertLockHeld(cs_wallet); // setLockedCoins
2524 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
2525 it != setLockedCoins.end(); it++) {
2526 COutPoint outpt = (*it);
2527 vOutpts.push_back(outpt);
2531 /** @} */ // end of Actions
2533 class CAffectedKeysVisitor : public boost::static_visitor<void> {
2535 const CKeyStore &keystore;
2536 std::vector<CKeyID> &vKeys;
2539 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
2541 void Process(const CScript &script) {
2543 std::vector<CTxDestination> vDest;
2545 if (ExtractDestinations(script, type, vDest, nRequired)) {
2546 BOOST_FOREACH(const CTxDestination &dest, vDest)
2547 boost::apply_visitor(*this, dest);
2551 void operator()(const CKeyID &keyId) {
2552 if (keystore.HaveKey(keyId))
2553 vKeys.push_back(keyId);
2556 void operator()(const CScriptID &scriptId) {
2558 if (keystore.GetCScript(scriptId, script))
2562 void operator()(const CNoDestination &none) {}
2565 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2566 AssertLockHeld(cs_wallet); // mapKeyMetadata
2567 mapKeyBirth.clear();
2569 // get birth times for keys with metadata
2570 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2571 if (it->second.nCreateTime)
2572 mapKeyBirth[it->first] = it->second.nCreateTime;
2574 // map in which we'll infer heights of other keys
2575 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
2576 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2577 std::set<CKeyID> setKeys;
2579 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2580 if (mapKeyBirth.count(keyid) == 0)
2581 mapKeyFirstBlock[keyid] = pindexMax;
2585 // if there are no such keys, we're done
2586 if (mapKeyFirstBlock.empty())
2589 // find first block that affects those keys, if there are any left
2590 std::vector<CKeyID> vAffected;
2591 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2592 // iterate over all wallet transactions...
2593 const CWalletTx &wtx = (*it).second;
2594 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2595 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
2596 // ... which are already in a block
2597 int nHeight = blit->second->nHeight;
2598 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2599 // iterate over all their outputs
2600 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
2601 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2602 // ... and all their affected keys
2603 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2604 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2605 rit->second = blit->second;
2612 // Extract block timestamps for those keys
2613 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2614 mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
2617 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
2619 if (boost::get<CNoDestination>(&dest))
2622 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
2625 return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
2628 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
2630 if (!mapAddressBook[dest].destdata.erase(key))
2634 return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
2637 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
2639 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
2643 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
2645 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
2646 if(i != mapAddressBook.end())
2648 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
2649 if(j != i->second.destdata.end())
2659 CKeyPool::CKeyPool()
2664 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
2667 vchPubKey = vchPubKeyIn;
2670 CWalletKey::CWalletKey(int64_t nExpires)
2672 nTimeCreated = (nExpires ? GetTime() : 0);
2673 nTimeExpires = nExpires;
2676 int CMerkleTx::SetMerkleBranch(const CBlock& block)
2678 AssertLockHeld(cs_main);
2681 // Update the tx's hashBlock
2682 hashBlock = block.GetHash();
2684 // Locate the transaction
2685 for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
2686 if (block.vtx[nIndex] == *(CTransaction*)this)
2688 if (nIndex == (int)block.vtx.size())
2690 vMerkleBranch.clear();
2692 LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
2696 // Fill in merkle branch
2697 vMerkleBranch = block.GetMerkleBranch(nIndex);
2699 // Is the tx in a block that's in the main chain
2700 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
2701 if (mi == mapBlockIndex.end())
2703 const CBlockIndex* pindex = (*mi).second;
2704 if (!pindex || !chainActive.Contains(pindex))
2707 return chainActive.Height() - pindex->nHeight + 1;
2710 int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const
2712 if (hashBlock.IsNull() || nIndex == -1)
2714 AssertLockHeld(cs_main);
2716 // Find the block it claims to be in
2717 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
2718 if (mi == mapBlockIndex.end())
2720 CBlockIndex* pindex = (*mi).second;
2721 if (!pindex || !chainActive.Contains(pindex))
2724 // Make sure the merkle branch connects to this block
2725 if (!fMerkleVerified)
2727 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
2729 fMerkleVerified = true;
2733 return chainActive.Height() - pindex->nHeight + 1;
2736 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
2738 AssertLockHeld(cs_main);
2739 int nResult = GetDepthInMainChainINTERNAL(pindexRet);
2740 if (nResult == 0 && !mempool.exists(GetHash()))
2741 return -1; // Not in chain, not in mempool
2746 int CMerkleTx::GetBlocksToMaturity() const
2750 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
2754 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectAbsurdFee)
2756 CValidationState state;
2757 return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectAbsurdFee);