1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
9 #include "checkpoints.h"
10 #include "coincontrol.h"
12 #include "script/script.h"
13 #include "script/sign.h"
16 #include "utilmoneystr.h"
20 #include <boost/algorithm/string/replace.hpp>
21 #include <boost/thread.hpp>
28 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
29 unsigned int nTxConfirmTarget = 1;
30 bool bSpendZeroConfChange = true;
31 bool fSendFreeTransactions = false;
32 bool fPayAtLeastCustomFee = true;
35 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
36 * Override with -mintxfee
38 CFeeRate CWallet::minTxFee = CFeeRate(10000);
40 /** @defgroup mapWallet
45 struct CompareValueOnly
47 bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
48 const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
50 return t1.first < t2.first;
54 std::string COutput::ToString() const
56 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
59 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
62 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
63 if (it == mapWallet.end())
68 CPubKey CWallet::GenerateNewKey()
70 AssertLockHeld(cs_wallet); // mapKeyMetadata
71 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
75 secret.MakeNewKey(fCompressed);
77 // Compressed public keys were introduced in version 0.6.0
79 SetMinVersion(FEATURE_COMPRPUBKEY);
81 CPubKey pubkey = secret.GetPubKey();
82 assert(secret.VerifyPubKey(pubkey));
84 // Create new metadata
85 int64_t nCreationTime = GetTime();
86 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
87 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
88 nTimeFirstKey = nCreationTime;
90 if (!AddKeyPubKey(secret, pubkey))
91 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
95 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
97 AssertLockHeld(cs_wallet); // mapKeyMetadata
98 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
101 // check if we need to remove from watch-only
103 script = GetScriptForDestination(pubkey.GetID());
104 if (HaveWatchOnly(script))
105 RemoveWatchOnly(script);
110 return CWalletDB(strWalletFile).WriteKey(pubkey,
112 mapKeyMetadata[pubkey.GetID()]);
117 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
118 const vector<unsigned char> &vchCryptedSecret)
120 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
126 if (pwalletdbEncryption)
127 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
129 mapKeyMetadata[vchPubKey.GetID()]);
131 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
133 mapKeyMetadata[vchPubKey.GetID()]);
138 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
140 AssertLockHeld(cs_wallet); // mapKeyMetadata
141 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
142 nTimeFirstKey = meta.nCreateTime;
144 mapKeyMetadata[pubkey.GetID()] = meta;
148 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
150 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
153 bool CWallet::AddCScript(const CScript& redeemScript)
155 if (!CCryptoKeyStore::AddCScript(redeemScript))
159 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
162 bool CWallet::LoadCScript(const CScript& redeemScript)
164 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
165 * that never can be redeemed. However, old wallets may still contain
166 * these. Do not add them to the wallet and warn. */
167 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
169 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
170 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",
171 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
175 return CCryptoKeyStore::AddCScript(redeemScript);
178 bool CWallet::AddWatchOnly(const CScript &dest)
180 if (!CCryptoKeyStore::AddWatchOnly(dest))
182 nTimeFirstKey = 1; // No birthday information for watch-only keys.
183 NotifyWatchonlyChanged(true);
186 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
189 bool CWallet::RemoveWatchOnly(const CScript &dest)
191 AssertLockHeld(cs_wallet);
192 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
194 if (!HaveWatchOnly())
195 NotifyWatchonlyChanged(false);
197 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
203 bool CWallet::LoadWatchOnly(const CScript &dest)
205 return CCryptoKeyStore::AddWatchOnly(dest);
208 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
211 CKeyingMaterial vMasterKey;
215 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
217 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
219 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
220 continue; // try another master key
221 if (CCryptoKeyStore::Unlock(vMasterKey))
228 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
230 bool fWasLocked = IsLocked();
237 CKeyingMaterial vMasterKey;
238 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
240 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
242 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
244 if (CCryptoKeyStore::Unlock(vMasterKey))
246 int64_t nStartTime = GetTimeMillis();
247 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
248 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
250 nStartTime = GetTimeMillis();
251 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
252 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
254 if (pMasterKey.second.nDeriveIterations < 25000)
255 pMasterKey.second.nDeriveIterations = 25000;
257 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
259 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
261 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
263 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
274 void CWallet::SetBestChain(const CBlockLocator& loc)
276 CWalletDB walletdb(strWalletFile);
277 walletdb.WriteBestBlock(loc);
280 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
282 LOCK(cs_wallet); // nWalletVersion
283 if (nWalletVersion >= nVersion)
286 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
287 if (fExplicit && nVersion > nWalletMaxVersion)
288 nVersion = FEATURE_LATEST;
290 nWalletVersion = nVersion;
292 if (nVersion > nWalletMaxVersion)
293 nWalletMaxVersion = nVersion;
297 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
298 if (nWalletVersion > 40000)
299 pwalletdb->WriteMinVersion(nWalletVersion);
307 bool CWallet::SetMaxVersion(int nVersion)
309 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
310 // cannot downgrade below current version
311 if (nWalletVersion > nVersion)
314 nWalletMaxVersion = nVersion;
319 set<uint256> CWallet::GetConflicts(const uint256& txid) const
322 AssertLockHeld(cs_wallet);
324 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
325 if (it == mapWallet.end())
327 const CWalletTx& wtx = it->second;
329 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
331 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
333 if (mapTxSpends.count(txin.prevout) <= 1)
334 continue; // No conflict if zero or one spends
335 range = mapTxSpends.equal_range(txin.prevout);
336 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
337 result.insert(it->second);
342 void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range)
344 // We want all the wallet transactions in range to have the same metadata as
345 // the oldest (smallest nOrderPos).
346 // So: find smallest nOrderPos:
348 int nMinOrderPos = std::numeric_limits<int>::max();
349 const CWalletTx* copyFrom = NULL;
350 for (TxSpends::iterator it = range.first; it != range.second; ++it)
352 const uint256& hash = it->second;
353 int n = mapWallet[hash].nOrderPos;
354 if (n < nMinOrderPos)
357 copyFrom = &mapWallet[hash];
360 // Now copy data from copyFrom to rest:
361 for (TxSpends::iterator it = range.first; it != range.second; ++it)
363 const uint256& hash = it->second;
364 CWalletTx* copyTo = &mapWallet[hash];
365 if (copyFrom == copyTo) continue;
366 copyTo->mapValue = copyFrom->mapValue;
367 copyTo->vOrderForm = copyFrom->vOrderForm;
368 // fTimeReceivedIsTxTime not copied on purpose
369 // nTimeReceived not copied on purpose
370 copyTo->nTimeSmart = copyFrom->nTimeSmart;
371 copyTo->fFromMe = copyFrom->fFromMe;
372 copyTo->strFromAccount = copyFrom->strFromAccount;
373 // nOrderPos not copied on purpose
374 // cached members not copied on purpose
379 * Outpoint is spent if any non-conflicted transaction
382 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
384 const COutPoint outpoint(hash, n);
385 pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
386 range = mapTxSpends.equal_range(outpoint);
388 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
390 const uint256& wtxid = it->second;
391 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
392 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
393 return true; // Spent
398 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
400 mapTxSpends.insert(make_pair(outpoint, wtxid));
402 pair<TxSpends::iterator, TxSpends::iterator> range;
403 range = mapTxSpends.equal_range(outpoint);
408 void CWallet::AddToSpends(const uint256& wtxid)
410 assert(mapWallet.count(wtxid));
411 CWalletTx& thisTx = mapWallet[wtxid];
412 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
415 BOOST_FOREACH(const CTxIn& txin, thisTx.vin)
416 AddToSpends(txin.prevout, wtxid);
419 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
424 CKeyingMaterial vMasterKey;
425 RandAddSeedPerfmon();
427 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
428 GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
430 CMasterKey kMasterKey;
431 RandAddSeedPerfmon();
433 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
434 GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
437 int64_t nStartTime = GetTimeMillis();
438 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
439 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
441 nStartTime = GetTimeMillis();
442 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
443 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
445 if (kMasterKey.nDeriveIterations < 25000)
446 kMasterKey.nDeriveIterations = 25000;
448 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
450 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
452 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
457 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
460 assert(!pwalletdbEncryption);
461 pwalletdbEncryption = new CWalletDB(strWalletFile);
462 if (!pwalletdbEncryption->TxnBegin()) {
463 delete pwalletdbEncryption;
464 pwalletdbEncryption = NULL;
467 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
470 if (!EncryptKeys(vMasterKey))
473 pwalletdbEncryption->TxnAbort();
474 delete pwalletdbEncryption;
476 // We now probably have half of our keys encrypted in memory, and half not...
477 // die and let the user reload their unencrypted wallet.
481 // Encryption was introduced in version 0.4.0
482 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
486 if (!pwalletdbEncryption->TxnCommit()) {
487 delete pwalletdbEncryption;
488 // We now have keys encrypted in memory, but not on disk...
489 // die to avoid confusion and let the user reload their unencrypted wallet.
493 delete pwalletdbEncryption;
494 pwalletdbEncryption = NULL;
498 Unlock(strWalletPassphrase);
502 // Need to completely rewrite the wallet file; if we don't, bdb might keep
503 // bits of the unencrypted private key in slack space in the database file.
504 CDB::Rewrite(strWalletFile);
507 NotifyStatusChanged(this);
512 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
514 AssertLockHeld(cs_wallet); // nOrderPosNext
515 int64_t nRet = nOrderPosNext++;
517 pwalletdb->WriteOrderPosNext(nOrderPosNext);
519 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
524 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
526 AssertLockHeld(cs_wallet); // mapWallet
527 CWalletDB walletdb(strWalletFile);
529 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
532 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
533 // would make this much faster for applications that do this a lot.
534 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
536 CWalletTx* wtx = &((*it).second);
537 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
540 walletdb.ListAccountCreditDebit(strAccount, acentries);
541 BOOST_FOREACH(CAccountingEntry& entry, acentries)
543 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
549 void CWallet::MarkDirty()
553 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
554 item.second.MarkDirty();
558 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet)
560 uint256 hash = wtxIn.GetHash();
564 mapWallet[hash] = wtxIn;
565 mapWallet[hash].BindWallet(this);
571 // Inserts only if not already there, returns tx inserted or tx found
572 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
573 CWalletTx& wtx = (*ret.first).second;
574 wtx.BindWallet(this);
575 bool fInsertedNew = ret.second;
578 wtx.nTimeReceived = GetAdjustedTime();
579 wtx.nOrderPos = IncOrderPosNext();
581 wtx.nTimeSmart = wtx.nTimeReceived;
582 if (wtxIn.hashBlock != 0)
584 if (mapBlockIndex.count(wtxIn.hashBlock))
586 int64_t latestNow = wtx.nTimeReceived;
587 int64_t latestEntry = 0;
589 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
590 int64_t latestTolerated = latestNow + 300;
591 std::list<CAccountingEntry> acentries;
592 TxItems txOrdered = OrderedTxItems(acentries);
593 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
595 CWalletTx *const pwtx = (*it).second.first;
598 CAccountingEntry *const pacentry = (*it).second.second;
602 nSmartTime = pwtx->nTimeSmart;
604 nSmartTime = pwtx->nTimeReceived;
607 nSmartTime = pacentry->nTime;
608 if (nSmartTime <= latestTolerated)
610 latestEntry = nSmartTime;
611 if (nSmartTime > latestNow)
612 latestNow = nSmartTime;
618 int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
619 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
622 LogPrintf("AddToWallet() : found %s in block %s not in index\n",
623 wtxIn.GetHash().ToString(),
624 wtxIn.hashBlock.ToString());
629 bool fUpdated = false;
633 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
635 wtx.hashBlock = wtxIn.hashBlock;
638 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
640 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
641 wtx.nIndex = wtxIn.nIndex;
644 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
646 wtx.fFromMe = wtxIn.fFromMe;
652 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
655 if (fInsertedNew || fUpdated)
656 if (!wtx.WriteToDisk())
659 // Break debit/credit balance caches:
662 // Notify UI of new or updated transaction
663 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
665 // notify an external script when a wallet transaction comes in or is updated
666 std::string strCmd = GetArg("-walletnotify", "");
668 if ( !strCmd.empty())
670 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
671 boost::thread t(runCommand, strCmd); // thread runs free
679 * Add a transaction to the wallet, or update it.
680 * pblock is optional, but should be provided if the transaction is known to be in a block.
681 * If fUpdate is true, existing transactions will be updated.
683 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
686 AssertLockHeld(cs_wallet);
687 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
688 if (fExisted && !fUpdate) return false;
689 if (fExisted || IsMine(tx) || IsFromMe(tx))
691 CWalletTx wtx(this,tx);
692 // Get merkle branch if transaction was found in a block
694 wtx.SetMerkleBranch(*pblock);
695 return AddToWallet(wtx);
701 void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
703 LOCK2(cs_main, cs_wallet);
704 if (!AddToWalletIfInvolvingMe(tx, pblock, true))
705 return; // Not one of ours
707 // If a transaction changes 'conflicted' state, that changes the balance
708 // available of the outputs it spends. So force those to be
710 BOOST_FOREACH(const CTxIn& txin, tx.vin)
712 if (mapWallet.count(txin.prevout.hash))
713 mapWallet[txin.prevout.hash].MarkDirty();
717 void CWallet::EraseFromWallet(const uint256 &hash)
723 if (mapWallet.erase(hash))
724 CWalletDB(strWalletFile).EraseTx(hash);
730 isminetype CWallet::IsMine(const CTxIn &txin) const
734 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
735 if (mi != mapWallet.end())
737 const CWalletTx& prev = (*mi).second;
738 if (txin.prevout.n < prev.vout.size())
739 return IsMine(prev.vout[txin.prevout.n]);
745 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
749 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
750 if (mi != mapWallet.end())
752 const CWalletTx& prev = (*mi).second;
753 if (txin.prevout.n < prev.vout.size())
754 if (IsMine(prev.vout[txin.prevout.n]) & filter)
755 return prev.vout[txin.prevout.n].nValue;
761 bool CWallet::IsChange(const CTxOut& txout) const
763 // TODO: fix handling of 'change' outputs. The assumption is that any
764 // payment to a script that is ours, but is not in the address book
765 // is change. That assumption is likely to break when we implement multisignature
766 // wallets that return change back into a multi-signature-protected address;
767 // a better way of identifying which outputs are 'the send' and which are
768 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
769 // which output, if any, was change).
770 if (::IsMine(*this, txout.scriptPubKey))
772 CTxDestination address;
773 if (!ExtractDestination(txout.scriptPubKey, address))
777 if (!mapAddressBook.count(address))
783 int64_t CWalletTx::GetTxTime() const
785 int64_t n = nTimeSmart;
786 return n ? n : nTimeReceived;
789 int CWalletTx::GetRequestCount() const
791 // Returns -1 if it wasn't being tracked
794 LOCK(pwallet->cs_wallet);
800 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
801 if (mi != pwallet->mapRequestCount.end())
802 nRequests = (*mi).second;
807 // Did anyone request this transaction?
808 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
809 if (mi != pwallet->mapRequestCount.end())
811 nRequests = (*mi).second;
813 // How about the block it's in?
814 if (nRequests == 0 && hashBlock != 0)
816 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
817 if (mi != pwallet->mapRequestCount.end())
818 nRequests = (*mi).second;
820 nRequests = 1; // If it's in someone else's block it must have got out
828 void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
829 list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
832 listReceived.clear();
834 strSentAccount = strFromAccount;
837 CAmount nDebit = GetDebit(filter);
838 if (nDebit > 0) // debit>0 means we signed/sent this transaction
840 CAmount nValueOut = GetValueOut();
841 nFee = nDebit - nValueOut;
845 for (unsigned int i = 0; i < vout.size(); ++i)
847 const CTxOut& txout = vout[i];
848 isminetype fIsMine = pwallet->IsMine(txout);
849 // Only need to handle txouts if AT LEAST one of these is true:
850 // 1) they debit from us (sent)
851 // 2) the output is to us (received)
854 // Don't report 'change' txouts
855 if (pwallet->IsChange(txout))
858 else if (!(fIsMine & filter))
861 // In either case, we need to get the destination address
862 CTxDestination address;
863 if (!ExtractDestination(txout.scriptPubKey, address))
865 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
866 this->GetHash().ToString());
867 address = CNoDestination();
870 COutputEntry output = {address, txout.nValue, (int)i};
872 // If we are debited by the transaction, add the output as a "sent" entry
874 listSent.push_back(output);
876 // If we are receiving the output, add it as a "received" entry
877 if (fIsMine & filter)
878 listReceived.push_back(output);
883 void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
884 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
886 nReceived = nSent = nFee = 0;
889 string strSentAccount;
890 list<COutputEntry> listReceived;
891 list<COutputEntry> listSent;
892 GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
894 if (strAccount == strSentAccount)
896 BOOST_FOREACH(const COutputEntry& s, listSent)
901 LOCK(pwallet->cs_wallet);
902 BOOST_FOREACH(const COutputEntry& r, listReceived)
904 if (pwallet->mapAddressBook.count(r.destination))
906 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
907 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
908 nReceived += r.amount;
910 else if (strAccount.empty())
912 nReceived += r.amount;
919 bool CWalletTx::WriteToDisk()
921 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
925 * Scan the block chain (starting in pindexStart) for transactions
926 * from or to us. If fUpdate is true, found transactions that already
927 * exist in the wallet will be updated.
929 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
932 int64_t nNow = GetTime();
934 CBlockIndex* pindex = pindexStart;
936 LOCK2(cs_main, cs_wallet);
938 // no need to read and scan block, if block was created before
939 // our wallet birthday (as adjusted for block time variability)
940 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
941 pindex = chainActive.Next(pindex);
943 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
944 double dProgressStart = Checkpoints::GuessVerificationProgress(pindex, false);
945 double dProgressTip = Checkpoints::GuessVerificationProgress(chainActive.Tip(), false);
948 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
949 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
952 ReadBlockFromDisk(block, pindex);
953 BOOST_FOREACH(CTransaction& tx, block.vtx)
955 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
958 pindex = chainActive.Next(pindex);
959 if (GetTime() >= nNow + 60) {
961 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(pindex));
964 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
969 void CWallet::ReacceptWalletTransactions()
971 LOCK2(cs_main, cs_wallet);
972 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
974 const uint256& wtxid = item.first;
975 CWalletTx& wtx = item.second;
976 assert(wtx.GetHash() == wtxid);
978 int nDepth = wtx.GetDepthInMainChain();
980 if (!wtx.IsCoinBase() && nDepth < 0)
982 // Try to add to memory pool
984 wtx.AcceptToMemoryPool(false);
989 void CWalletTx::RelayWalletTransaction()
993 if (GetDepthInMainChain() == 0) {
994 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
995 RelayTransaction((CTransaction)*this);
1000 set<uint256> CWalletTx::GetConflicts() const
1002 set<uint256> result;
1003 if (pwallet != NULL)
1005 uint256 myHash = GetHash();
1006 result = pwallet->GetConflicts(myHash);
1007 result.erase(myHash);
1012 void CWallet::ResendWalletTransactions()
1014 // Do this infrequently and randomly to avoid giving away
1015 // that these are our transactions.
1016 if (GetTime() < nNextResend)
1018 bool fFirst = (nNextResend == 0);
1019 nNextResend = GetTime() + GetRand(30 * 60);
1023 // Only do it if there's been a new block since last time
1024 if (nTimeBestReceived < nLastResend)
1026 nLastResend = GetTime();
1028 // Rebroadcast any of our txes that aren't in a block yet
1029 LogPrintf("ResendWalletTransactions()\n");
1032 // Sort them in chronological order
1033 multimap<unsigned int, CWalletTx*> mapSorted;
1034 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1036 CWalletTx& wtx = item.second;
1037 // Don't rebroadcast until it's had plenty of time that
1038 // it should have gotten in already by now.
1039 if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
1040 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1042 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1044 CWalletTx& wtx = *item.second;
1045 wtx.RelayWalletTransaction();
1050 /** @} */ // end of mapWallet
1055 /** @defgroup Actions
1061 CAmount CWallet::GetBalance() const
1065 LOCK2(cs_main, cs_wallet);
1066 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1068 const CWalletTx* pcoin = &(*it).second;
1069 if (pcoin->IsTrusted())
1070 nTotal += pcoin->GetAvailableCredit();
1077 CAmount CWallet::GetUnconfirmedBalance() const
1081 LOCK2(cs_main, cs_wallet);
1082 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1084 const CWalletTx* pcoin = &(*it).second;
1085 if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
1086 nTotal += pcoin->GetAvailableCredit();
1092 CAmount CWallet::GetImmatureBalance() const
1096 LOCK2(cs_main, cs_wallet);
1097 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1099 const CWalletTx* pcoin = &(*it).second;
1100 nTotal += pcoin->GetImmatureCredit();
1106 CAmount CWallet::GetWatchOnlyBalance() const
1110 LOCK2(cs_main, cs_wallet);
1111 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1113 const CWalletTx* pcoin = &(*it).second;
1114 if (pcoin->IsTrusted())
1115 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1122 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
1126 LOCK2(cs_main, cs_wallet);
1127 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1129 const CWalletTx* pcoin = &(*it).second;
1130 if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
1131 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1137 CAmount CWallet::GetImmatureWatchOnlyBalance() const
1141 LOCK2(cs_main, cs_wallet);
1142 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1144 const CWalletTx* pcoin = &(*it).second;
1145 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1152 * populate vCoins with vector of available COutputs.
1154 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1159 LOCK2(cs_main, cs_wallet);
1160 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1162 const uint256& wtxid = it->first;
1163 const CWalletTx* pcoin = &(*it).second;
1165 if (!IsFinalTx(*pcoin))
1168 if (fOnlyConfirmed && !pcoin->IsTrusted())
1171 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1174 int nDepth = pcoin->GetDepthInMainChain();
1178 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1179 isminetype mine = IsMine(pcoin->vout[i]);
1180 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
1181 !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue > 0 &&
1182 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1183 vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO));
1189 static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
1190 vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
1192 vector<char> vfIncluded;
1194 vfBest.assign(vValue.size(), true);
1195 nBest = nTotalLower;
1197 seed_insecure_rand();
1199 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1201 vfIncluded.assign(vValue.size(), false);
1203 bool fReachedTarget = false;
1204 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1206 for (unsigned int i = 0; i < vValue.size(); i++)
1208 //The solver here uses a randomized algorithm,
1209 //the randomness serves no real security purpose but is just
1210 //needed to prevent degenerate behavior and it is important
1211 //that the rng is fast. We do not use a constant random sequence,
1212 //because there may be some privacy improvement by making
1213 //the selection random.
1214 if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
1216 nTotal += vValue[i].first;
1217 vfIncluded[i] = true;
1218 if (nTotal >= nTargetValue)
1220 fReachedTarget = true;
1224 vfBest = vfIncluded;
1226 nTotal -= vValue[i].first;
1227 vfIncluded[i] = false;
1235 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
1236 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
1238 setCoinsRet.clear();
1241 // List of values less than target
1242 pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1243 coinLowestLarger.first = std::numeric_limits<CAmount>::max();
1244 coinLowestLarger.second.first = NULL;
1245 vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
1246 CAmount nTotalLower = 0;
1248 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1250 BOOST_FOREACH(const COutput &output, vCoins)
1252 if (!output.fSpendable)
1255 const CWalletTx *pcoin = output.tx;
1257 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
1261 CAmount n = pcoin->vout[i].nValue;
1263 pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1265 if (n == nTargetValue)
1267 setCoinsRet.insert(coin.second);
1268 nValueRet += coin.first;
1271 else if (n < nTargetValue + CENT)
1273 vValue.push_back(coin);
1276 else if (n < coinLowestLarger.first)
1278 coinLowestLarger = coin;
1282 if (nTotalLower == nTargetValue)
1284 for (unsigned int i = 0; i < vValue.size(); ++i)
1286 setCoinsRet.insert(vValue[i].second);
1287 nValueRet += vValue[i].first;
1292 if (nTotalLower < nTargetValue)
1294 if (coinLowestLarger.second.first == NULL)
1296 setCoinsRet.insert(coinLowestLarger.second);
1297 nValueRet += coinLowestLarger.first;
1301 // Solve subset sum by stochastic approximation
1302 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1303 vector<char> vfBest;
1306 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1307 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1308 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1310 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1311 // or the next bigger coin is closer), return the bigger coin
1312 if (coinLowestLarger.second.first &&
1313 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1315 setCoinsRet.insert(coinLowestLarger.second);
1316 nValueRet += coinLowestLarger.first;
1319 for (unsigned int i = 0; i < vValue.size(); i++)
1322 setCoinsRet.insert(vValue[i].second);
1323 nValueRet += vValue[i].first;
1326 LogPrint("selectcoins", "SelectCoins() best subset: ");
1327 for (unsigned int i = 0; i < vValue.size(); i++)
1329 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
1330 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
1336 bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
1338 vector<COutput> vCoins;
1339 AvailableCoins(vCoins, true, coinControl);
1341 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1342 if (coinControl && coinControl->HasSelected())
1344 BOOST_FOREACH(const COutput& out, vCoins)
1348 nValueRet += out.tx->vout[out.i].nValue;
1349 setCoinsRet.insert(make_pair(out.tx, out.i));
1351 return (nValueRet >= nTargetValue);
1354 return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1355 SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1356 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet)));
1362 bool CWallet::CreateTransaction(const vector<pair<CScript, CAmount> >& vecSend,
1363 CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl)
1366 BOOST_FOREACH (const PAIRTYPE(CScript, CAmount)& s, vecSend)
1370 strFailReason = _("Transaction amounts must be positive");
1375 if (vecSend.empty() || nValue < 0)
1377 strFailReason = _("Transaction amounts must be positive");
1381 wtxNew.fTimeReceivedIsTxTime = true;
1382 wtxNew.BindWallet(this);
1383 CMutableTransaction txNew;
1386 LOCK2(cs_main, cs_wallet);
1393 wtxNew.fFromMe = true;
1395 CAmount nTotalValue = nValue + nFeeRet;
1396 double dPriority = 0;
1397 // vouts to the payees
1398 BOOST_FOREACH (const PAIRTYPE(CScript, CAmount)& s, vecSend)
1400 CTxOut txout(s.second, s.first);
1401 if (txout.IsDust(::minRelayTxFee))
1403 strFailReason = _("Transaction amount too small");
1406 txNew.vout.push_back(txout);
1409 // Choose coins to use
1410 set<pair<const CWalletTx*,unsigned int> > setCoins;
1411 CAmount nValueIn = 0;
1412 if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl))
1414 strFailReason = _("Insufficient funds");
1417 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1419 CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
1420 //The priority after the next block (depth+1) is used instead of the current,
1421 //reflecting an assumption the user would accept a bit more delay for
1422 //a chance at a free transaction.
1423 dPriority += (double)nCredit * (pcoin.first->GetDepthInMainChain()+1);
1426 CAmount nChange = nValueIn - nValue - nFeeRet;
1430 // Fill a vout to ourself
1431 // TODO: pass in scriptChange instead of reservekey so
1432 // change transaction isn't always pay-to-bitcoin-address
1433 CScript scriptChange;
1435 // coin control: send change to custom address
1436 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1437 scriptChange = GetScriptForDestination(coinControl->destChange);
1439 // no coin control: send change to newly generated address
1442 // Note: We use a new key here to keep it from being obvious which side is the change.
1443 // The drawback is that by not reusing a previous key, the change may be lost if a
1444 // backup is restored, if the backup doesn't have the new private key for the change.
1445 // If we reused the old key, it would be possible to add code to look for and
1446 // rediscover unknown transactions that were written with keys of ours to recover
1447 // post-backup change.
1449 // Reserve a new key pair from key pool
1452 ret = reservekey.GetReservedKey(vchPubKey);
1453 assert(ret); // should never fail, as we just unlocked
1455 scriptChange = GetScriptForDestination(vchPubKey.GetID());
1458 CTxOut newTxOut(nChange, scriptChange);
1460 // Never create dust outputs; if we would, just
1461 // add the dust to the fee.
1462 if (newTxOut.IsDust(::minRelayTxFee))
1465 reservekey.ReturnKey();
1469 // Insert change txn at random position:
1470 vector<CTxOut>::iterator position = txNew.vout.begin()+GetRandInt(txNew.vout.size()+1);
1471 txNew.vout.insert(position, newTxOut);
1475 reservekey.ReturnKey();
1478 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1479 txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1483 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1484 if (!SignSignature(*this, *coin.first, txNew, nIn++))
1486 strFailReason = _("Signing transaction failed");
1490 // Embed the constructed transaction data in wtxNew.
1491 *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
1494 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1495 if (nBytes >= MAX_STANDARD_TX_SIZE)
1497 strFailReason = _("Transaction too large");
1500 dPriority = wtxNew.ComputePriority(dPriority, nBytes);
1502 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
1504 if (nFeeRet >= nFeeNeeded)
1505 break; // Done, enough fee included.
1507 // Too big to send for free? Include more fee and try again:
1508 if (!fSendFreeTransactions || nBytes > MAX_FREE_TRANSACTION_CREATE_SIZE)
1510 nFeeRet = nFeeNeeded;
1514 // Not enough fee: enough priority?
1515 double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
1516 // Not enough mempool history to estimate: use hard-coded AllowFree.
1517 if (dPriorityNeeded <= 0 && AllowFree(dPriority))
1520 // Small enough, and priority high enough, to send for free
1521 if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
1524 // Include more fee and try again.
1525 nFeeRet = nFeeNeeded;
1533 bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue,
1534 CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl)
1536 vector< pair<CScript, CAmount> > vecSend;
1537 vecSend.push_back(make_pair(scriptPubKey, nValue));
1538 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl);
1542 * Call after CreateTransaction unless you want to abort
1544 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1547 LOCK2(cs_main, cs_wallet);
1548 LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
1550 // This is only to keep the database open to defeat the auto-flush for the
1551 // duration of this scope. This is the only place where this optimization
1552 // maybe makes sense; please don't do it anywhere else.
1553 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1555 // Take key pair from key pool so it won't be used again
1556 reservekey.KeepKey();
1558 // Add tx to wallet, because if it has change it's also ours,
1559 // otherwise just for transaction history.
1560 AddToWallet(wtxNew);
1562 // Notify that old coins are spent
1563 set<CWalletTx*> setCoins;
1564 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1566 CWalletTx &coin = mapWallet[txin.prevout.hash];
1567 coin.BindWallet(this);
1568 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1575 // Track how many getdata requests our transaction gets
1576 mapRequestCount[wtxNew.GetHash()] = 0;
1579 if (!wtxNew.AcceptToMemoryPool(false))
1581 // This must not fail. The transaction has already been signed and recorded.
1582 LogPrintf("CommitTransaction() : Error: Transaction not valid");
1585 wtxNew.RelayWalletTransaction();
1593 string CWallet::SendMoney(const CTxDestination &address, CAmount nValue, CWalletTx& wtxNew)
1597 return _("Invalid amount");
1598 if (nValue > GetBalance())
1599 return _("Insufficient funds");
1604 strError = _("Error: Wallet locked, unable to create transaction!");
1605 LogPrintf("SendMoney() : %s", strError);
1609 // Parse Bitcoin address
1610 CScript scriptPubKey = GetScriptForDestination(address);
1612 // Create and send the transaction
1613 CReserveKey reservekey(this);
1614 CAmount nFeeRequired;
1615 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strError))
1617 if (nValue + nFeeRequired > GetBalance())
1618 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));
1619 LogPrintf("SendMoney() : %s\n", strError);
1622 if (!CommitTransaction(wtxNew, reservekey))
1623 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.");
1630 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
1632 // payTxFee is user-set "I want to pay this much"
1633 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
1634 // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
1635 if (nFeeNeeded > 0 && nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
1636 nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
1637 // user selected total at least (default=true)
1638 if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
1639 nFeeNeeded = payTxFee.GetFeePerK();
1640 // User didn't set: use -txconfirmtarget to estimate...
1641 if (nFeeNeeded == 0)
1642 nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
1643 // ... unless we don't have enough mempool data, in which case fall
1644 // back to a hard-coded fee
1645 if (nFeeNeeded == 0)
1646 nFeeNeeded = minTxFee.GetFee(nTxBytes);
1653 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1657 fFirstRunRet = false;
1658 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1659 if (nLoadWalletRet == DB_NEED_REWRITE)
1661 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1665 // Note: can't top-up keypool here, because wallet is locked.
1666 // User will be prompted to unlock wallet the next operation
1667 // the requires a new key.
1671 if (nLoadWalletRet != DB_LOAD_OK)
1672 return nLoadWalletRet;
1673 fFirstRunRet = !vchDefaultKey.IsValid();
1675 uiInterface.LoadWallet(this);
1681 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
1685 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
1686 if (nZapWalletTxRet == DB_NEED_REWRITE)
1688 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1692 // Note: can't top-up keypool here, because wallet is locked.
1693 // User will be prompted to unlock wallet the next operation
1694 // that requires a new key.
1698 if (nZapWalletTxRet != DB_LOAD_OK)
1699 return nZapWalletTxRet;
1705 bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
1707 bool fUpdated = false;
1709 LOCK(cs_wallet); // mapAddressBook
1710 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
1711 fUpdated = mi != mapAddressBook.end();
1712 mapAddressBook[address].name = strName;
1713 if (!strPurpose.empty()) /* update purpose only if requested */
1714 mapAddressBook[address].purpose = strPurpose;
1716 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
1717 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
1720 if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
1722 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1725 bool CWallet::DelAddressBook(const CTxDestination& address)
1728 LOCK(cs_wallet); // mapAddressBook
1732 // Delete destdata tuples associated with address
1733 std::string strAddress = CBitcoinAddress(address).ToString();
1734 BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
1736 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
1739 mapAddressBook.erase(address);
1742 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
1746 CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
1747 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1750 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
1754 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1757 vchDefaultKey = vchPubKey;
1762 * Mark old keypool keys as used,
1763 * and generate all new keys
1765 bool CWallet::NewKeyPool()
1769 CWalletDB walletdb(strWalletFile);
1770 BOOST_FOREACH(int64_t nIndex, setKeyPool)
1771 walletdb.ErasePool(nIndex);
1777 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
1778 for (int i = 0; i < nKeys; i++)
1780 int64_t nIndex = i+1;
1781 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1782 setKeyPool.insert(nIndex);
1784 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
1789 bool CWallet::TopUpKeyPool(unsigned int kpSize)
1797 CWalletDB walletdb(strWalletFile);
1800 unsigned int nTargetSize;
1802 nTargetSize = kpSize;
1804 nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0);
1806 while (setKeyPool.size() < (nTargetSize + 1))
1809 if (!setKeyPool.empty())
1810 nEnd = *(--setKeyPool.end()) + 1;
1811 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1812 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1813 setKeyPool.insert(nEnd);
1814 LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
1820 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
1823 keypool.vchPubKey = CPubKey();
1830 // Get the oldest key
1831 if(setKeyPool.empty())
1834 CWalletDB walletdb(strWalletFile);
1836 nIndex = *(setKeyPool.begin());
1837 setKeyPool.erase(setKeyPool.begin());
1838 if (!walletdb.ReadPool(nIndex, keypool))
1839 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1840 if (!HaveKey(keypool.vchPubKey.GetID()))
1841 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1842 assert(keypool.vchPubKey.IsValid());
1843 LogPrintf("keypool reserve %d\n", nIndex);
1847 void CWallet::KeepKey(int64_t nIndex)
1849 // Remove from key pool
1852 CWalletDB walletdb(strWalletFile);
1853 walletdb.ErasePool(nIndex);
1855 LogPrintf("keypool keep %d\n", nIndex);
1858 void CWallet::ReturnKey(int64_t nIndex)
1860 // Return to key pool
1863 setKeyPool.insert(nIndex);
1865 LogPrintf("keypool return %d\n", nIndex);
1868 bool CWallet::GetKeyFromPool(CPubKey& result)
1874 ReserveKeyFromKeyPool(nIndex, keypool);
1877 if (IsLocked()) return false;
1878 result = GenerateNewKey();
1882 result = keypool.vchPubKey;
1887 int64_t CWallet::GetOldestKeyPoolTime()
1891 ReserveKeyFromKeyPool(nIndex, keypool);
1895 return keypool.nTime;
1898 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
1900 map<CTxDestination, CAmount> balances;
1904 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1906 CWalletTx *pcoin = &walletEntry.second;
1908 if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted())
1911 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1914 int nDepth = pcoin->GetDepthInMainChain();
1915 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
1918 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1920 CTxDestination addr;
1921 if (!IsMine(pcoin->vout[i]))
1923 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
1926 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
1928 if (!balances.count(addr))
1930 balances[addr] += n;
1938 set< set<CTxDestination> > CWallet::GetAddressGroupings()
1940 AssertLockHeld(cs_wallet); // mapWallet
1941 set< set<CTxDestination> > groupings;
1942 set<CTxDestination> grouping;
1944 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1946 CWalletTx *pcoin = &walletEntry.second;
1948 if (pcoin->vin.size() > 0)
1950 bool any_mine = false;
1951 // group all input addresses with each other
1952 BOOST_FOREACH(CTxIn txin, pcoin->vin)
1954 CTxDestination address;
1955 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
1957 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
1959 grouping.insert(address);
1963 // group change with input addresses
1966 BOOST_FOREACH(CTxOut txout, pcoin->vout)
1967 if (IsChange(txout))
1969 CTxDestination txoutAddr;
1970 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
1972 grouping.insert(txoutAddr);
1975 if (grouping.size() > 0)
1977 groupings.insert(grouping);
1982 // group lone addrs by themselves
1983 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1984 if (IsMine(pcoin->vout[i]))
1986 CTxDestination address;
1987 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
1989 grouping.insert(address);
1990 groupings.insert(grouping);
1995 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
1996 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
1997 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
1999 // make a set of all the groups hit by this new group
2000 set< set<CTxDestination>* > hits;
2001 map< CTxDestination, set<CTxDestination>* >::iterator it;
2002 BOOST_FOREACH(CTxDestination address, grouping)
2003 if ((it = setmap.find(address)) != setmap.end())
2004 hits.insert((*it).second);
2006 // merge all hit groups into a new single group and delete old groups
2007 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2008 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2010 merged->insert(hit->begin(), hit->end());
2011 uniqueGroupings.erase(hit);
2014 uniqueGroupings.insert(merged);
2017 BOOST_FOREACH(CTxDestination element, *merged)
2018 setmap[element] = merged;
2021 set< set<CTxDestination> > ret;
2022 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2024 ret.insert(*uniqueGrouping);
2025 delete uniqueGrouping;
2031 set<CTxDestination> CWallet::GetAccountAddresses(string strAccount) const
2033 AssertLockHeld(cs_wallet); // mapWallet
2034 set<CTxDestination> result;
2035 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
2037 const CTxDestination& address = item.first;
2038 const string& strName = item.second.name;
2039 if (strName == strAccount)
2040 result.insert(address);
2045 bool CReserveKey::GetReservedKey(CPubKey& pubkey)
2050 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2052 vchPubKey = keypool.vchPubKey;
2057 assert(vchPubKey.IsValid());
2062 void CReserveKey::KeepKey()
2065 pwallet->KeepKey(nIndex);
2067 vchPubKey = CPubKey();
2070 void CReserveKey::ReturnKey()
2073 pwallet->ReturnKey(nIndex);
2075 vchPubKey = CPubKey();
2078 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2082 CWalletDB walletdb(strWalletFile);
2084 LOCK2(cs_main, cs_wallet);
2085 BOOST_FOREACH(const int64_t& id, setKeyPool)
2088 if (!walletdb.ReadPool(id, keypool))
2089 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2090 assert(keypool.vchPubKey.IsValid());
2091 CKeyID keyID = keypool.vchPubKey.GetID();
2092 if (!HaveKey(keyID))
2093 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2094 setAddress.insert(keyID);
2098 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2102 // Only notify UI if this transaction is in this wallet
2103 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2104 if (mi != mapWallet.end())
2105 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2109 void CWallet::LockCoin(COutPoint& output)
2111 AssertLockHeld(cs_wallet); // setLockedCoins
2112 setLockedCoins.insert(output);
2115 void CWallet::UnlockCoin(COutPoint& output)
2117 AssertLockHeld(cs_wallet); // setLockedCoins
2118 setLockedCoins.erase(output);
2121 void CWallet::UnlockAllCoins()
2123 AssertLockHeld(cs_wallet); // setLockedCoins
2124 setLockedCoins.clear();
2127 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
2129 AssertLockHeld(cs_wallet); // setLockedCoins
2130 COutPoint outpt(hash, n);
2132 return (setLockedCoins.count(outpt) > 0);
2135 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
2137 AssertLockHeld(cs_wallet); // setLockedCoins
2138 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
2139 it != setLockedCoins.end(); it++) {
2140 COutPoint outpt = (*it);
2141 vOutpts.push_back(outpt);
2145 /** @} */ // end of Actions
2147 class CAffectedKeysVisitor : public boost::static_visitor<void> {
2149 const CKeyStore &keystore;
2150 std::vector<CKeyID> &vKeys;
2153 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
2155 void Process(const CScript &script) {
2157 std::vector<CTxDestination> vDest;
2159 if (ExtractDestinations(script, type, vDest, nRequired)) {
2160 BOOST_FOREACH(const CTxDestination &dest, vDest)
2161 boost::apply_visitor(*this, dest);
2165 void operator()(const CKeyID &keyId) {
2166 if (keystore.HaveKey(keyId))
2167 vKeys.push_back(keyId);
2170 void operator()(const CScriptID &scriptId) {
2172 if (keystore.GetCScript(scriptId, script))
2176 void operator()(const CNoDestination &none) {}
2179 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2180 AssertLockHeld(cs_wallet); // mapKeyMetadata
2181 mapKeyBirth.clear();
2183 // get birth times for keys with metadata
2184 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2185 if (it->second.nCreateTime)
2186 mapKeyBirth[it->first] = it->second.nCreateTime;
2188 // map in which we'll infer heights of other keys
2189 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
2190 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2191 std::set<CKeyID> setKeys;
2193 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2194 if (mapKeyBirth.count(keyid) == 0)
2195 mapKeyFirstBlock[keyid] = pindexMax;
2199 // if there are no such keys, we're done
2200 if (mapKeyFirstBlock.empty())
2203 // find first block that affects those keys, if there are any left
2204 std::vector<CKeyID> vAffected;
2205 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2206 // iterate over all wallet transactions...
2207 const CWalletTx &wtx = (*it).second;
2208 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2209 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
2210 // ... which are already in a block
2211 int nHeight = blit->second->nHeight;
2212 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2213 // iterate over all their outputs
2214 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
2215 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2216 // ... and all their affected keys
2217 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2218 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2219 rit->second = blit->second;
2226 // Extract block timestamps for those keys
2227 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2228 mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
2231 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
2233 if (boost::get<CNoDestination>(&dest))
2236 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
2239 return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
2242 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
2244 if (!mapAddressBook[dest].destdata.erase(key))
2248 return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
2251 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
2253 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
2257 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
2259 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
2260 if(i != mapAddressBook.end())
2262 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
2263 if(j != i->second.destdata.end())
2273 CKeyPool::CKeyPool()
2278 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
2281 vchPubKey = vchPubKeyIn;
2284 CWalletKey::CWalletKey(int64_t nExpires)
2286 nTimeCreated = (nExpires ? GetTime() : 0);
2287 nTimeExpires = nExpires;
2290 int CMerkleTx::SetMerkleBranch(const CBlock& block)
2292 AssertLockHeld(cs_main);
2295 // Update the tx's hashBlock
2296 hashBlock = block.GetHash();
2298 // Locate the transaction
2299 for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
2300 if (block.vtx[nIndex] == *(CTransaction*)this)
2302 if (nIndex == (int)block.vtx.size())
2304 vMerkleBranch.clear();
2306 LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
2310 // Fill in merkle branch
2311 vMerkleBranch = block.GetMerkleBranch(nIndex);
2313 // Is the tx in a block that's in the main chain
2314 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
2315 if (mi == mapBlockIndex.end())
2317 const CBlockIndex* pindex = (*mi).second;
2318 if (!pindex || !chainActive.Contains(pindex))
2321 return chainActive.Height() - pindex->nHeight + 1;
2324 int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const
2326 if (hashBlock == 0 || nIndex == -1)
2328 AssertLockHeld(cs_main);
2330 // Find the block it claims to be in
2331 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
2332 if (mi == mapBlockIndex.end())
2334 CBlockIndex* pindex = (*mi).second;
2335 if (!pindex || !chainActive.Contains(pindex))
2338 // Make sure the merkle branch connects to this block
2339 if (!fMerkleVerified)
2341 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
2343 fMerkleVerified = true;
2347 return chainActive.Height() - pindex->nHeight + 1;
2350 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
2352 AssertLockHeld(cs_main);
2353 int nResult = GetDepthInMainChainINTERNAL(pindexRet);
2354 if (nResult == 0 && !mempool.exists(GetHash()))
2355 return -1; // Not in chain, not in mempool
2360 int CMerkleTx::GetBlocksToMaturity() const
2364 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
2368 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectInsaneFee)
2370 CValidationState state;
2371 return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectInsaneFee);