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/validation.h"
15 #include "script/script.h"
16 #include "script/sign.h"
18 #include "utilmoneystr.h"
19 #include "zcash/Note.hpp"
24 #include <boost/algorithm/string/replace.hpp>
25 #include <boost/filesystem.hpp>
26 #include <boost/thread.hpp>
29 using namespace libzcash;
34 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
35 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
36 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
37 bool bSpendZeroConfChange = true;
38 bool fSendFreeTransactions = false;
39 bool fPayAtLeastCustomFee = true;
42 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
43 * Override with -mintxfee
45 CFeeRate CWallet::minTxFee = CFeeRate(1000);
47 /** @defgroup mapWallet
52 struct CompareValueOnly
54 bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
55 const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
57 return t1.first < t2.first;
61 std::string JSOutPoint::ToString() const
63 return strprintf("JSOutPoint(%s, %d, %d)", hash.ToString().substr(0,10), js, n);
66 std::string COutput::ToString() const
68 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
71 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
74 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
75 if (it == mapWallet.end())
80 // Generate a new spending key and return its public payment address
81 CZCPaymentAddress CWallet::GenerateNewZKey()
83 AssertLockHeld(cs_wallet); // mapZKeyMetadata
84 auto k = SpendingKey::random();
85 auto addr = k.address();
87 // Check for collision, even though it is unlikely to ever occur
88 if (CCryptoKeyStore::HaveSpendingKey(addr))
89 throw std::runtime_error("CWallet::GenerateNewZKey(): Collision detected");
91 // Create new metadata
92 int64_t nCreationTime = GetTime();
93 mapZKeyMetadata[addr] = CKeyMetadata(nCreationTime);
95 CZCPaymentAddress pubaddr(addr);
97 throw std::runtime_error("CWallet::GenerateNewZKey(): AddZKey failed");
101 // Add spending key to keystore and persist to disk
102 bool CWallet::AddZKey(const libzcash::SpendingKey &key)
104 AssertLockHeld(cs_wallet); // mapZKeyMetadata
105 auto addr = key.address();
107 if (!CCryptoKeyStore::AddSpendingKey(key))
110 // check if we need to remove from viewing keys
111 if (HaveViewingKey(addr))
112 RemoveViewingKey(key.viewing_key());
118 return CWalletDB(strWalletFile).WriteZKey(addr,
120 mapZKeyMetadata[addr]);
125 CPubKey CWallet::GenerateNewKey()
127 AssertLockHeld(cs_wallet); // mapKeyMetadata
128 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
131 secret.MakeNewKey(fCompressed);
133 // Compressed public keys were introduced in version 0.6.0
135 SetMinVersion(FEATURE_COMPRPUBKEY);
137 CPubKey pubkey = secret.GetPubKey();
138 assert(secret.VerifyPubKey(pubkey));
140 // Create new metadata
141 int64_t nCreationTime = GetTime();
142 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
143 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
144 nTimeFirstKey = nCreationTime;
146 if (!AddKeyPubKey(secret, pubkey))
147 throw std::runtime_error("CWallet::GenerateNewKey(): AddKey failed");
151 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
153 AssertLockHeld(cs_wallet); // mapKeyMetadata
154 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
157 // check if we need to remove from watch-only
159 script = GetScriptForDestination(pubkey.GetID());
160 if (HaveWatchOnly(script))
161 RemoveWatchOnly(script);
166 return CWalletDB(strWalletFile).WriteKey(pubkey,
168 mapKeyMetadata[pubkey.GetID()]);
173 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
174 const vector<unsigned char> &vchCryptedSecret)
177 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
183 if (pwalletdbEncryption)
184 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
186 mapKeyMetadata[vchPubKey.GetID()]);
188 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
190 mapKeyMetadata[vchPubKey.GetID()]);
196 bool CWallet::AddCryptedSpendingKey(const libzcash::PaymentAddress &address,
197 const libzcash::ReceivingKey &rk,
198 const std::vector<unsigned char> &vchCryptedSecret)
200 if (!CCryptoKeyStore::AddCryptedSpendingKey(address, rk, vchCryptedSecret))
206 if (pwalletdbEncryption) {
207 return pwalletdbEncryption->WriteCryptedZKey(address,
210 mapZKeyMetadata[address]);
212 return CWalletDB(strWalletFile).WriteCryptedZKey(address,
215 mapZKeyMetadata[address]);
221 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
223 AssertLockHeld(cs_wallet); // mapKeyMetadata
224 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
225 nTimeFirstKey = meta.nCreateTime;
227 mapKeyMetadata[pubkey.GetID()] = meta;
231 bool CWallet::LoadZKeyMetadata(const PaymentAddress &addr, const CKeyMetadata &meta)
233 AssertLockHeld(cs_wallet); // mapZKeyMetadata
234 mapZKeyMetadata[addr] = meta;
238 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
240 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
243 bool CWallet::LoadCryptedZKey(const libzcash::PaymentAddress &addr, const libzcash::ReceivingKey &rk, const std::vector<unsigned char> &vchCryptedSecret)
245 return CCryptoKeyStore::AddCryptedSpendingKey(addr, rk, vchCryptedSecret);
248 bool CWallet::LoadZKey(const libzcash::SpendingKey &key)
250 return CCryptoKeyStore::AddSpendingKey(key);
253 bool CWallet::AddViewingKey(const libzcash::ViewingKey &vk)
255 if (!CCryptoKeyStore::AddViewingKey(vk)) {
258 nTimeFirstKey = 1; // No birthday information for viewing keys.
262 return CWalletDB(strWalletFile).WriteViewingKey(vk);
265 bool CWallet::RemoveViewingKey(const libzcash::ViewingKey &vk)
267 AssertLockHeld(cs_wallet);
268 if (!CCryptoKeyStore::RemoveViewingKey(vk)) {
272 if (!CWalletDB(strWalletFile).EraseViewingKey(vk)) {
280 bool CWallet::LoadViewingKey(const libzcash::ViewingKey &vk)
282 return CCryptoKeyStore::AddViewingKey(vk);
285 bool CWallet::AddCScript(const CScript& redeemScript)
287 if (!CCryptoKeyStore::AddCScript(redeemScript))
291 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
294 bool CWallet::LoadCScript(const CScript& redeemScript)
296 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
297 * that never can be redeemed. However, old wallets may still contain
298 * these. Do not add them to the wallet and warn. */
299 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
301 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
302 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",
303 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
307 return CCryptoKeyStore::AddCScript(redeemScript);
310 bool CWallet::AddWatchOnly(const CScript &dest)
312 if (!CCryptoKeyStore::AddWatchOnly(dest))
314 nTimeFirstKey = 1; // No birthday information for watch-only keys.
315 NotifyWatchonlyChanged(true);
318 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
321 bool CWallet::RemoveWatchOnly(const CScript &dest)
323 AssertLockHeld(cs_wallet);
324 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
326 if (!HaveWatchOnly())
327 NotifyWatchonlyChanged(false);
329 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
335 bool CWallet::LoadWatchOnly(const CScript &dest)
337 return CCryptoKeyStore::AddWatchOnly(dest);
340 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
343 CKeyingMaterial vMasterKey;
347 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
349 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
351 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
352 continue; // try another master key
353 if (CCryptoKeyStore::Unlock(vMasterKey))
360 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
362 bool fWasLocked = IsLocked();
369 CKeyingMaterial vMasterKey;
370 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
372 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
374 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
376 if (CCryptoKeyStore::Unlock(vMasterKey))
378 int64_t nStartTime = GetTimeMillis();
379 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
380 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
382 nStartTime = GetTimeMillis();
383 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
384 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
386 if (pMasterKey.second.nDeriveIterations < 25000)
387 pMasterKey.second.nDeriveIterations = 25000;
389 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
391 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
393 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
395 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
406 void CWallet::ChainTip(const CBlockIndex *pindex, const CBlock *pblock,
407 ZCIncrementalMerkleTree tree, bool added)
410 IncrementNoteWitnesses(pindex, pblock, tree);
412 DecrementNoteWitnesses(pindex);
416 void CWallet::SetBestChain(const CBlockLocator& loc)
418 CWalletDB walletdb(strWalletFile);
419 SetBestChainINTERNAL(walletdb, loc);
422 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
424 LOCK(cs_wallet); // nWalletVersion
425 if (nWalletVersion >= nVersion)
428 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
429 if (fExplicit && nVersion > nWalletMaxVersion)
430 nVersion = FEATURE_LATEST;
432 nWalletVersion = nVersion;
434 if (nVersion > nWalletMaxVersion)
435 nWalletMaxVersion = nVersion;
439 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
440 if (nWalletVersion > 40000)
441 pwalletdb->WriteMinVersion(nWalletVersion);
449 bool CWallet::SetMaxVersion(int nVersion)
451 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
452 // cannot downgrade below current version
453 if (nWalletVersion > nVersion)
456 nWalletMaxVersion = nVersion;
461 set<uint256> CWallet::GetConflicts(const uint256& txid) const
464 AssertLockHeld(cs_wallet);
466 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
467 if (it == mapWallet.end())
469 const CWalletTx& wtx = it->second;
471 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
473 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
475 if (mapTxSpends.count(txin.prevout) <= 1)
476 continue; // No conflict if zero or one spends
477 range = mapTxSpends.equal_range(txin.prevout);
478 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
479 result.insert(it->second);
482 std::pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range_n;
484 for (const JSDescription& jsdesc : wtx.vjoinsplit) {
485 for (const uint256& nullifier : jsdesc.nullifiers) {
486 if (mapTxNullifiers.count(nullifier) <= 1) {
487 continue; // No conflict if zero or one spends
489 range_n = mapTxNullifiers.equal_range(nullifier);
490 for (TxNullifiers::const_iterator it = range_n.first; it != range_n.second; ++it) {
491 result.insert(it->second);
498 void CWallet::Flush(bool shutdown)
500 bitdb.Flush(shutdown);
503 bool CWallet::Verify(const string& walletFile, string& warningString, string& errorString)
505 if (!bitdb.Open(GetDataDir()))
507 // try moving the database env out of the way
508 boost::filesystem::path pathDatabase = GetDataDir() / "database";
509 boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
511 boost::filesystem::rename(pathDatabase, pathDatabaseBak);
512 LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
513 } catch (const boost::filesystem::filesystem_error&) {
514 // failure is ok (well, not really, but it's not worse than what we started with)
518 if (!bitdb.Open(GetDataDir())) {
519 // if it still fails, it probably means we can't even create the database env
520 string msg = strprintf(_("Error initializing wallet database environment %s!"), GetDataDir());
526 if (GetBoolArg("-salvagewallet", false))
528 // Recover readable keypairs:
529 if (!CWalletDB::Recover(bitdb, walletFile, true))
533 if (boost::filesystem::exists(GetDataDir() / walletFile))
535 CDBEnv::VerifyResult r = bitdb.Verify(walletFile, CWalletDB::Recover);
536 if (r == CDBEnv::RECOVER_OK)
538 warningString += strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
539 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
540 " your balance or transactions are incorrect you should"
541 " restore from a backup."), GetDataDir());
543 if (r == CDBEnv::RECOVER_FAIL)
544 errorString += _("wallet.dat corrupt, salvage failed");
551 void CWallet::SyncMetaData(pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator> range)
553 // We want all the wallet transactions in range to have the same metadata as
554 // the oldest (smallest nOrderPos).
555 // So: find smallest nOrderPos:
557 int nMinOrderPos = std::numeric_limits<int>::max();
558 const CWalletTx* copyFrom = NULL;
559 for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
561 const uint256& hash = it->second;
562 int n = mapWallet[hash].nOrderPos;
563 if (n < nMinOrderPos)
566 copyFrom = &mapWallet[hash];
569 // Now copy data from copyFrom to rest:
570 for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
572 const uint256& hash = it->second;
573 CWalletTx* copyTo = &mapWallet[hash];
574 if (copyFrom == copyTo) continue;
575 copyTo->mapValue = copyFrom->mapValue;
576 // mapNoteData not copied on purpose
577 // (it is always set correctly for each CWalletTx)
578 copyTo->vOrderForm = copyFrom->vOrderForm;
579 // fTimeReceivedIsTxTime not copied on purpose
580 // nTimeReceived not copied on purpose
581 copyTo->nTimeSmart = copyFrom->nTimeSmart;
582 copyTo->fFromMe = copyFrom->fFromMe;
583 copyTo->strFromAccount = copyFrom->strFromAccount;
584 // nOrderPos not copied on purpose
585 // cached members not copied on purpose
590 * Outpoint is spent if any non-conflicted transaction
593 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
595 const COutPoint outpoint(hash, n);
596 pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
597 range = mapTxSpends.equal_range(outpoint);
599 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
601 const uint256& wtxid = it->second;
602 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
603 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
604 return true; // Spent
610 * Note is spent if any non-conflicted transaction
613 bool CWallet::IsSpent(const uint256& nullifier) const
615 pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range;
616 range = mapTxNullifiers.equal_range(nullifier);
618 for (TxNullifiers::const_iterator it = range.first; it != range.second; ++it) {
619 const uint256& wtxid = it->second;
620 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
621 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) {
622 return true; // Spent
628 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
630 mapTxSpends.insert(make_pair(outpoint, wtxid));
632 pair<TxSpends::iterator, TxSpends::iterator> range;
633 range = mapTxSpends.equal_range(outpoint);
634 SyncMetaData<COutPoint>(range);
637 void CWallet::AddToSpends(const uint256& nullifier, const uint256& wtxid)
639 mapTxNullifiers.insert(make_pair(nullifier, wtxid));
641 pair<TxNullifiers::iterator, TxNullifiers::iterator> range;
642 range = mapTxNullifiers.equal_range(nullifier);
643 SyncMetaData<uint256>(range);
646 void CWallet::AddToSpends(const uint256& wtxid)
648 assert(mapWallet.count(wtxid));
649 CWalletTx& thisTx = mapWallet[wtxid];
650 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
653 for (const CTxIn& txin : thisTx.vin) {
654 AddToSpends(txin.prevout, wtxid);
656 for (const JSDescription& jsdesc : thisTx.vjoinsplit) {
657 for (const uint256& nullifier : jsdesc.nullifiers) {
658 AddToSpends(nullifier, wtxid);
663 void CWallet::ClearNoteWitnessCache()
666 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
667 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
668 item.second.witnesses.clear();
669 item.second.witnessHeight = -1;
672 nWitnessCacheSize = 0;
675 void CWallet::IncrementNoteWitnesses(const CBlockIndex* pindex,
676 const CBlock* pblockIn,
677 ZCIncrementalMerkleTree& tree)
681 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
682 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
683 CNoteData* nd = &(item.second);
684 // Only increment witnesses that are behind the current height
685 if (nd->witnessHeight < pindex->nHeight) {
686 // Check the validity of the cache
687 // The only time a note witnessed above the current height
688 // would be invalid here is during a reindex when blocks
689 // have been decremented, and we are incrementing the blocks
690 // immediately after.
691 assert(nWitnessCacheSize >= nd->witnesses.size());
692 // Witnesses being incremented should always be either -1
693 // (never incremented or decremented) or one below pindex
694 assert((nd->witnessHeight == -1) ||
695 (nd->witnessHeight == pindex->nHeight - 1));
696 // Copy the witness for the previous block if we have one
697 if (nd->witnesses.size() > 0) {
698 nd->witnesses.push_front(nd->witnesses.front());
700 if (nd->witnesses.size() > WITNESS_CACHE_SIZE) {
701 nd->witnesses.pop_back();
706 if (nWitnessCacheSize < WITNESS_CACHE_SIZE) {
707 nWitnessCacheSize += 1;
710 const CBlock* pblock {pblockIn};
713 ReadBlockFromDisk(block, pindex);
717 for (const CTransaction& tx : pblock->vtx) {
718 auto hash = tx.GetHash();
719 bool txIsOurs = mapWallet.count(hash);
720 for (size_t i = 0; i < tx.vjoinsplit.size(); i++) {
721 const JSDescription& jsdesc = tx.vjoinsplit[i];
722 for (uint8_t j = 0; j < jsdesc.commitments.size(); j++) {
723 const uint256& note_commitment = jsdesc.commitments[j];
724 tree.append(note_commitment);
726 // Increment existing witnesses
727 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
728 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
729 CNoteData* nd = &(item.second);
730 if (nd->witnessHeight < pindex->nHeight &&
731 nd->witnesses.size() > 0) {
732 // Check the validity of the cache
733 // See earlier comment about validity.
734 assert(nWitnessCacheSize >= nd->witnesses.size());
735 nd->witnesses.front().append(note_commitment);
740 // If this is our note, witness it
742 JSOutPoint jsoutpt {hash, i, j};
743 if (mapWallet[hash].mapNoteData.count(jsoutpt) &&
744 mapWallet[hash].mapNoteData[jsoutpt].witnessHeight < pindex->nHeight) {
745 CNoteData* nd = &(mapWallet[hash].mapNoteData[jsoutpt]);
746 if (nd->witnesses.size() > 0) {
747 // We think this can happen because we write out the
748 // witness cache state after every block increment or
749 // decrement, but the block index itself is written in
750 // batches. So if the node crashes in between these two
751 // operations, it is possible for IncrementNoteWitnesses
752 // to be called again on previously-cached blocks. This
753 // doesn't affect existing cached notes because of the
754 // CNoteData::witnessHeight checks. See #1378 for details.
755 LogPrintf("Inconsistent witness cache state found for %s\n- Cache size: %d\n- Top (height %d): %s\n- New (height %d): %s\n",
756 jsoutpt.ToString(), nd->witnesses.size(),
758 nd->witnesses.front().root().GetHex(),
760 tree.witness().root().GetHex());
761 nd->witnesses.clear();
763 nd->witnesses.push_front(tree.witness());
764 // Set height to one less than pindex so it gets incremented
765 nd->witnessHeight = pindex->nHeight - 1;
766 // Check the validity of the cache
767 assert(nWitnessCacheSize >= nd->witnesses.size());
774 // Update witness heights
775 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
776 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
777 CNoteData* nd = &(item.second);
778 if (nd->witnessHeight < pindex->nHeight) {
779 nd->witnessHeight = pindex->nHeight;
780 // Check the validity of the cache
781 // See earlier comment about validity.
782 assert(nWitnessCacheSize >= nd->witnesses.size());
787 // For performance reasons, we write out the witness cache in
788 // CWallet::SetBestChain() (which also ensures that overall consistency
789 // of the wallet.dat is maintained).
793 void CWallet::DecrementNoteWitnesses(const CBlockIndex* pindex)
797 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
798 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
799 CNoteData* nd = &(item.second);
800 // Only increment witnesses that are not above the current height
801 if (nd->witnessHeight <= pindex->nHeight) {
802 // Check the validity of the cache
803 // See comment below (this would be invalid if there was a
805 assert(nWitnessCacheSize >= nd->witnesses.size());
806 // Witnesses being decremented should always be either -1
807 // (never incremented or decremented) or equal to pindex
808 assert((nd->witnessHeight == -1) ||
809 (nd->witnessHeight == pindex->nHeight));
810 if (nd->witnesses.size() > 0) {
811 nd->witnesses.pop_front();
813 // pindex is the block being removed, so the new witness cache
814 // height is one below it.
815 nd->witnessHeight = pindex->nHeight - 1;
819 nWitnessCacheSize -= 1;
820 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
821 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
822 CNoteData* nd = &(item.second);
823 // Check the validity of the cache
824 // Technically if there are notes witnessed above the current
825 // height, their cache will now be invalid (relative to the new
826 // value of nWitnessCacheSize). However, this would only occur
827 // during a reindex, and by the time the reindex reaches the tip
828 // of the chain again, the existing witness caches will be valid
830 // We don't set nWitnessCacheSize to zero at the start of the
831 // reindex because the on-disk blocks had already resulted in a
832 // chain that didn't trigger the assertion below.
833 if (nd->witnessHeight < pindex->nHeight) {
834 assert(nWitnessCacheSize >= nd->witnesses.size());
838 // TODO: If nWitnessCache is zero, we need to regenerate the caches (#1302)
839 assert(nWitnessCacheSize > 0);
841 // For performance reasons, we write out the witness cache in
842 // CWallet::SetBestChain() (which also ensures that overall consistency
843 // of the wallet.dat is maintained).
847 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
852 CKeyingMaterial vMasterKey;
854 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
855 GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
857 CMasterKey kMasterKey;
859 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
860 GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
863 int64_t nStartTime = GetTimeMillis();
864 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
865 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
867 nStartTime = GetTimeMillis();
868 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
869 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
871 if (kMasterKey.nDeriveIterations < 25000)
872 kMasterKey.nDeriveIterations = 25000;
874 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
876 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
878 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
883 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
886 assert(!pwalletdbEncryption);
887 pwalletdbEncryption = new CWalletDB(strWalletFile);
888 if (!pwalletdbEncryption->TxnBegin()) {
889 delete pwalletdbEncryption;
890 pwalletdbEncryption = NULL;
893 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
896 if (!EncryptKeys(vMasterKey))
899 pwalletdbEncryption->TxnAbort();
900 delete pwalletdbEncryption;
902 // We now probably have half of our keys encrypted in memory, and half not...
903 // die and let the user reload the unencrypted wallet.
907 // Encryption was introduced in version 0.4.0
908 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
912 if (!pwalletdbEncryption->TxnCommit()) {
913 delete pwalletdbEncryption;
914 // We now have keys encrypted in memory, but not on disk...
915 // die to avoid confusion and let the user reload the unencrypted wallet.
919 delete pwalletdbEncryption;
920 pwalletdbEncryption = NULL;
924 Unlock(strWalletPassphrase);
928 // Need to completely rewrite the wallet file; if we don't, bdb might keep
929 // bits of the unencrypted private key in slack space in the database file.
930 CDB::Rewrite(strWalletFile);
933 NotifyStatusChanged(this);
938 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
940 AssertLockHeld(cs_wallet); // nOrderPosNext
941 int64_t nRet = nOrderPosNext++;
943 pwalletdb->WriteOrderPosNext(nOrderPosNext);
945 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
950 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
952 AssertLockHeld(cs_wallet); // mapWallet
953 CWalletDB walletdb(strWalletFile);
955 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
958 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
959 // would make this much faster for applications that do this a lot.
960 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
962 CWalletTx* wtx = &((*it).second);
963 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
966 walletdb.ListAccountCreditDebit(strAccount, acentries);
967 BOOST_FOREACH(CAccountingEntry& entry, acentries)
969 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
975 void CWallet::MarkDirty()
979 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
980 item.second.MarkDirty();
985 * Ensure that every note in the wallet (for which we possess a spending key)
986 * has a cached nullifier.
988 bool CWallet::UpdateNullifierNoteMap()
996 ZCNoteDecryption dec;
997 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
998 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
999 if (!item.second.nullifier) {
1000 if (GetNoteDecryptor(item.second.address, dec)) {
1001 auto i = item.first.js;
1002 auto hSig = wtxItem.second.vjoinsplit[i].h_sig(
1003 *pzcashParams, wtxItem.second.joinSplitPubKey);
1004 item.second.nullifier = GetNoteNullifier(
1005 wtxItem.second.vjoinsplit[i],
1006 item.second.address,
1013 UpdateNullifierNoteMapWithTx(wtxItem.second);
1020 * Update mapNullifiersToNotes with the cached nullifiers in this tx.
1022 void CWallet::UpdateNullifierNoteMapWithTx(const CWalletTx& wtx)
1026 for (const mapNoteData_t::value_type& item : wtx.mapNoteData) {
1027 if (item.second.nullifier) {
1028 mapNullifiersToNotes[*item.second.nullifier] = item.first;
1034 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb)
1036 uint256 hash = wtxIn.GetHash();
1038 if (fFromLoadWallet)
1040 mapWallet[hash] = wtxIn;
1041 mapWallet[hash].BindWallet(this);
1042 UpdateNullifierNoteMapWithTx(mapWallet[hash]);
1048 // Inserts only if not already there, returns tx inserted or tx found
1049 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
1050 CWalletTx& wtx = (*ret.first).second;
1051 wtx.BindWallet(this);
1052 UpdateNullifierNoteMapWithTx(wtx);
1053 bool fInsertedNew = ret.second;
1056 wtx.nTimeReceived = GetAdjustedTime();
1057 wtx.nOrderPos = IncOrderPosNext(pwalletdb);
1059 wtx.nTimeSmart = wtx.nTimeReceived;
1060 if (!wtxIn.hashBlock.IsNull())
1062 if (mapBlockIndex.count(wtxIn.hashBlock))
1064 int64_t latestNow = wtx.nTimeReceived;
1065 int64_t latestEntry = 0;
1067 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
1068 int64_t latestTolerated = latestNow + 300;
1069 std::list<CAccountingEntry> acentries;
1070 TxItems txOrdered = OrderedTxItems(acentries);
1071 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
1073 CWalletTx *const pwtx = (*it).second.first;
1076 CAccountingEntry *const pacentry = (*it).second.second;
1080 nSmartTime = pwtx->nTimeSmart;
1082 nSmartTime = pwtx->nTimeReceived;
1085 nSmartTime = pacentry->nTime;
1086 if (nSmartTime <= latestTolerated)
1088 latestEntry = nSmartTime;
1089 if (nSmartTime > latestNow)
1090 latestNow = nSmartTime;
1096 int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
1097 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
1100 LogPrintf("AddToWallet(): found %s in block %s not in index\n",
1101 wtxIn.GetHash().ToString(),
1102 wtxIn.hashBlock.ToString());
1107 bool fUpdated = false;
1111 if (!wtxIn.hashBlock.IsNull() && wtxIn.hashBlock != wtx.hashBlock)
1113 wtx.hashBlock = wtxIn.hashBlock;
1116 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
1118 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
1119 wtx.nIndex = wtxIn.nIndex;
1122 if (UpdatedNoteData(wtxIn, wtx)) {
1125 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
1127 wtx.fFromMe = wtxIn.fFromMe;
1133 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
1136 if (fInsertedNew || fUpdated)
1137 if (!wtx.WriteToDisk(pwalletdb))
1140 // Break debit/credit balance caches:
1143 // Notify UI of new or updated transaction
1144 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
1146 // notify an external script when a wallet transaction comes in or is updated
1147 std::string strCmd = GetArg("-walletnotify", "");
1149 if ( !strCmd.empty())
1151 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
1152 boost::thread t(runCommand, strCmd); // thread runs free
1159 bool CWallet::UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx)
1161 if (wtxIn.mapNoteData.empty() || wtxIn.mapNoteData == wtx.mapNoteData) {
1164 auto tmp = wtxIn.mapNoteData;
1165 // Ensure we keep any cached witnesses we may already have
1166 for (const std::pair<JSOutPoint, CNoteData> nd : wtx.mapNoteData) {
1167 if (tmp.count(nd.first) && nd.second.witnesses.size() > 0) {
1168 tmp.at(nd.first).witnesses.assign(
1169 nd.second.witnesses.cbegin(), nd.second.witnesses.cend());
1171 tmp.at(nd.first).witnessHeight = nd.second.witnessHeight;
1173 // Now copy over the updated note data
1174 wtx.mapNoteData = tmp;
1179 * Add a transaction to the wallet, or update it.
1180 * pblock is optional, but should be provided if the transaction is known to be in a block.
1181 * If fUpdate is true, existing transactions will be updated.
1183 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
1186 AssertLockHeld(cs_wallet);
1187 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1188 if (fExisted && !fUpdate) return false;
1189 auto noteData = FindMyNotes(tx);
1190 if (fExisted || IsMine(tx) || IsFromMe(tx) || noteData.size() > 0)
1192 CWalletTx wtx(this,tx);
1194 if (noteData.size() > 0) {
1195 wtx.SetNoteData(noteData);
1198 // Get merkle branch if transaction was found in a block
1200 wtx.SetMerkleBranch(*pblock);
1202 // Do not flush the wallet here for performance reasons
1203 // this is safe, as in case of a crash, we rescan the necessary blocks on startup through our SetBestChain-mechanism
1204 CWalletDB walletdb(strWalletFile, "r+", false);
1206 return AddToWallet(wtx, false, &walletdb);
1212 void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
1214 LOCK2(cs_main, cs_wallet);
1215 if (!AddToWalletIfInvolvingMe(tx, pblock, true))
1216 return; // Not one of ours
1218 MarkAffectedTransactionsDirty(tx);
1221 void CWallet::MarkAffectedTransactionsDirty(const CTransaction& tx)
1223 // If a transaction changes 'conflicted' state, that changes the balance
1224 // available of the outputs it spends. So force those to be
1225 // recomputed, also:
1226 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1228 if (mapWallet.count(txin.prevout.hash))
1229 mapWallet[txin.prevout.hash].MarkDirty();
1231 for (const JSDescription& jsdesc : tx.vjoinsplit) {
1232 for (const uint256& nullifier : jsdesc.nullifiers) {
1233 if (mapNullifiersToNotes.count(nullifier) &&
1234 mapWallet.count(mapNullifiersToNotes[nullifier].hash)) {
1235 mapWallet[mapNullifiersToNotes[nullifier].hash].MarkDirty();
1241 void CWallet::EraseFromWallet(const uint256 &hash)
1247 if (mapWallet.erase(hash))
1248 CWalletDB(strWalletFile).EraseTx(hash);
1255 * Returns a nullifier if the SpendingKey is available
1256 * Throws std::runtime_error if the decryptor doesn't match this note
1258 boost::optional<uint256> CWallet::GetNoteNullifier(const JSDescription& jsdesc,
1259 const libzcash::PaymentAddress& address,
1260 const ZCNoteDecryption& dec,
1261 const uint256& hSig,
1264 boost::optional<uint256> ret;
1265 auto note_pt = libzcash::NotePlaintext::decrypt(
1267 jsdesc.ciphertexts[n],
1268 jsdesc.ephemeralKey,
1271 auto note = note_pt.note(address);
1272 // SpendingKeys are only available if:
1273 // - We have them (this isn't a viewing key)
1274 // - The wallet is unlocked
1275 libzcash::SpendingKey key;
1276 if (GetSpendingKey(address, key)) {
1277 ret = note.nullifier(key);
1283 * Finds all output notes in the given transaction that have been sent to
1284 * PaymentAddresses in this wallet.
1286 * It should never be necessary to call this method with a CWalletTx, because
1287 * the result of FindMyNotes (for the addresses available at the time) will
1288 * already have been cached in CWalletTx.mapNoteData.
1290 mapNoteData_t CWallet::FindMyNotes(const CTransaction& tx) const
1292 LOCK(cs_SpendingKeyStore);
1293 uint256 hash = tx.GetHash();
1295 mapNoteData_t noteData;
1296 for (size_t i = 0; i < tx.vjoinsplit.size(); i++) {
1297 auto hSig = tx.vjoinsplit[i].h_sig(*pzcashParams, tx.joinSplitPubKey);
1298 for (uint8_t j = 0; j < tx.vjoinsplit[i].ciphertexts.size(); j++) {
1299 for (const NoteDecryptorMap::value_type& item : mapNoteDecryptors) {
1301 auto address = item.first;
1302 JSOutPoint jsoutpt {hash, i, j};
1303 auto nullifier = GetNoteNullifier(
1309 CNoteData nd {address, *nullifier};
1310 noteData.insert(std::make_pair(jsoutpt, nd));
1312 CNoteData nd {address};
1313 noteData.insert(std::make_pair(jsoutpt, nd));
1316 } catch (const note_decryption_failed &err) {
1317 // Couldn't decrypt with this decryptor
1318 } catch (const std::exception &exc) {
1319 // Unexpected failure
1320 LogPrintf("FindMyNotes(): Unexpected error while testing decrypt:\n");
1321 LogPrintf("%s\n", exc.what());
1329 bool CWallet::IsFromMe(const uint256& nullifier) const
1333 if (mapNullifiersToNotes.count(nullifier) &&
1334 mapWallet.count(mapNullifiersToNotes.at(nullifier).hash)) {
1341 void CWallet::GetNoteWitnesses(std::vector<JSOutPoint> notes,
1342 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
1343 uint256 &final_anchor)
1347 witnesses.resize(notes.size());
1348 boost::optional<uint256> rt;
1350 for (JSOutPoint note : notes) {
1351 if (mapWallet.count(note.hash) &&
1352 mapWallet[note.hash].mapNoteData.count(note) &&
1353 mapWallet[note.hash].mapNoteData[note].witnesses.size() > 0) {
1354 witnesses[i] = mapWallet[note.hash].mapNoteData[note].witnesses.front();
1356 rt = witnesses[i]->root();
1358 assert(*rt == witnesses[i]->root());
1363 // All returned witnesses have the same anchor
1370 isminetype CWallet::IsMine(const CTxIn &txin) const
1374 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1375 if (mi != mapWallet.end())
1377 const CWalletTx& prev = (*mi).second;
1378 if (txin.prevout.n < prev.vout.size())
1379 return IsMine(prev.vout[txin.prevout.n]);
1385 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1389 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1390 if (mi != mapWallet.end())
1392 const CWalletTx& prev = (*mi).second;
1393 if (txin.prevout.n < prev.vout.size())
1394 if (IsMine(prev.vout[txin.prevout.n]) & filter)
1395 return prev.vout[txin.prevout.n].nValue;
1401 isminetype CWallet::IsMine(const CTxOut& txout) const
1403 return ::IsMine(*this, txout.scriptPubKey);
1406 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1408 if (!MoneyRange(txout.nValue))
1409 throw std::runtime_error("CWallet::GetCredit(): value out of range");
1410 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1413 bool CWallet::IsChange(const CTxOut& txout) const
1415 // TODO: fix handling of 'change' outputs. The assumption is that any
1416 // payment to a script that is ours, but is not in the address book
1417 // is change. That assumption is likely to break when we implement multisignature
1418 // wallets that return change back into a multi-signature-protected address;
1419 // a better way of identifying which outputs are 'the send' and which are
1420 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1421 // which output, if any, was change).
1422 if (::IsMine(*this, txout.scriptPubKey))
1424 CTxDestination address;
1425 if (!ExtractDestination(txout.scriptPubKey, address))
1429 if (!mapAddressBook.count(address))
1435 CAmount CWallet::GetChange(const CTxOut& txout) const
1437 if (!MoneyRange(txout.nValue))
1438 throw std::runtime_error("CWallet::GetChange(): value out of range");
1439 return (IsChange(txout) ? txout.nValue : 0);
1442 bool CWallet::IsMine(const CTransaction& tx) const
1444 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1450 bool CWallet::IsFromMe(const CTransaction& tx) const
1452 if (GetDebit(tx, ISMINE_ALL) > 0) {
1455 for (const JSDescription& jsdesc : tx.vjoinsplit) {
1456 for (const uint256& nullifier : jsdesc.nullifiers) {
1457 if (IsFromMe(nullifier)) {
1465 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1468 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1470 nDebit += GetDebit(txin, filter);
1471 if (!MoneyRange(nDebit))
1472 throw std::runtime_error("CWallet::GetDebit(): value out of range");
1477 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1479 CAmount nCredit = 0;
1480 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1482 nCredit += GetCredit(txout, filter);
1483 if (!MoneyRange(nCredit))
1484 throw std::runtime_error("CWallet::GetCredit(): value out of range");
1489 CAmount CWallet::GetChange(const CTransaction& tx) const
1491 CAmount nChange = 0;
1492 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1494 nChange += GetChange(txout);
1495 if (!MoneyRange(nChange))
1496 throw std::runtime_error("CWallet::GetChange(): value out of range");
1501 void CWalletTx::SetNoteData(mapNoteData_t ¬eData)
1503 mapNoteData.clear();
1504 for (const std::pair<JSOutPoint, CNoteData> nd : noteData) {
1505 if (nd.first.js < vjoinsplit.size() &&
1506 nd.first.n < vjoinsplit[nd.first.js].ciphertexts.size()) {
1507 // Store the address and nullifier for the Note
1508 mapNoteData[nd.first] = nd.second;
1510 // If FindMyNotes() was used to obtain noteData,
1511 // this should never happen
1512 throw std::logic_error("CWalletTx::SetNoteData(): Invalid note");
1517 int64_t CWalletTx::GetTxTime() const
1519 int64_t n = nTimeSmart;
1520 return n ? n : nTimeReceived;
1523 int CWalletTx::GetRequestCount() const
1525 // Returns -1 if it wasn't being tracked
1528 LOCK(pwallet->cs_wallet);
1532 if (!hashBlock.IsNull())
1534 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1535 if (mi != pwallet->mapRequestCount.end())
1536 nRequests = (*mi).second;
1541 // Did anyone request this transaction?
1542 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1543 if (mi != pwallet->mapRequestCount.end())
1545 nRequests = (*mi).second;
1547 // How about the block it's in?
1548 if (nRequests == 0 && !hashBlock.IsNull())
1550 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1551 if (mi != pwallet->mapRequestCount.end())
1552 nRequests = (*mi).second;
1554 nRequests = 1; // If it's in someone else's block it must have got out
1562 // GetAmounts will determine the transparent debits and credits for a given wallet tx.
1563 void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
1564 list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
1567 listReceived.clear();
1569 strSentAccount = strFromAccount;
1571 // Is this tx sent/signed by me?
1572 CAmount nDebit = GetDebit(filter);
1573 bool isFromMyTaddr = nDebit > 0; // debit>0 means we signed/sent this transaction
1575 // Does this tx spend my notes?
1576 bool isFromMyZaddr = false;
1577 for (const JSDescription& js : vjoinsplit) {
1578 for (const uint256& nullifier : js.nullifiers) {
1579 if (pwallet->IsFromMe(nullifier)) {
1580 isFromMyZaddr = true;
1584 if (isFromMyZaddr) {
1589 // Compute fee if we sent this transaction.
1590 if (isFromMyTaddr) {
1591 CAmount nValueOut = GetValueOut(); // transparent outputs plus all vpub_old
1592 CAmount nValueIn = 0;
1593 for (const JSDescription & js : vjoinsplit) {
1594 nValueIn += js.vpub_new;
1596 nFee = nDebit - nValueOut + nValueIn;
1599 // Create output entry for vpub_old/new, if we sent utxos from this transaction
1600 if (isFromMyTaddr) {
1601 CAmount myVpubOld = 0;
1602 CAmount myVpubNew = 0;
1603 for (const JSDescription& js : vjoinsplit) {
1604 bool fMyJSDesc = false;
1607 for (const uint256& nullifier : js.nullifiers) {
1608 if (pwallet->IsFromMe(nullifier)) {
1614 // Check output side
1616 for (const std::pair<JSOutPoint, CNoteData> nd : this->mapNoteData) {
1617 if (nd.first.js < vjoinsplit.size() && nd.first.n < vjoinsplit[nd.first.js].ciphertexts.size()) {
1625 myVpubOld += js.vpub_old;
1626 myVpubNew += js.vpub_new;
1629 if (!MoneyRange(js.vpub_old) || !MoneyRange(js.vpub_new) || !MoneyRange(myVpubOld) || !MoneyRange(myVpubNew)) {
1630 throw std::runtime_error("CWalletTx::GetAmounts: value out of range");
1634 // Create an output for the value taken from or added to the transparent value pool by JoinSplits
1635 if (myVpubOld > myVpubNew) {
1636 COutputEntry output = {CNoDestination(), myVpubOld - myVpubNew, (int)vout.size()};
1637 listSent.push_back(output);
1638 } else if (myVpubNew > myVpubOld) {
1639 COutputEntry output = {CNoDestination(), myVpubNew - myVpubOld, (int)vout.size()};
1640 listReceived.push_back(output);
1645 for (unsigned int i = 0; i < vout.size(); ++i)
1647 const CTxOut& txout = vout[i];
1648 isminetype fIsMine = pwallet->IsMine(txout);
1649 // Only need to handle txouts if AT LEAST one of these is true:
1650 // 1) they debit from us (sent)
1651 // 2) the output is to us (received)
1654 // Don't report 'change' txouts
1655 if (pwallet->IsChange(txout))
1658 else if (!(fIsMine & filter))
1661 // In either case, we need to get the destination address
1662 CTxDestination address;
1663 if (!ExtractDestination(txout.scriptPubKey, address))
1665 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1666 this->GetHash().ToString());
1667 address = CNoDestination();
1670 COutputEntry output = {address, txout.nValue, (int)i};
1672 // If we are debited by the transaction, add the output as a "sent" entry
1674 listSent.push_back(output);
1676 // If we are receiving the output, add it as a "received" entry
1677 if (fIsMine & filter)
1678 listReceived.push_back(output);
1683 void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
1684 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
1686 nReceived = nSent = nFee = 0;
1689 string strSentAccount;
1690 list<COutputEntry> listReceived;
1691 list<COutputEntry> listSent;
1692 GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
1694 if (strAccount == strSentAccount)
1696 BOOST_FOREACH(const COutputEntry& s, listSent)
1701 LOCK(pwallet->cs_wallet);
1702 BOOST_FOREACH(const COutputEntry& r, listReceived)
1704 if (pwallet->mapAddressBook.count(r.destination))
1706 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
1707 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
1708 nReceived += r.amount;
1710 else if (strAccount.empty())
1712 nReceived += r.amount;
1719 bool CWalletTx::WriteToDisk(CWalletDB *pwalletdb)
1721 return pwalletdb->WriteTx(GetHash(), *this);
1724 void CWallet::WitnessNoteCommitment(std::vector<uint256> commitments,
1725 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
1726 uint256 &final_anchor)
1728 witnesses.resize(commitments.size());
1729 CBlockIndex* pindex = chainActive.Genesis();
1730 ZCIncrementalMerkleTree tree;
1734 ReadBlockFromDisk(block, pindex);
1736 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1738 BOOST_FOREACH(const JSDescription& jsdesc, tx.vjoinsplit)
1740 BOOST_FOREACH(const uint256 ¬e_commitment, jsdesc.commitments)
1742 tree.append(note_commitment);
1744 BOOST_FOREACH(boost::optional<ZCIncrementalWitness>& wit, witnesses) {
1746 wit->append(note_commitment);
1751 BOOST_FOREACH(uint256& commitment, commitments) {
1752 if (note_commitment == commitment) {
1753 witnesses.at(i) = tree.witness();
1761 uint256 current_anchor = tree.root();
1763 // Consistency check: we should be able to find the current tree
1764 // in our CCoins view.
1765 ZCIncrementalMerkleTree dummy_tree;
1766 assert(pcoinsTip->GetAnchorAt(current_anchor, dummy_tree));
1768 pindex = chainActive.Next(pindex);
1771 // TODO: #93; Select a root via some heuristic.
1772 final_anchor = tree.root();
1774 BOOST_FOREACH(boost::optional<ZCIncrementalWitness>& wit, witnesses) {
1776 assert(final_anchor == wit->root());
1782 * Scan the block chain (starting in pindexStart) for transactions
1783 * from or to us. If fUpdate is true, found transactions that already
1784 * exist in the wallet will be updated.
1786 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1789 int64_t nNow = GetTime();
1790 const CChainParams& chainParams = Params();
1792 CBlockIndex* pindex = pindexStart;
1794 LOCK2(cs_main, cs_wallet);
1796 // no need to read and scan block, if block was created before
1797 // our wallet birthday (as adjusted for block time variability)
1798 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
1799 pindex = chainActive.Next(pindex);
1801 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1802 double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
1803 double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip(), false);
1806 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1807 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1810 ReadBlockFromDisk(block, pindex);
1811 BOOST_FOREACH(CTransaction& tx, block.vtx)
1813 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1817 ZCIncrementalMerkleTree tree;
1818 // This should never fail: we should always be able to get the tree
1819 // state on the path to the tip of our chain
1820 assert(pcoinsTip->GetAnchorAt(pindex->hashAnchor, tree));
1821 // Increment note witness caches
1822 IncrementNoteWitnesses(pindex, &block, tree);
1824 pindex = chainActive.Next(pindex);
1825 if (GetTime() >= nNow + 60) {
1827 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex));
1830 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1835 void CWallet::ReacceptWalletTransactions()
1837 // If transactions aren't being broadcasted, don't let them into local mempool either
1838 if (!fBroadcastTransactions)
1840 LOCK2(cs_main, cs_wallet);
1841 std::map<int64_t, CWalletTx*> mapSorted;
1843 // Sort pending wallet transactions based on their initial wallet insertion order
1844 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1846 const uint256& wtxid = item.first;
1847 CWalletTx& wtx = item.second;
1848 assert(wtx.GetHash() == wtxid);
1850 int nDepth = wtx.GetDepthInMainChain();
1852 if (!wtx.IsCoinBase() && nDepth < 0) {
1853 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1857 // Try to add wallet transactions to memory pool
1858 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1860 CWalletTx& wtx = *(item.second);
1863 wtx.AcceptToMemoryPool(false);
1867 bool CWalletTx::RelayWalletTransaction()
1869 assert(pwallet->GetBroadcastTransactions());
1872 if (GetDepthInMainChain() == 0) {
1873 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1874 RelayTransaction((CTransaction)*this);
1881 set<uint256> CWalletTx::GetConflicts() const
1883 set<uint256> result;
1884 if (pwallet != NULL)
1886 uint256 myHash = GetHash();
1887 result = pwallet->GetConflicts(myHash);
1888 result.erase(myHash);
1893 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1899 if(filter & ISMINE_SPENDABLE)
1902 debit += nDebitCached;
1905 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1906 fDebitCached = true;
1907 debit += nDebitCached;
1910 if(filter & ISMINE_WATCH_ONLY)
1912 if(fWatchDebitCached)
1913 debit += nWatchDebitCached;
1916 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1917 fWatchDebitCached = true;
1918 debit += nWatchDebitCached;
1924 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1926 // Must wait until coinbase is safely deep enough in the chain before valuing it
1927 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1931 if (filter & ISMINE_SPENDABLE)
1933 // GetBalance can assume transactions in mapWallet won't change
1935 credit += nCreditCached;
1938 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1939 fCreditCached = true;
1940 credit += nCreditCached;
1943 if (filter & ISMINE_WATCH_ONLY)
1945 if (fWatchCreditCached)
1946 credit += nWatchCreditCached;
1949 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1950 fWatchCreditCached = true;
1951 credit += nWatchCreditCached;
1957 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1959 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1961 if (fUseCache && fImmatureCreditCached)
1962 return nImmatureCreditCached;
1963 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1964 fImmatureCreditCached = true;
1965 return nImmatureCreditCached;
1971 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1976 // Must wait until coinbase is safely deep enough in the chain before valuing it
1977 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1980 if (fUseCache && fAvailableCreditCached)
1981 return nAvailableCreditCached;
1983 CAmount nCredit = 0;
1984 uint256 hashTx = GetHash();
1985 for (unsigned int i = 0; i < vout.size(); i++)
1987 if (!pwallet->IsSpent(hashTx, i))
1989 const CTxOut &txout = vout[i];
1990 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1991 if (!MoneyRange(nCredit))
1992 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1996 nAvailableCreditCached = nCredit;
1997 fAvailableCreditCached = true;
2001 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
2003 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
2005 if (fUseCache && fImmatureWatchCreditCached)
2006 return nImmatureWatchCreditCached;
2007 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
2008 fImmatureWatchCreditCached = true;
2009 return nImmatureWatchCreditCached;
2015 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
2020 // Must wait until coinbase is safely deep enough in the chain before valuing it
2021 if (IsCoinBase() && GetBlocksToMaturity() > 0)
2024 if (fUseCache && fAvailableWatchCreditCached)
2025 return nAvailableWatchCreditCached;
2027 CAmount nCredit = 0;
2028 for (unsigned int i = 0; i < vout.size(); i++)
2030 if (!pwallet->IsSpent(GetHash(), i))
2032 const CTxOut &txout = vout[i];
2033 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
2034 if (!MoneyRange(nCredit))
2035 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
2039 nAvailableWatchCreditCached = nCredit;
2040 fAvailableWatchCreditCached = true;
2044 CAmount CWalletTx::GetChange() const
2047 return nChangeCached;
2048 nChangeCached = pwallet->GetChange(*this);
2049 fChangeCached = true;
2050 return nChangeCached;
2053 bool CWalletTx::IsTrusted() const
2055 // Quick answer in most cases
2056 if (!CheckFinalTx(*this))
2058 int nDepth = GetDepthInMainChain();
2063 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
2066 // Trusted if all inputs are from us and are in the mempool:
2067 BOOST_FOREACH(const CTxIn& txin, vin)
2069 // Transactions not sent by us: not trusted
2070 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
2073 const CTxOut& parentOut = parent->vout[txin.prevout.n];
2074 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
2080 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
2082 std::vector<uint256> result;
2085 // Sort them in chronological order
2086 multimap<unsigned int, CWalletTx*> mapSorted;
2087 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
2089 CWalletTx& wtx = item.second;
2090 // Don't rebroadcast if newer than nTime:
2091 if (wtx.nTimeReceived > nTime)
2093 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
2095 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
2097 CWalletTx& wtx = *item.second;
2098 if (wtx.RelayWalletTransaction())
2099 result.push_back(wtx.GetHash());
2104 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
2106 // Do this infrequently and randomly to avoid giving away
2107 // that these are our transactions.
2108 if (GetTime() < nNextResend || !fBroadcastTransactions)
2110 bool fFirst = (nNextResend == 0);
2111 nNextResend = GetTime() + GetRand(30 * 60);
2115 // Only do it if there's been a new block since last time
2116 if (nBestBlockTime < nLastResend)
2118 nLastResend = GetTime();
2120 // Rebroadcast unconfirmed txes older than 5 minutes before the last
2122 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60);
2123 if (!relayed.empty())
2124 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
2127 /** @} */ // end of mapWallet
2132 /** @defgroup Actions
2138 CAmount CWallet::GetBalance() const
2142 LOCK2(cs_main, cs_wallet);
2143 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2145 const CWalletTx* pcoin = &(*it).second;
2146 if (pcoin->IsTrusted())
2147 nTotal += pcoin->GetAvailableCredit();
2154 CAmount CWallet::GetUnconfirmedBalance() const
2158 LOCK2(cs_main, cs_wallet);
2159 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2161 const CWalletTx* pcoin = &(*it).second;
2162 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
2163 nTotal += pcoin->GetAvailableCredit();
2169 CAmount CWallet::GetImmatureBalance() const
2173 LOCK2(cs_main, cs_wallet);
2174 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2176 const CWalletTx* pcoin = &(*it).second;
2177 nTotal += pcoin->GetImmatureCredit();
2183 CAmount CWallet::GetWatchOnlyBalance() const
2187 LOCK2(cs_main, cs_wallet);
2188 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2190 const CWalletTx* pcoin = &(*it).second;
2191 if (pcoin->IsTrusted())
2192 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2199 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2203 LOCK2(cs_main, cs_wallet);
2204 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2206 const CWalletTx* pcoin = &(*it).second;
2207 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
2208 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2214 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2218 LOCK2(cs_main, cs_wallet);
2219 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2221 const CWalletTx* pcoin = &(*it).second;
2222 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2229 * populate vCoins with vector of available COutputs.
2231 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue, bool fIncludeCoinBase) const
2236 LOCK2(cs_main, cs_wallet);
2237 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2239 const uint256& wtxid = it->first;
2240 const CWalletTx* pcoin = &(*it).second;
2242 if (!CheckFinalTx(*pcoin))
2245 if (fOnlyConfirmed && !pcoin->IsTrusted())
2248 if (pcoin->IsCoinBase() && !fIncludeCoinBase)
2251 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2254 int nDepth = pcoin->GetDepthInMainChain();
2258 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
2259 isminetype mine = IsMine(pcoin->vout[i]);
2260 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
2261 !IsLockedCoin((*it).first, i) && (pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
2262 (!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected((*it).first, i)))
2263 vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO));
2269 static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2270 vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2272 vector<char> vfIncluded;
2274 vfBest.assign(vValue.size(), true);
2275 nBest = nTotalLower;
2277 seed_insecure_rand();
2279 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2281 vfIncluded.assign(vValue.size(), false);
2283 bool fReachedTarget = false;
2284 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2286 for (unsigned int i = 0; i < vValue.size(); i++)
2288 //The solver here uses a randomized algorithm,
2289 //the randomness serves no real security purpose but is just
2290 //needed to prevent degenerate behavior and it is important
2291 //that the rng is fast. We do not use a constant random sequence,
2292 //because there may be some privacy improvement by making
2293 //the selection random.
2294 if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
2296 nTotal += vValue[i].first;
2297 vfIncluded[i] = true;
2298 if (nTotal >= nTargetValue)
2300 fReachedTarget = true;
2304 vfBest = vfIncluded;
2306 nTotal -= vValue[i].first;
2307 vfIncluded[i] = false;
2315 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
2316 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
2318 setCoinsRet.clear();
2321 // List of values less than target
2322 pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
2323 coinLowestLarger.first = std::numeric_limits<CAmount>::max();
2324 coinLowestLarger.second.first = NULL;
2325 vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
2326 CAmount nTotalLower = 0;
2328 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2330 BOOST_FOREACH(const COutput &output, vCoins)
2332 if (!output.fSpendable)
2335 const CWalletTx *pcoin = output.tx;
2337 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2341 CAmount n = pcoin->vout[i].nValue;
2343 pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
2345 if (n == nTargetValue)
2347 setCoinsRet.insert(coin.second);
2348 nValueRet += coin.first;
2351 else if (n < nTargetValue + CENT)
2353 vValue.push_back(coin);
2356 else if (n < coinLowestLarger.first)
2358 coinLowestLarger = coin;
2362 if (nTotalLower == nTargetValue)
2364 for (unsigned int i = 0; i < vValue.size(); ++i)
2366 setCoinsRet.insert(vValue[i].second);
2367 nValueRet += vValue[i].first;
2372 if (nTotalLower < nTargetValue)
2374 if (coinLowestLarger.second.first == NULL)
2376 setCoinsRet.insert(coinLowestLarger.second);
2377 nValueRet += coinLowestLarger.first;
2381 // Solve subset sum by stochastic approximation
2382 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
2383 vector<char> vfBest;
2386 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
2387 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
2388 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
2390 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2391 // or the next bigger coin is closer), return the bigger coin
2392 if (coinLowestLarger.second.first &&
2393 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
2395 setCoinsRet.insert(coinLowestLarger.second);
2396 nValueRet += coinLowestLarger.first;
2399 for (unsigned int i = 0; i < vValue.size(); i++)
2402 setCoinsRet.insert(vValue[i].second);
2403 nValueRet += vValue[i].first;
2406 LogPrint("selectcoins", "SelectCoins() best subset: ");
2407 for (unsigned int i = 0; i < vValue.size(); i++)
2409 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
2410 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
2416 bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, bool& fOnlyCoinbaseCoinsRet, bool& fNeedCoinbaseCoinsRet, const CCoinControl* coinControl) const
2418 // Output parameter fOnlyCoinbaseCoinsRet is set to true when the only available coins are coinbase utxos.
2419 vector<COutput> vCoinsNoCoinbase, vCoinsWithCoinbase;
2420 AvailableCoins(vCoinsNoCoinbase, true, coinControl, false, false);
2421 AvailableCoins(vCoinsWithCoinbase, true, coinControl, false, true);
2422 fOnlyCoinbaseCoinsRet = vCoinsNoCoinbase.size() == 0 && vCoinsWithCoinbase.size() > 0;
2424 // If coinbase utxos can only be sent to zaddrs, exclude any coinbase utxos from coin selection.
2425 bool fProtectCoinbase = Params().GetConsensus().fCoinbaseMustBeProtected;
2426 vector<COutput> vCoins = (fProtectCoinbase) ? vCoinsNoCoinbase : vCoinsWithCoinbase;
2428 // Output parameter fNeedCoinbaseCoinsRet is set to true if coinbase utxos need to be spent to meet target amount
2429 if (fProtectCoinbase && vCoinsWithCoinbase.size() > vCoinsNoCoinbase.size()) {
2431 for (const COutput& out : vCoinsNoCoinbase) {
2432 if (!out.fSpendable) {
2435 value += out.tx->vout[out.i].nValue;
2437 if (value <= nTargetValue) {
2438 CAmount valueWithCoinbase = 0;
2439 for (const COutput& out : vCoinsWithCoinbase) {
2440 if (!out.fSpendable) {
2443 valueWithCoinbase += out.tx->vout[out.i].nValue;
2445 fNeedCoinbaseCoinsRet = (valueWithCoinbase >= nTargetValue);
2449 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2450 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2452 BOOST_FOREACH(const COutput& out, vCoins)
2454 if (!out.fSpendable)
2456 nValueRet += out.tx->vout[out.i].nValue;
2457 setCoinsRet.insert(make_pair(out.tx, out.i));
2459 return (nValueRet >= nTargetValue);
2462 // calculate value from preset inputs and store them
2463 set<pair<const CWalletTx*, uint32_t> > setPresetCoins;
2464 CAmount nValueFromPresetInputs = 0;
2466 std::vector<COutPoint> vPresetInputs;
2468 coinControl->ListSelected(vPresetInputs);
2469 BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
2471 map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2472 if (it != mapWallet.end())
2474 const CWalletTx* pcoin = &it->second;
2475 // Clearly invalid input, fail
2476 if (pcoin->vout.size() <= outpoint.n)
2478 nValueFromPresetInputs += pcoin->vout[outpoint.n].nValue;
2479 setPresetCoins.insert(make_pair(pcoin, outpoint.n));
2481 return false; // TODO: Allow non-wallet inputs
2484 // remove preset inputs from vCoins
2485 for (vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2487 if (setPresetCoins.count(make_pair(it->tx, it->i)))
2488 it = vCoins.erase(it);
2493 bool res = nTargetValue <= nValueFromPresetInputs ||
2494 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, vCoins, setCoinsRet, nValueRet) ||
2495 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, vCoins, setCoinsRet, nValueRet) ||
2496 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, vCoins, setCoinsRet, nValueRet));
2498 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2499 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2501 // add preset inputs to the total value selected
2502 nValueRet += nValueFromPresetInputs;
2507 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount &nFeeRet, int& nChangePosRet, std::string& strFailReason)
2509 vector<CRecipient> vecSend;
2511 // Turn the txout set into a CRecipient vector
2512 BOOST_FOREACH(const CTxOut& txOut, tx.vout)
2514 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, false};
2515 vecSend.push_back(recipient);
2518 CCoinControl coinControl;
2519 coinControl.fAllowOtherInputs = true;
2520 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2521 coinControl.Select(txin.prevout);
2523 CReserveKey reservekey(this);
2525 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosRet, strFailReason, &coinControl, false))
2528 if (nChangePosRet != -1)
2529 tx.vout.insert(tx.vout.begin() + nChangePosRet, wtx.vout[nChangePosRet]);
2531 // Add new txins (keeping original txin scriptSig/order)
2532 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
2535 BOOST_FOREACH(const CTxIn& origTxIn, tx.vin)
2537 if (txin.prevout.hash == origTxIn.prevout.hash && txin.prevout.n == origTxIn.prevout.n)
2544 tx.vin.push_back(txin);
2550 bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2551 int& nChangePosRet, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
2554 unsigned int nSubtractFeeFromAmount = 0;
2555 BOOST_FOREACH (const CRecipient& recipient, vecSend)
2557 if (nValue < 0 || recipient.nAmount < 0)
2559 strFailReason = _("Transaction amounts must be positive");
2562 nValue += recipient.nAmount;
2564 if (recipient.fSubtractFeeFromAmount)
2565 nSubtractFeeFromAmount++;
2567 if (vecSend.empty() || nValue < 0)
2569 strFailReason = _("Transaction amounts must be positive");
2573 wtxNew.fTimeReceivedIsTxTime = true;
2574 wtxNew.BindWallet(this);
2575 CMutableTransaction txNew;
2577 // Discourage fee sniping.
2579 // However because of a off-by-one-error in previous versions we need to
2580 // neuter it by setting nLockTime to at least one less than nBestHeight.
2581 // Secondly currently propagation of transactions created for block heights
2582 // corresponding to blocks that were just mined may be iffy - transactions
2583 // aren't re-accepted into the mempool - we additionally neuter the code by
2584 // going ten blocks back. Doesn't yet do anything for sniping, but does act
2585 // to shake out wallet bugs like not showing nLockTime'd transactions at
2587 txNew.nLockTime = std::max(0, chainActive.Height() - 10);
2589 // Secondly occasionally randomly pick a nLockTime even further back, so
2590 // that transactions that are delayed after signing for whatever reason,
2591 // e.g. high-latency mix networks and some CoinJoin implementations, have
2593 if (GetRandInt(10) == 0)
2594 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2596 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2597 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2600 LOCK2(cs_main, cs_wallet);
2607 wtxNew.fFromMe = true;
2611 CAmount nTotalValue = nValue;
2612 if (nSubtractFeeFromAmount == 0)
2613 nTotalValue += nFeeRet;
2614 double dPriority = 0;
2615 // vouts to the payees
2616 BOOST_FOREACH (const CRecipient& recipient, vecSend)
2618 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2620 if (recipient.fSubtractFeeFromAmount)
2622 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2624 if (fFirst) // first receiver pays the remainder not divisible by output count
2627 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2631 if (txout.IsDust(::minRelayTxFee))
2633 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2635 if (txout.nValue < 0)
2636 strFailReason = _("The transaction amount is too small to pay the fee");
2638 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2641 strFailReason = _("Transaction amount too small");
2644 txNew.vout.push_back(txout);
2647 // Choose coins to use
2648 set<pair<const CWalletTx*,unsigned int> > setCoins;
2649 CAmount nValueIn = 0;
2650 bool fOnlyCoinbaseCoins = false;
2651 bool fNeedCoinbaseCoins = false;
2652 if (!SelectCoins(nTotalValue, setCoins, nValueIn, fOnlyCoinbaseCoins, fNeedCoinbaseCoins, coinControl))
2654 if (fOnlyCoinbaseCoins && Params().GetConsensus().fCoinbaseMustBeProtected) {
2655 strFailReason = _("Coinbase funds can only be sent to a zaddr");
2656 } else if (fNeedCoinbaseCoins) {
2657 strFailReason = _("Insufficient funds, coinbase funds can only be spent after they have been sent to a zaddr");
2659 strFailReason = _("Insufficient funds");
2663 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
2665 CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
2666 //The coin age after the next block (depth+1) is used instead of the current,
2667 //reflecting an assumption the user would accept a bit more delay for
2668 //a chance at a free transaction.
2669 //But mempool inputs might still be in the mempool, so their age stays 0
2670 int age = pcoin.first->GetDepthInMainChain();
2673 dPriority += (double)nCredit * age;
2676 CAmount nChange = nValueIn - nValue;
2677 if (nSubtractFeeFromAmount == 0)
2682 // Fill a vout to ourself
2683 // TODO: pass in scriptChange instead of reservekey so
2684 // change transaction isn't always pay-to-bitcoin-address
2685 CScript scriptChange;
2687 // coin control: send change to custom address
2688 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
2689 scriptChange = GetScriptForDestination(coinControl->destChange);
2691 // no coin control: send change to newly generated address
2694 // Note: We use a new key here to keep it from being obvious which side is the change.
2695 // The drawback is that by not reusing a previous key, the change may be lost if a
2696 // backup is restored, if the backup doesn't have the new private key for the change.
2697 // If we reused the old key, it would be possible to add code to look for and
2698 // rediscover unknown transactions that were written with keys of ours to recover
2699 // post-backup change.
2701 // Reserve a new key pair from key pool
2704 ret = reservekey.GetReservedKey(vchPubKey);
2705 assert(ret); // should never fail, as we just unlocked
2707 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2710 CTxOut newTxOut(nChange, scriptChange);
2712 // We do not move dust-change to fees, because the sender would end up paying more than requested.
2713 // This would be against the purpose of the all-inclusive feature.
2714 // So instead we raise the change and deduct from the recipient.
2715 if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust(::minRelayTxFee))
2717 CAmount nDust = newTxOut.GetDustThreshold(::minRelayTxFee) - newTxOut.nValue;
2718 newTxOut.nValue += nDust; // raise change until no more dust
2719 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
2721 if (vecSend[i].fSubtractFeeFromAmount)
2723 txNew.vout[i].nValue -= nDust;
2724 if (txNew.vout[i].IsDust(::minRelayTxFee))
2726 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2734 // Never create dust outputs; if we would, just
2735 // add the dust to the fee.
2736 if (newTxOut.IsDust(::minRelayTxFee))
2739 reservekey.ReturnKey();
2743 // Insert change txn at random position:
2744 nChangePosRet = GetRandInt(txNew.vout.size()+1);
2745 vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosRet;
2746 txNew.vout.insert(position, newTxOut);
2750 reservekey.ReturnKey();
2754 // Note how the sequence number is set to max()-1 so that the
2755 // nLockTime set above actually works.
2756 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2757 txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
2758 std::numeric_limits<unsigned int>::max()-1));
2760 // Check mempooltxinputlimit to avoid creating a transaction which the local mempool rejects
2761 size_t limit = (size_t)GetArg("-mempooltxinputlimit", 0);
2763 size_t n = txNew.vin.size();
2765 strFailReason = _(strprintf("Too many transparent inputs %zu > limit %zu", n, limit).c_str());
2772 CTransaction txNewConst(txNew);
2773 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2776 const CScript& scriptPubKey = coin.first->vout[coin.second].scriptPubKey;
2777 CScript& scriptSigRes = txNew.vin[nIn].scriptSig;
2779 signSuccess = ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, SIGHASH_ALL), scriptPubKey, scriptSigRes);
2781 signSuccess = ProduceSignature(DummySignatureCreator(this), scriptPubKey, scriptSigRes);
2785 strFailReason = _("Signing transaction failed");
2791 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2793 // Remove scriptSigs if we used dummy signatures for fee calculation
2795 BOOST_FOREACH (CTxIn& vin, txNew.vin)
2796 vin.scriptSig = CScript();
2799 // Embed the constructed transaction data in wtxNew.
2800 *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
2803 if (nBytes >= MAX_TX_SIZE)
2805 strFailReason = _("Transaction too large");
2809 dPriority = wtxNew.ComputePriority(dPriority, nBytes);
2811 // Can we complete this as a free transaction?
2812 if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
2814 // Not enough fee: enough priority?
2815 double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
2816 // Not enough mempool history to estimate: use hard-coded AllowFree.
2817 if (dPriorityNeeded <= 0 && AllowFree(dPriority))
2820 // Small enough, and priority high enough, to send for free
2821 if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
2825 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
2827 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2828 // because we must be at the maximum allowed fee.
2829 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2831 strFailReason = _("Transaction too large for fee policy");
2835 if (nFeeRet >= nFeeNeeded)
2836 break; // Done, enough fee included.
2838 // Include more fee and try again.
2839 nFeeRet = nFeeNeeded;
2849 * Call after CreateTransaction unless you want to abort
2851 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2854 LOCK2(cs_main, cs_wallet);
2855 LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
2857 // This is only to keep the database open to defeat the auto-flush for the
2858 // duration of this scope. This is the only place where this optimization
2859 // maybe makes sense; please don't do it anywhere else.
2860 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r+") : NULL;
2862 // Take key pair from key pool so it won't be used again
2863 reservekey.KeepKey();
2865 // Add tx to wallet, because if it has change it's also ours,
2866 // otherwise just for transaction history.
2867 AddToWallet(wtxNew, false, pwalletdb);
2869 // Notify that old coins are spent
2870 set<CWalletTx*> setCoins;
2871 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2873 CWalletTx &coin = mapWallet[txin.prevout.hash];
2874 coin.BindWallet(this);
2875 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2882 // Track how many getdata requests our transaction gets
2883 mapRequestCount[wtxNew.GetHash()] = 0;
2885 if (fBroadcastTransactions)
2888 if (!wtxNew.AcceptToMemoryPool(false))
2890 // This must not fail. The transaction has already been signed and recorded.
2891 LogPrintf("CommitTransaction(): Error: Transaction not valid\n");
2894 wtxNew.RelayWalletTransaction();
2900 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
2902 // payTxFee is user-set "I want to pay this much"
2903 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
2904 // user selected total at least (default=true)
2905 if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
2906 nFeeNeeded = payTxFee.GetFeePerK();
2907 // User didn't set: use -txconfirmtarget to estimate...
2908 if (nFeeNeeded == 0)
2909 nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
2910 // ... unless we don't have enough mempool data, in which case fall
2911 // back to a hard-coded fee
2912 if (nFeeNeeded == 0)
2913 nFeeNeeded = minTxFee.GetFee(nTxBytes);
2914 // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
2915 if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
2916 nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
2917 // But always obey the maximum
2918 if (nFeeNeeded > maxTxFee)
2919 nFeeNeeded = maxTxFee;
2926 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2930 fFirstRunRet = false;
2931 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2932 if (nLoadWalletRet == DB_NEED_REWRITE)
2934 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2938 // Note: can't top-up keypool here, because wallet is locked.
2939 // User will be prompted to unlock wallet the next operation
2940 // that requires a new key.
2944 if (nLoadWalletRet != DB_LOAD_OK)
2945 return nLoadWalletRet;
2946 fFirstRunRet = !vchDefaultKey.IsValid();
2948 uiInterface.LoadWallet(this);
2954 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
2958 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
2959 if (nZapWalletTxRet == DB_NEED_REWRITE)
2961 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2965 // Note: can't top-up keypool here, because wallet is locked.
2966 // User will be prompted to unlock wallet the next operation
2967 // that requires a new key.
2971 if (nZapWalletTxRet != DB_LOAD_OK)
2972 return nZapWalletTxRet;
2978 bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
2980 bool fUpdated = false;
2982 LOCK(cs_wallet); // mapAddressBook
2983 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
2984 fUpdated = mi != mapAddressBook.end();
2985 mapAddressBook[address].name = strName;
2986 if (!strPurpose.empty()) /* update purpose only if requested */
2987 mapAddressBook[address].purpose = strPurpose;
2989 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
2990 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
2993 if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
2995 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2998 bool CWallet::DelAddressBook(const CTxDestination& address)
3001 LOCK(cs_wallet); // mapAddressBook
3005 // Delete destdata tuples associated with address
3006 std::string strAddress = CBitcoinAddress(address).ToString();
3007 BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
3009 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
3012 mapAddressBook.erase(address);
3015 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3019 CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
3020 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
3023 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3027 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
3030 vchDefaultKey = vchPubKey;
3035 * Mark old keypool keys as used,
3036 * and generate all new keys
3038 bool CWallet::NewKeyPool()
3042 CWalletDB walletdb(strWalletFile);
3043 BOOST_FOREACH(int64_t nIndex, setKeyPool)
3044 walletdb.ErasePool(nIndex);
3050 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
3051 for (int i = 0; i < nKeys; i++)
3053 int64_t nIndex = i+1;
3054 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
3055 setKeyPool.insert(nIndex);
3057 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
3062 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3070 CWalletDB walletdb(strWalletFile);
3073 unsigned int nTargetSize;
3075 nTargetSize = kpSize;
3077 nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0);
3079 while (setKeyPool.size() < (nTargetSize + 1))
3082 if (!setKeyPool.empty())
3083 nEnd = *(--setKeyPool.end()) + 1;
3084 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
3085 throw runtime_error("TopUpKeyPool(): writing generated key failed");
3086 setKeyPool.insert(nEnd);
3087 LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
3093 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
3096 keypool.vchPubKey = CPubKey();
3103 // Get the oldest key
3104 if(setKeyPool.empty())
3107 CWalletDB walletdb(strWalletFile);
3109 nIndex = *(setKeyPool.begin());
3110 setKeyPool.erase(setKeyPool.begin());
3111 if (!walletdb.ReadPool(nIndex, keypool))
3112 throw runtime_error("ReserveKeyFromKeyPool(): read failed");
3113 if (!HaveKey(keypool.vchPubKey.GetID()))
3114 throw runtime_error("ReserveKeyFromKeyPool(): unknown key in key pool");
3115 assert(keypool.vchPubKey.IsValid());
3116 LogPrintf("keypool reserve %d\n", nIndex);
3120 void CWallet::KeepKey(int64_t nIndex)
3122 // Remove from key pool
3125 CWalletDB walletdb(strWalletFile);
3126 walletdb.ErasePool(nIndex);
3128 LogPrintf("keypool keep %d\n", nIndex);
3131 void CWallet::ReturnKey(int64_t nIndex)
3133 // Return to key pool
3136 setKeyPool.insert(nIndex);
3138 LogPrintf("keypool return %d\n", nIndex);
3141 bool CWallet::GetKeyFromPool(CPubKey& result)
3147 ReserveKeyFromKeyPool(nIndex, keypool);
3150 if (IsLocked()) return false;
3151 result = GenerateNewKey();
3155 result = keypool.vchPubKey;
3160 int64_t CWallet::GetOldestKeyPoolTime()
3164 ReserveKeyFromKeyPool(nIndex, keypool);
3168 return keypool.nTime;
3171 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3173 map<CTxDestination, CAmount> balances;
3177 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3179 CWalletTx *pcoin = &walletEntry.second;
3181 if (!CheckFinalTx(*pcoin) || !pcoin->IsTrusted())
3184 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3187 int nDepth = pcoin->GetDepthInMainChain();
3188 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3191 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
3193 CTxDestination addr;
3194 if (!IsMine(pcoin->vout[i]))
3196 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
3199 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
3201 if (!balances.count(addr))
3203 balances[addr] += n;
3211 set< set<CTxDestination> > CWallet::GetAddressGroupings()
3213 AssertLockHeld(cs_wallet); // mapWallet
3214 set< set<CTxDestination> > groupings;
3215 set<CTxDestination> grouping;
3217 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3219 CWalletTx *pcoin = &walletEntry.second;
3221 if (pcoin->vin.size() > 0)
3223 bool any_mine = false;
3224 // group all input addresses with each other
3225 BOOST_FOREACH(CTxIn txin, pcoin->vin)
3227 CTxDestination address;
3228 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3230 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
3232 grouping.insert(address);
3236 // group change with input addresses
3239 BOOST_FOREACH(CTxOut txout, pcoin->vout)
3240 if (IsChange(txout))
3242 CTxDestination txoutAddr;
3243 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3245 grouping.insert(txoutAddr);
3248 if (grouping.size() > 0)
3250 groupings.insert(grouping);
3255 // group lone addrs by themselves
3256 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
3257 if (IsMine(pcoin->vout[i]))
3259 CTxDestination address;
3260 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
3262 grouping.insert(address);
3263 groupings.insert(grouping);
3268 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3269 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3270 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
3272 // make a set of all the groups hit by this new group
3273 set< set<CTxDestination>* > hits;
3274 map< CTxDestination, set<CTxDestination>* >::iterator it;
3275 BOOST_FOREACH(CTxDestination address, grouping)
3276 if ((it = setmap.find(address)) != setmap.end())
3277 hits.insert((*it).second);
3279 // merge all hit groups into a new single group and delete old groups
3280 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
3281 BOOST_FOREACH(set<CTxDestination>* hit, hits)
3283 merged->insert(hit->begin(), hit->end());
3284 uniqueGroupings.erase(hit);
3287 uniqueGroupings.insert(merged);
3290 BOOST_FOREACH(CTxDestination element, *merged)
3291 setmap[element] = merged;
3294 set< set<CTxDestination> > ret;
3295 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
3297 ret.insert(*uniqueGrouping);
3298 delete uniqueGrouping;
3304 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3307 set<CTxDestination> result;
3308 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
3310 const CTxDestination& address = item.first;
3311 const string& strName = item.second.name;
3312 if (strName == strAccount)
3313 result.insert(address);
3318 bool CReserveKey::GetReservedKey(CPubKey& pubkey)
3323 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
3325 vchPubKey = keypool.vchPubKey;
3330 assert(vchPubKey.IsValid());
3335 void CReserveKey::KeepKey()
3338 pwallet->KeepKey(nIndex);
3340 vchPubKey = CPubKey();
3343 void CReserveKey::ReturnKey()
3346 pwallet->ReturnKey(nIndex);
3348 vchPubKey = CPubKey();
3351 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
3355 CWalletDB walletdb(strWalletFile);
3357 LOCK2(cs_main, cs_wallet);
3358 BOOST_FOREACH(const int64_t& id, setKeyPool)
3361 if (!walletdb.ReadPool(id, keypool))
3362 throw runtime_error("GetAllReserveKeyHashes(): read failed");
3363 assert(keypool.vchPubKey.IsValid());
3364 CKeyID keyID = keypool.vchPubKey.GetID();
3365 if (!HaveKey(keyID))
3366 throw runtime_error("GetAllReserveKeyHashes(): unknown key in key pool");
3367 setAddress.insert(keyID);
3371 void CWallet::UpdatedTransaction(const uint256 &hashTx)
3375 // Only notify UI if this transaction is in this wallet
3376 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
3377 if (mi != mapWallet.end())
3378 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
3382 void CWallet::LockCoin(COutPoint& output)
3384 AssertLockHeld(cs_wallet); // setLockedCoins
3385 setLockedCoins.insert(output);
3388 void CWallet::UnlockCoin(COutPoint& output)
3390 AssertLockHeld(cs_wallet); // setLockedCoins
3391 setLockedCoins.erase(output);
3394 void CWallet::UnlockAllCoins()
3396 AssertLockHeld(cs_wallet); // setLockedCoins
3397 setLockedCoins.clear();
3400 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3402 AssertLockHeld(cs_wallet); // setLockedCoins
3403 COutPoint outpt(hash, n);
3405 return (setLockedCoins.count(outpt) > 0);
3408 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
3410 AssertLockHeld(cs_wallet); // setLockedCoins
3411 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3412 it != setLockedCoins.end(); it++) {
3413 COutPoint outpt = (*it);
3414 vOutpts.push_back(outpt);
3418 /** @} */ // end of Actions
3420 class CAffectedKeysVisitor : public boost::static_visitor<void> {
3422 const CKeyStore &keystore;
3423 std::vector<CKeyID> &vKeys;
3426 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
3428 void Process(const CScript &script) {
3430 std::vector<CTxDestination> vDest;
3432 if (ExtractDestinations(script, type, vDest, nRequired)) {
3433 BOOST_FOREACH(const CTxDestination &dest, vDest)
3434 boost::apply_visitor(*this, dest);
3438 void operator()(const CKeyID &keyId) {
3439 if (keystore.HaveKey(keyId))
3440 vKeys.push_back(keyId);
3443 void operator()(const CScriptID &scriptId) {
3445 if (keystore.GetCScript(scriptId, script))
3449 void operator()(const CNoDestination &none) {}
3452 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
3453 AssertLockHeld(cs_wallet); // mapKeyMetadata
3454 mapKeyBirth.clear();
3456 // get birth times for keys with metadata
3457 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
3458 if (it->second.nCreateTime)
3459 mapKeyBirth[it->first] = it->second.nCreateTime;
3461 // map in which we'll infer heights of other keys
3462 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
3463 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3464 std::set<CKeyID> setKeys;
3466 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
3467 if (mapKeyBirth.count(keyid) == 0)
3468 mapKeyFirstBlock[keyid] = pindexMax;
3472 // if there are no such keys, we're done
3473 if (mapKeyFirstBlock.empty())
3476 // find first block that affects those keys, if there are any left
3477 std::vector<CKeyID> vAffected;
3478 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3479 // iterate over all wallet transactions...
3480 const CWalletTx &wtx = (*it).second;
3481 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3482 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3483 // ... which are already in a block
3484 int nHeight = blit->second->nHeight;
3485 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
3486 // iterate over all their outputs
3487 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3488 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
3489 // ... and all their affected keys
3490 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3491 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3492 rit->second = blit->second;
3499 // Extract block timestamps for those keys
3500 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3501 mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
3504 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3506 if (boost::get<CNoDestination>(&dest))
3509 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3512 return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3515 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3517 if (!mapAddressBook[dest].destdata.erase(key))
3521 return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3524 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3526 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3530 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3532 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3533 if(i != mapAddressBook.end())
3535 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3536 if(j != i->second.destdata.end())
3546 CKeyPool::CKeyPool()
3551 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
3554 vchPubKey = vchPubKeyIn;
3557 CWalletKey::CWalletKey(int64_t nExpires)
3559 nTimeCreated = (nExpires ? GetTime() : 0);
3560 nTimeExpires = nExpires;
3563 int CMerkleTx::SetMerkleBranch(const CBlock& block)
3565 AssertLockHeld(cs_main);
3568 // Update the tx's hashBlock
3569 hashBlock = block.GetHash();
3571 // Locate the transaction
3572 for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
3573 if (block.vtx[nIndex] == *(CTransaction*)this)
3575 if (nIndex == (int)block.vtx.size())
3577 vMerkleBranch.clear();
3579 LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
3583 // Fill in merkle branch
3584 vMerkleBranch = block.GetMerkleBranch(nIndex);
3586 // Is the tx in a block that's in the main chain
3587 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
3588 if (mi == mapBlockIndex.end())
3590 const CBlockIndex* pindex = (*mi).second;
3591 if (!pindex || !chainActive.Contains(pindex))
3594 return chainActive.Height() - pindex->nHeight + 1;
3597 int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const
3599 if (hashBlock.IsNull() || nIndex == -1)
3601 AssertLockHeld(cs_main);
3603 // Find the block it claims to be in
3604 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
3605 if (mi == mapBlockIndex.end())
3607 CBlockIndex* pindex = (*mi).second;
3608 if (!pindex || !chainActive.Contains(pindex))
3611 // Make sure the merkle branch connects to this block
3612 if (!fMerkleVerified)
3614 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
3616 fMerkleVerified = true;
3620 return chainActive.Height() - pindex->nHeight + 1;
3623 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
3625 AssertLockHeld(cs_main);
3626 int nResult = GetDepthInMainChainINTERNAL(pindexRet);
3627 if (nResult == 0 && !mempool.exists(GetHash()))
3628 return -1; // Not in chain, not in mempool
3633 int CMerkleTx::GetBlocksToMaturity() const
3637 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
3641 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectAbsurdFee)
3643 CValidationState state;
3644 return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectAbsurdFee);
3648 * Find notes in the wallet filtered by payment address, min depth and ability to spend.
3649 * These notes are decrypted and added to the output parameter vector, outEntries.
3651 void CWallet::GetFilteredNotes(std::vector<CNotePlaintextEntry> & outEntries, std::string address, int minDepth, bool ignoreSpent, bool ignoreUnspendable)
3653 bool fFilterAddress = false;
3654 libzcash::PaymentAddress filterPaymentAddress;
3655 if (address.length() > 0) {
3656 filterPaymentAddress = CZCPaymentAddress(address).Get();
3657 fFilterAddress = true;
3660 LOCK2(cs_main, cs_wallet);
3662 for (auto & p : mapWallet) {
3663 CWalletTx wtx = p.second;
3665 // Filter the transactions before checking for notes
3666 if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < minDepth) {
3670 if (wtx.mapNoteData.size() == 0) {
3674 for (auto & pair : wtx.mapNoteData) {
3675 JSOutPoint jsop = pair.first;
3676 CNoteData nd = pair.second;
3677 PaymentAddress pa = nd.address;
3679 // skip notes which belong to a different payment address in the wallet
3680 if (fFilterAddress && !(pa == filterPaymentAddress)) {
3684 // skip note which has been spent
3685 if (ignoreSpent && nd.nullifier && IsSpent(*nd.nullifier)) {
3689 // skip notes which cannot be spent
3690 if (ignoreUnspendable && !HaveSpendingKey(pa)) {
3694 int i = jsop.js; // Index into CTransaction.vjoinsplit
3695 int j = jsop.n; // Index into JSDescription.ciphertexts
3697 // Get cached decryptor
3698 ZCNoteDecryption decryptor;
3699 if (!GetNoteDecryptor(pa, decryptor)) {
3700 // Note decryptors are created when the wallet is loaded, so it should always exist
3701 throw std::runtime_error(strprintf("Could not find note decryptor for payment address %s", CZCPaymentAddress(pa).ToString()));
3704 // determine amount of funds in the note
3705 auto hSig = wtx.vjoinsplit[i].h_sig(*pzcashParams, wtx.joinSplitPubKey);
3707 NotePlaintext plaintext = NotePlaintext::decrypt(
3709 wtx.vjoinsplit[i].ciphertexts[j],
3710 wtx.vjoinsplit[i].ephemeralKey,
3714 outEntries.push_back(CNotePlaintextEntry{jsop, plaintext});
3716 } catch (const note_decryption_failed &err) {
3717 // Couldn't decrypt with this spending key
3718 throw std::runtime_error(strprintf("Could not decrypt note for payment address %s", CZCPaymentAddress(pa).ToString()));
3719 } catch (const std::exception &exc) {
3720 // Unexpected failure
3721 throw std::runtime_error(strprintf("Error while decrypting note for payment address %s: %s", CZCPaymentAddress(pa).ToString(), exc.what()));