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/upgrades.h"
12 #include "consensus/validation.h"
16 #include "script/script.h"
17 #include "script/sign.h"
19 #include "utilmoneystr.h"
20 #include "zcash/Note.hpp"
25 #include <boost/algorithm/string/replace.hpp>
26 #include <boost/filesystem.hpp>
27 #include <boost/thread.hpp>
30 using namespace libzcash;
35 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
36 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
37 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
38 bool bSpendZeroConfChange = true;
39 bool fSendFreeTransactions = false;
40 bool fPayAtLeastCustomFee = true;
43 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
44 * Override with -mintxfee
46 CFeeRate CWallet::minTxFee = CFeeRate(1000);
48 /** @defgroup mapWallet
53 struct CompareValueOnly
55 bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
56 const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
58 return t1.first < t2.first;
62 std::string JSOutPoint::ToString() const
64 return strprintf("JSOutPoint(%s, %d, %d)", hash.ToString().substr(0,10), js, n);
67 std::string COutput::ToString() const
69 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
72 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
75 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
76 if (it == mapWallet.end())
81 // Generate a new spending key and return its public payment address
82 CZCPaymentAddress CWallet::GenerateNewZKey()
84 AssertLockHeld(cs_wallet); // mapZKeyMetadata
85 auto k = SpendingKey::random();
86 auto addr = k.address();
88 // Check for collision, even though it is unlikely to ever occur
89 if (CCryptoKeyStore::HaveSpendingKey(addr))
90 throw std::runtime_error("CWallet::GenerateNewZKey(): Collision detected");
92 // Create new metadata
93 int64_t nCreationTime = GetTime();
94 mapZKeyMetadata[addr] = CKeyMetadata(nCreationTime);
96 CZCPaymentAddress pubaddr(addr);
98 throw std::runtime_error("CWallet::GenerateNewZKey(): AddZKey failed");
102 // Add spending key to keystore and persist to disk
103 bool CWallet::AddZKey(const libzcash::SpendingKey &key)
105 AssertLockHeld(cs_wallet); // mapZKeyMetadata
106 auto addr = key.address();
108 if (!CCryptoKeyStore::AddSpendingKey(key))
111 // check if we need to remove from viewing keys
112 if (HaveViewingKey(addr))
113 RemoveViewingKey(key.viewing_key());
119 return CWalletDB(strWalletFile).WriteZKey(addr,
121 mapZKeyMetadata[addr]);
126 CPubKey CWallet::GenerateNewKey()
128 AssertLockHeld(cs_wallet); // mapKeyMetadata
129 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
132 secret.MakeNewKey(fCompressed);
134 // Compressed public keys were introduced in version 0.6.0
136 SetMinVersion(FEATURE_COMPRPUBKEY);
138 CPubKey pubkey = secret.GetPubKey();
139 assert(secret.VerifyPubKey(pubkey));
141 // Create new metadata
142 int64_t nCreationTime = GetTime();
143 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
144 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
145 nTimeFirstKey = nCreationTime;
147 if (!AddKeyPubKey(secret, pubkey))
148 throw std::runtime_error("CWallet::GenerateNewKey(): AddKey failed");
152 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
154 AssertLockHeld(cs_wallet); // mapKeyMetadata
155 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
158 // check if we need to remove from watch-only
160 script = GetScriptForDestination(pubkey.GetID());
161 if (HaveWatchOnly(script))
162 RemoveWatchOnly(script);
167 return CWalletDB(strWalletFile).WriteKey(pubkey,
169 mapKeyMetadata[pubkey.GetID()]);
174 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
175 const vector<unsigned char> &vchCryptedSecret)
178 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
184 if (pwalletdbEncryption)
185 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
187 mapKeyMetadata[vchPubKey.GetID()]);
189 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
191 mapKeyMetadata[vchPubKey.GetID()]);
197 bool CWallet::AddCryptedSpendingKey(const libzcash::PaymentAddress &address,
198 const libzcash::ReceivingKey &rk,
199 const std::vector<unsigned char> &vchCryptedSecret)
201 if (!CCryptoKeyStore::AddCryptedSpendingKey(address, rk, vchCryptedSecret))
207 if (pwalletdbEncryption) {
208 return pwalletdbEncryption->WriteCryptedZKey(address,
211 mapZKeyMetadata[address]);
213 return CWalletDB(strWalletFile).WriteCryptedZKey(address,
216 mapZKeyMetadata[address]);
222 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
224 AssertLockHeld(cs_wallet); // mapKeyMetadata
225 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
226 nTimeFirstKey = meta.nCreateTime;
228 mapKeyMetadata[pubkey.GetID()] = meta;
232 bool CWallet::LoadZKeyMetadata(const PaymentAddress &addr, const CKeyMetadata &meta)
234 AssertLockHeld(cs_wallet); // mapZKeyMetadata
235 mapZKeyMetadata[addr] = meta;
239 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
241 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
244 bool CWallet::LoadCryptedZKey(const libzcash::PaymentAddress &addr, const libzcash::ReceivingKey &rk, const std::vector<unsigned char> &vchCryptedSecret)
246 return CCryptoKeyStore::AddCryptedSpendingKey(addr, rk, vchCryptedSecret);
249 bool CWallet::LoadZKey(const libzcash::SpendingKey &key)
251 return CCryptoKeyStore::AddSpendingKey(key);
254 bool CWallet::AddViewingKey(const libzcash::ViewingKey &vk)
256 if (!CCryptoKeyStore::AddViewingKey(vk)) {
259 nTimeFirstKey = 1; // No birthday information for viewing keys.
263 return CWalletDB(strWalletFile).WriteViewingKey(vk);
266 bool CWallet::RemoveViewingKey(const libzcash::ViewingKey &vk)
268 AssertLockHeld(cs_wallet);
269 if (!CCryptoKeyStore::RemoveViewingKey(vk)) {
273 if (!CWalletDB(strWalletFile).EraseViewingKey(vk)) {
281 bool CWallet::LoadViewingKey(const libzcash::ViewingKey &vk)
283 return CCryptoKeyStore::AddViewingKey(vk);
286 bool CWallet::AddCScript(const CScript& redeemScript)
288 if (!CCryptoKeyStore::AddCScript(redeemScript))
292 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
295 bool CWallet::LoadCScript(const CScript& redeemScript)
297 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
298 * that never can be redeemed. However, old wallets may still contain
299 * these. Do not add them to the wallet and warn. */
300 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
302 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
303 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",
304 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
308 return CCryptoKeyStore::AddCScript(redeemScript);
311 bool CWallet::AddWatchOnly(const CScript &dest)
313 if (!CCryptoKeyStore::AddWatchOnly(dest))
315 nTimeFirstKey = 1; // No birthday information for watch-only keys.
316 NotifyWatchonlyChanged(true);
319 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
322 bool CWallet::RemoveWatchOnly(const CScript &dest)
324 AssertLockHeld(cs_wallet);
325 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
327 if (!HaveWatchOnly())
328 NotifyWatchonlyChanged(false);
330 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
336 bool CWallet::LoadWatchOnly(const CScript &dest)
338 return CCryptoKeyStore::AddWatchOnly(dest);
341 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
344 CKeyingMaterial vMasterKey;
348 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
350 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
352 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
353 continue; // try another master key
354 if (CCryptoKeyStore::Unlock(vMasterKey))
361 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
363 bool fWasLocked = IsLocked();
370 CKeyingMaterial vMasterKey;
371 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
373 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
375 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
377 if (CCryptoKeyStore::Unlock(vMasterKey))
379 int64_t nStartTime = GetTimeMillis();
380 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
381 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
383 nStartTime = GetTimeMillis();
384 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
385 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
387 if (pMasterKey.second.nDeriveIterations < 25000)
388 pMasterKey.second.nDeriveIterations = 25000;
390 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
392 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
394 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
396 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
407 void CWallet::ChainTip(const CBlockIndex *pindex, const CBlock *pblock,
408 ZCIncrementalMerkleTree tree, bool added)
411 IncrementNoteWitnesses(pindex, pblock, tree);
413 DecrementNoteWitnesses(pindex);
417 void CWallet::SetBestChain(const CBlockLocator& loc)
419 CWalletDB walletdb(strWalletFile);
420 SetBestChainINTERNAL(walletdb, loc);
423 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
425 LOCK(cs_wallet); // nWalletVersion
426 if (nWalletVersion >= nVersion)
429 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
430 if (fExplicit && nVersion > nWalletMaxVersion)
431 nVersion = FEATURE_LATEST;
433 nWalletVersion = nVersion;
435 if (nVersion > nWalletMaxVersion)
436 nWalletMaxVersion = nVersion;
440 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
441 if (nWalletVersion > 40000)
442 pwalletdb->WriteMinVersion(nWalletVersion);
450 bool CWallet::SetMaxVersion(int nVersion)
452 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
453 // cannot downgrade below current version
454 if (nWalletVersion > nVersion)
457 nWalletMaxVersion = nVersion;
462 set<uint256> CWallet::GetConflicts(const uint256& txid) const
465 AssertLockHeld(cs_wallet);
467 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
468 if (it == mapWallet.end())
470 const CWalletTx& wtx = it->second;
472 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
474 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
476 if (mapTxSpends.count(txin.prevout) <= 1)
477 continue; // No conflict if zero or one spends
478 range = mapTxSpends.equal_range(txin.prevout);
479 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
480 result.insert(it->second);
483 std::pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range_n;
485 for (const JSDescription& jsdesc : wtx.vjoinsplit) {
486 for (const uint256& nullifier : jsdesc.nullifiers) {
487 if (mapTxNullifiers.count(nullifier) <= 1) {
488 continue; // No conflict if zero or one spends
490 range_n = mapTxNullifiers.equal_range(nullifier);
491 for (TxNullifiers::const_iterator it = range_n.first; it != range_n.second; ++it) {
492 result.insert(it->second);
499 void CWallet::Flush(bool shutdown)
501 bitdb.Flush(shutdown);
504 bool CWallet::Verify(const string& walletFile, string& warningString, string& errorString)
506 if (!bitdb.Open(GetDataDir()))
508 // try moving the database env out of the way
509 boost::filesystem::path pathDatabase = GetDataDir() / "database";
510 boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
512 boost::filesystem::rename(pathDatabase, pathDatabaseBak);
513 LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
514 } catch (const boost::filesystem::filesystem_error&) {
515 // failure is ok (well, not really, but it's not worse than what we started with)
519 if (!bitdb.Open(GetDataDir())) {
520 // if it still fails, it probably means we can't even create the database env
521 string msg = strprintf(_("Error initializing wallet database environment %s!"), GetDataDir());
527 if (GetBoolArg("-salvagewallet", false))
529 // Recover readable keypairs:
530 if (!CWalletDB::Recover(bitdb, walletFile, true))
534 if (boost::filesystem::exists(GetDataDir() / walletFile))
536 CDBEnv::VerifyResult r = bitdb.Verify(walletFile, CWalletDB::Recover);
537 if (r == CDBEnv::RECOVER_OK)
539 warningString += strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
540 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
541 " your balance or transactions are incorrect you should"
542 " restore from a backup."), GetDataDir());
544 if (r == CDBEnv::RECOVER_FAIL)
545 errorString += _("wallet.dat corrupt, salvage failed");
552 void CWallet::SyncMetaData(pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator> range)
554 // We want all the wallet transactions in range to have the same metadata as
555 // the oldest (smallest nOrderPos).
556 // So: find smallest nOrderPos:
558 int nMinOrderPos = std::numeric_limits<int>::max();
559 const CWalletTx* copyFrom = NULL;
560 for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
562 const uint256& hash = it->second;
563 int n = mapWallet[hash].nOrderPos;
564 if (n < nMinOrderPos)
567 copyFrom = &mapWallet[hash];
570 // Now copy data from copyFrom to rest:
571 for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
573 const uint256& hash = it->second;
574 CWalletTx* copyTo = &mapWallet[hash];
575 if (copyFrom == copyTo) continue;
576 copyTo->mapValue = copyFrom->mapValue;
577 // mapNoteData not copied on purpose
578 // (it is always set correctly for each CWalletTx)
579 copyTo->vOrderForm = copyFrom->vOrderForm;
580 // fTimeReceivedIsTxTime not copied on purpose
581 // nTimeReceived not copied on purpose
582 copyTo->nTimeSmart = copyFrom->nTimeSmart;
583 copyTo->fFromMe = copyFrom->fFromMe;
584 copyTo->strFromAccount = copyFrom->strFromAccount;
585 // nOrderPos not copied on purpose
586 // cached members not copied on purpose
591 * Outpoint is spent if any non-conflicted transaction
594 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
596 const COutPoint outpoint(hash, n);
597 pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
598 range = mapTxSpends.equal_range(outpoint);
600 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
602 const uint256& wtxid = it->second;
603 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
604 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
605 return true; // Spent
611 * Note is spent if any non-conflicted transaction
614 bool CWallet::IsSpent(const uint256& nullifier) const
616 pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range;
617 range = mapTxNullifiers.equal_range(nullifier);
619 for (TxNullifiers::const_iterator it = range.first; it != range.second; ++it) {
620 const uint256& wtxid = it->second;
621 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
622 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) {
623 return true; // Spent
629 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
631 mapTxSpends.insert(make_pair(outpoint, wtxid));
633 pair<TxSpends::iterator, TxSpends::iterator> range;
634 range = mapTxSpends.equal_range(outpoint);
635 SyncMetaData<COutPoint>(range);
638 void CWallet::AddToSpends(const uint256& nullifier, const uint256& wtxid)
640 mapTxNullifiers.insert(make_pair(nullifier, wtxid));
642 pair<TxNullifiers::iterator, TxNullifiers::iterator> range;
643 range = mapTxNullifiers.equal_range(nullifier);
644 SyncMetaData<uint256>(range);
647 void CWallet::AddToSpends(const uint256& wtxid)
649 assert(mapWallet.count(wtxid));
650 CWalletTx& thisTx = mapWallet[wtxid];
651 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
654 for (const CTxIn& txin : thisTx.vin) {
655 AddToSpends(txin.prevout, wtxid);
657 for (const JSDescription& jsdesc : thisTx.vjoinsplit) {
658 for (const uint256& nullifier : jsdesc.nullifiers) {
659 AddToSpends(nullifier, wtxid);
664 void CWallet::ClearNoteWitnessCache()
667 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
668 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
669 item.second.witnesses.clear();
670 item.second.witnessHeight = -1;
673 nWitnessCacheSize = 0;
676 void CWallet::IncrementNoteWitnesses(const CBlockIndex* pindex,
677 const CBlock* pblockIn,
678 ZCIncrementalMerkleTree& tree)
682 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
683 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
684 CNoteData* nd = &(item.second);
685 // Only increment witnesses that are behind the current height
686 if (nd->witnessHeight < pindex->nHeight) {
687 // Check the validity of the cache
688 // The only time a note witnessed above the current height
689 // would be invalid here is during a reindex when blocks
690 // have been decremented, and we are incrementing the blocks
691 // immediately after.
692 assert(nWitnessCacheSize >= nd->witnesses.size());
693 // Witnesses being incremented should always be either -1
694 // (never incremented or decremented) or one below pindex
695 assert((nd->witnessHeight == -1) ||
696 (nd->witnessHeight == pindex->nHeight - 1));
697 // Copy the witness for the previous block if we have one
698 if (nd->witnesses.size() > 0) {
699 nd->witnesses.push_front(nd->witnesses.front());
701 if (nd->witnesses.size() > WITNESS_CACHE_SIZE) {
702 nd->witnesses.pop_back();
707 if (nWitnessCacheSize < WITNESS_CACHE_SIZE) {
708 nWitnessCacheSize += 1;
711 const CBlock* pblock {pblockIn};
714 ReadBlockFromDisk(block, pindex);
718 for (const CTransaction& tx : pblock->vtx) {
719 auto hash = tx.GetHash();
720 bool txIsOurs = mapWallet.count(hash);
721 for (size_t i = 0; i < tx.vjoinsplit.size(); i++) {
722 const JSDescription& jsdesc = tx.vjoinsplit[i];
723 for (uint8_t j = 0; j < jsdesc.commitments.size(); j++) {
724 const uint256& note_commitment = jsdesc.commitments[j];
725 tree.append(note_commitment);
727 // Increment existing witnesses
728 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
729 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
730 CNoteData* nd = &(item.second);
731 if (nd->witnessHeight < pindex->nHeight &&
732 nd->witnesses.size() > 0) {
733 // Check the validity of the cache
734 // See earlier comment about validity.
735 assert(nWitnessCacheSize >= nd->witnesses.size());
736 nd->witnesses.front().append(note_commitment);
741 // If this is our note, witness it
743 JSOutPoint jsoutpt {hash, i, j};
744 if (mapWallet[hash].mapNoteData.count(jsoutpt) &&
745 mapWallet[hash].mapNoteData[jsoutpt].witnessHeight < pindex->nHeight) {
746 CNoteData* nd = &(mapWallet[hash].mapNoteData[jsoutpt]);
747 if (nd->witnesses.size() > 0) {
748 // We think this can happen because we write out the
749 // witness cache state after every block increment or
750 // decrement, but the block index itself is written in
751 // batches. So if the node crashes in between these two
752 // operations, it is possible for IncrementNoteWitnesses
753 // to be called again on previously-cached blocks. This
754 // doesn't affect existing cached notes because of the
755 // CNoteData::witnessHeight checks. See #1378 for details.
756 LogPrintf("Inconsistent witness cache state found for %s\n- Cache size: %d\n- Top (height %d): %s\n- New (height %d): %s\n",
757 jsoutpt.ToString(), nd->witnesses.size(),
759 nd->witnesses.front().root().GetHex(),
761 tree.witness().root().GetHex());
762 nd->witnesses.clear();
764 nd->witnesses.push_front(tree.witness());
765 // Set height to one less than pindex so it gets incremented
766 nd->witnessHeight = pindex->nHeight - 1;
767 // Check the validity of the cache
768 assert(nWitnessCacheSize >= nd->witnesses.size());
775 // Update witness heights
776 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
777 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
778 CNoteData* nd = &(item.second);
779 if (nd->witnessHeight < pindex->nHeight) {
780 nd->witnessHeight = pindex->nHeight;
781 // Check the validity of the cache
782 // See earlier comment about validity.
783 assert(nWitnessCacheSize >= nd->witnesses.size());
788 // For performance reasons, we write out the witness cache in
789 // CWallet::SetBestChain() (which also ensures that overall consistency
790 // of the wallet.dat is maintained).
794 void CWallet::DecrementNoteWitnesses(const CBlockIndex* pindex)
798 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
799 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
800 CNoteData* nd = &(item.second);
801 // Only increment witnesses that are not above the current height
802 if (nd->witnessHeight <= pindex->nHeight) {
803 // Check the validity of the cache
804 // See comment below (this would be invalid if there was a
806 assert(nWitnessCacheSize >= nd->witnesses.size());
807 // Witnesses being decremented should always be either -1
808 // (never incremented or decremented) or equal to pindex
809 assert((nd->witnessHeight == -1) ||
810 (nd->witnessHeight == pindex->nHeight));
811 if (nd->witnesses.size() > 0) {
812 nd->witnesses.pop_front();
814 // pindex is the block being removed, so the new witness cache
815 // height is one below it.
816 nd->witnessHeight = pindex->nHeight - 1;
820 nWitnessCacheSize -= 1;
821 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
822 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
823 CNoteData* nd = &(item.second);
824 // Check the validity of the cache
825 // Technically if there are notes witnessed above the current
826 // height, their cache will now be invalid (relative to the new
827 // value of nWitnessCacheSize). However, this would only occur
828 // during a reindex, and by the time the reindex reaches the tip
829 // of the chain again, the existing witness caches will be valid
831 // We don't set nWitnessCacheSize to zero at the start of the
832 // reindex because the on-disk blocks had already resulted in a
833 // chain that didn't trigger the assertion below.
834 if (nd->witnessHeight < pindex->nHeight) {
835 assert(nWitnessCacheSize >= nd->witnesses.size());
839 // TODO: If nWitnessCache is zero, we need to regenerate the caches (#1302)
840 assert(nWitnessCacheSize > 0);
842 // For performance reasons, we write out the witness cache in
843 // CWallet::SetBestChain() (which also ensures that overall consistency
844 // of the wallet.dat is maintained).
848 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
853 CKeyingMaterial vMasterKey;
855 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
856 GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
858 CMasterKey kMasterKey;
860 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
861 GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
864 int64_t nStartTime = GetTimeMillis();
865 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
866 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
868 nStartTime = GetTimeMillis();
869 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
870 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
872 if (kMasterKey.nDeriveIterations < 25000)
873 kMasterKey.nDeriveIterations = 25000;
875 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
877 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
879 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
884 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
887 assert(!pwalletdbEncryption);
888 pwalletdbEncryption = new CWalletDB(strWalletFile);
889 if (!pwalletdbEncryption->TxnBegin()) {
890 delete pwalletdbEncryption;
891 pwalletdbEncryption = NULL;
894 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
897 if (!EncryptKeys(vMasterKey))
900 pwalletdbEncryption->TxnAbort();
901 delete pwalletdbEncryption;
903 // We now probably have half of our keys encrypted in memory, and half not...
904 // die and let the user reload the unencrypted wallet.
908 // Encryption was introduced in version 0.4.0
909 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
913 if (!pwalletdbEncryption->TxnCommit()) {
914 delete pwalletdbEncryption;
915 // We now have keys encrypted in memory, but not on disk...
916 // die to avoid confusion and let the user reload the unencrypted wallet.
920 delete pwalletdbEncryption;
921 pwalletdbEncryption = NULL;
925 Unlock(strWalletPassphrase);
929 // Need to completely rewrite the wallet file; if we don't, bdb might keep
930 // bits of the unencrypted private key in slack space in the database file.
931 CDB::Rewrite(strWalletFile);
934 NotifyStatusChanged(this);
939 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
941 AssertLockHeld(cs_wallet); // nOrderPosNext
942 int64_t nRet = nOrderPosNext++;
944 pwalletdb->WriteOrderPosNext(nOrderPosNext);
946 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
951 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
953 AssertLockHeld(cs_wallet); // mapWallet
954 CWalletDB walletdb(strWalletFile);
956 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
959 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
960 // would make this much faster for applications that do this a lot.
961 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
963 CWalletTx* wtx = &((*it).second);
964 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
967 walletdb.ListAccountCreditDebit(strAccount, acentries);
968 BOOST_FOREACH(CAccountingEntry& entry, acentries)
970 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
976 void CWallet::MarkDirty()
980 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
981 item.second.MarkDirty();
986 * Ensure that every note in the wallet (for which we possess a spending key)
987 * has a cached nullifier.
989 bool CWallet::UpdateNullifierNoteMap()
997 ZCNoteDecryption dec;
998 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
999 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
1000 if (!item.second.nullifier) {
1001 if (GetNoteDecryptor(item.second.address, dec)) {
1002 auto i = item.first.js;
1003 auto hSig = wtxItem.second.vjoinsplit[i].h_sig(
1004 *pzcashParams, wtxItem.second.joinSplitPubKey);
1005 item.second.nullifier = GetNoteNullifier(
1006 wtxItem.second.vjoinsplit[i],
1007 item.second.address,
1014 UpdateNullifierNoteMapWithTx(wtxItem.second);
1021 * Update mapNullifiersToNotes with the cached nullifiers in this tx.
1023 void CWallet::UpdateNullifierNoteMapWithTx(const CWalletTx& wtx)
1027 for (const mapNoteData_t::value_type& item : wtx.mapNoteData) {
1028 if (item.second.nullifier) {
1029 mapNullifiersToNotes[*item.second.nullifier] = item.first;
1035 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb)
1037 uint256 hash = wtxIn.GetHash();
1039 if (fFromLoadWallet)
1041 mapWallet[hash] = wtxIn;
1042 mapWallet[hash].BindWallet(this);
1043 UpdateNullifierNoteMapWithTx(mapWallet[hash]);
1049 // Inserts only if not already there, returns tx inserted or tx found
1050 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
1051 CWalletTx& wtx = (*ret.first).second;
1052 wtx.BindWallet(this);
1053 UpdateNullifierNoteMapWithTx(wtx);
1054 bool fInsertedNew = ret.second;
1057 wtx.nTimeReceived = GetAdjustedTime();
1058 wtx.nOrderPos = IncOrderPosNext(pwalletdb);
1060 wtx.nTimeSmart = wtx.nTimeReceived;
1061 if (!wtxIn.hashBlock.IsNull())
1063 if (mapBlockIndex.count(wtxIn.hashBlock))
1065 int64_t latestNow = wtx.nTimeReceived;
1066 int64_t latestEntry = 0;
1068 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
1069 int64_t latestTolerated = latestNow + 300;
1070 std::list<CAccountingEntry> acentries;
1071 TxItems txOrdered = OrderedTxItems(acentries);
1072 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
1074 CWalletTx *const pwtx = (*it).second.first;
1077 CAccountingEntry *const pacentry = (*it).second.second;
1081 nSmartTime = pwtx->nTimeSmart;
1083 nSmartTime = pwtx->nTimeReceived;
1086 nSmartTime = pacentry->nTime;
1087 if (nSmartTime <= latestTolerated)
1089 latestEntry = nSmartTime;
1090 if (nSmartTime > latestNow)
1091 latestNow = nSmartTime;
1097 int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
1098 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
1101 LogPrintf("AddToWallet(): found %s in block %s not in index\n",
1102 wtxIn.GetHash().ToString(),
1103 wtxIn.hashBlock.ToString());
1108 bool fUpdated = false;
1112 if (!wtxIn.hashBlock.IsNull() && wtxIn.hashBlock != wtx.hashBlock)
1114 wtx.hashBlock = wtxIn.hashBlock;
1117 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
1119 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
1120 wtx.nIndex = wtxIn.nIndex;
1123 if (UpdatedNoteData(wtxIn, wtx)) {
1126 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
1128 wtx.fFromMe = wtxIn.fFromMe;
1134 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
1137 if (fInsertedNew || fUpdated)
1138 if (!wtx.WriteToDisk(pwalletdb))
1141 // Break debit/credit balance caches:
1144 // Notify UI of new or updated transaction
1145 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
1147 // notify an external script when a wallet transaction comes in or is updated
1148 std::string strCmd = GetArg("-walletnotify", "");
1150 if ( !strCmd.empty())
1152 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
1153 boost::thread t(runCommand, strCmd); // thread runs free
1160 bool CWallet::UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx)
1162 if (wtxIn.mapNoteData.empty() || wtxIn.mapNoteData == wtx.mapNoteData) {
1165 auto tmp = wtxIn.mapNoteData;
1166 // Ensure we keep any cached witnesses we may already have
1167 for (const std::pair<JSOutPoint, CNoteData> nd : wtx.mapNoteData) {
1168 if (tmp.count(nd.first) && nd.second.witnesses.size() > 0) {
1169 tmp.at(nd.first).witnesses.assign(
1170 nd.second.witnesses.cbegin(), nd.second.witnesses.cend());
1172 tmp.at(nd.first).witnessHeight = nd.second.witnessHeight;
1174 // Now copy over the updated note data
1175 wtx.mapNoteData = tmp;
1180 * Add a transaction to the wallet, or update it.
1181 * pblock is optional, but should be provided if the transaction is known to be in a block.
1182 * If fUpdate is true, existing transactions will be updated.
1184 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
1187 AssertLockHeld(cs_wallet);
1188 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1189 if (fExisted && !fUpdate) return false;
1190 auto noteData = FindMyNotes(tx);
1191 if (fExisted || IsMine(tx) || IsFromMe(tx) || noteData.size() > 0)
1193 CWalletTx wtx(this,tx);
1195 if (noteData.size() > 0) {
1196 wtx.SetNoteData(noteData);
1199 // Get merkle branch if transaction was found in a block
1201 wtx.SetMerkleBranch(*pblock);
1203 // Do not flush the wallet here for performance reasons
1204 // this is safe, as in case of a crash, we rescan the necessary blocks on startup through our SetBestChain-mechanism
1205 CWalletDB walletdb(strWalletFile, "r+", false);
1207 return AddToWallet(wtx, false, &walletdb);
1213 void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
1215 LOCK2(cs_main, cs_wallet);
1216 if (!AddToWalletIfInvolvingMe(tx, pblock, true))
1217 return; // Not one of ours
1219 MarkAffectedTransactionsDirty(tx);
1222 void CWallet::MarkAffectedTransactionsDirty(const CTransaction& tx)
1224 // If a transaction changes 'conflicted' state, that changes the balance
1225 // available of the outputs it spends. So force those to be
1226 // recomputed, also:
1227 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1229 if (mapWallet.count(txin.prevout.hash))
1230 mapWallet[txin.prevout.hash].MarkDirty();
1232 for (const JSDescription& jsdesc : tx.vjoinsplit) {
1233 for (const uint256& nullifier : jsdesc.nullifiers) {
1234 if (mapNullifiersToNotes.count(nullifier) &&
1235 mapWallet.count(mapNullifiersToNotes[nullifier].hash)) {
1236 mapWallet[mapNullifiersToNotes[nullifier].hash].MarkDirty();
1242 void CWallet::EraseFromWallet(const uint256 &hash)
1248 if (mapWallet.erase(hash))
1249 CWalletDB(strWalletFile).EraseTx(hash);
1256 * Returns a nullifier if the SpendingKey is available
1257 * Throws std::runtime_error if the decryptor doesn't match this note
1259 boost::optional<uint256> CWallet::GetNoteNullifier(const JSDescription& jsdesc,
1260 const libzcash::PaymentAddress& address,
1261 const ZCNoteDecryption& dec,
1262 const uint256& hSig,
1265 boost::optional<uint256> ret;
1266 auto note_pt = libzcash::NotePlaintext::decrypt(
1268 jsdesc.ciphertexts[n],
1269 jsdesc.ephemeralKey,
1272 auto note = note_pt.note(address);
1273 // SpendingKeys are only available if:
1274 // - We have them (this isn't a viewing key)
1275 // - The wallet is unlocked
1276 libzcash::SpendingKey key;
1277 if (GetSpendingKey(address, key)) {
1278 ret = note.nullifier(key);
1284 * Finds all output notes in the given transaction that have been sent to
1285 * PaymentAddresses in this wallet.
1287 * It should never be necessary to call this method with a CWalletTx, because
1288 * the result of FindMyNotes (for the addresses available at the time) will
1289 * already have been cached in CWalletTx.mapNoteData.
1291 mapNoteData_t CWallet::FindMyNotes(const CTransaction& tx) const
1293 LOCK(cs_SpendingKeyStore);
1294 uint256 hash = tx.GetHash();
1296 mapNoteData_t noteData;
1297 for (size_t i = 0; i < tx.vjoinsplit.size(); i++) {
1298 auto hSig = tx.vjoinsplit[i].h_sig(*pzcashParams, tx.joinSplitPubKey);
1299 for (uint8_t j = 0; j < tx.vjoinsplit[i].ciphertexts.size(); j++) {
1300 for (const NoteDecryptorMap::value_type& item : mapNoteDecryptors) {
1302 auto address = item.first;
1303 JSOutPoint jsoutpt {hash, i, j};
1304 auto nullifier = GetNoteNullifier(
1310 CNoteData nd {address, *nullifier};
1311 noteData.insert(std::make_pair(jsoutpt, nd));
1313 CNoteData nd {address};
1314 noteData.insert(std::make_pair(jsoutpt, nd));
1317 } catch (const note_decryption_failed &err) {
1318 // Couldn't decrypt with this decryptor
1319 } catch (const std::exception &exc) {
1320 // Unexpected failure
1321 LogPrintf("FindMyNotes(): Unexpected error while testing decrypt:\n");
1322 LogPrintf("%s\n", exc.what());
1330 bool CWallet::IsFromMe(const uint256& nullifier) const
1334 if (mapNullifiersToNotes.count(nullifier) &&
1335 mapWallet.count(mapNullifiersToNotes.at(nullifier).hash)) {
1342 void CWallet::GetNoteWitnesses(std::vector<JSOutPoint> notes,
1343 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
1344 uint256 &final_anchor)
1348 witnesses.resize(notes.size());
1349 boost::optional<uint256> rt;
1351 for (JSOutPoint note : notes) {
1352 if (mapWallet.count(note.hash) &&
1353 mapWallet[note.hash].mapNoteData.count(note) &&
1354 mapWallet[note.hash].mapNoteData[note].witnesses.size() > 0) {
1355 witnesses[i] = mapWallet[note.hash].mapNoteData[note].witnesses.front();
1357 rt = witnesses[i]->root();
1359 assert(*rt == witnesses[i]->root());
1364 // All returned witnesses have the same anchor
1371 isminetype CWallet::IsMine(const CTxIn &txin) const
1375 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1376 if (mi != mapWallet.end())
1378 const CWalletTx& prev = (*mi).second;
1379 if (txin.prevout.n < prev.vout.size())
1380 return IsMine(prev.vout[txin.prevout.n]);
1386 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1390 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1391 if (mi != mapWallet.end())
1393 const CWalletTx& prev = (*mi).second;
1394 if (txin.prevout.n < prev.vout.size())
1395 if (IsMine(prev.vout[txin.prevout.n]) & filter)
1396 return prev.vout[txin.prevout.n].nValue;
1402 isminetype CWallet::IsMine(const CTxOut& txout) const
1404 return ::IsMine(*this, txout.scriptPubKey);
1407 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1409 if (!MoneyRange(txout.nValue))
1410 throw std::runtime_error("CWallet::GetCredit(): value out of range");
1411 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1414 bool CWallet::IsChange(const CTxOut& txout) const
1416 // TODO: fix handling of 'change' outputs. The assumption is that any
1417 // payment to a script that is ours, but is not in the address book
1418 // is change. That assumption is likely to break when we implement multisignature
1419 // wallets that return change back into a multi-signature-protected address;
1420 // a better way of identifying which outputs are 'the send' and which are
1421 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1422 // which output, if any, was change).
1423 if (::IsMine(*this, txout.scriptPubKey))
1425 CTxDestination address;
1426 if (!ExtractDestination(txout.scriptPubKey, address))
1430 if (!mapAddressBook.count(address))
1436 CAmount CWallet::GetChange(const CTxOut& txout) const
1438 if (!MoneyRange(txout.nValue))
1439 throw std::runtime_error("CWallet::GetChange(): value out of range");
1440 return (IsChange(txout) ? txout.nValue : 0);
1443 bool CWallet::IsMine(const CTransaction& tx) const
1445 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1451 bool CWallet::IsFromMe(const CTransaction& tx) const
1453 if (GetDebit(tx, ISMINE_ALL) > 0) {
1456 for (const JSDescription& jsdesc : tx.vjoinsplit) {
1457 for (const uint256& nullifier : jsdesc.nullifiers) {
1458 if (IsFromMe(nullifier)) {
1466 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1469 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1471 nDebit += GetDebit(txin, filter);
1472 if (!MoneyRange(nDebit))
1473 throw std::runtime_error("CWallet::GetDebit(): value out of range");
1478 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1480 CAmount nCredit = 0;
1481 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1483 nCredit += GetCredit(txout, filter);
1484 if (!MoneyRange(nCredit))
1485 throw std::runtime_error("CWallet::GetCredit(): value out of range");
1490 CAmount CWallet::GetChange(const CTransaction& tx) const
1492 CAmount nChange = 0;
1493 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1495 nChange += GetChange(txout);
1496 if (!MoneyRange(nChange))
1497 throw std::runtime_error("CWallet::GetChange(): value out of range");
1502 void CWalletTx::SetNoteData(mapNoteData_t ¬eData)
1504 mapNoteData.clear();
1505 for (const std::pair<JSOutPoint, CNoteData> nd : noteData) {
1506 if (nd.first.js < vjoinsplit.size() &&
1507 nd.first.n < vjoinsplit[nd.first.js].ciphertexts.size()) {
1508 // Store the address and nullifier for the Note
1509 mapNoteData[nd.first] = nd.second;
1511 // If FindMyNotes() was used to obtain noteData,
1512 // this should never happen
1513 throw std::logic_error("CWalletTx::SetNoteData(): Invalid note");
1518 int64_t CWalletTx::GetTxTime() const
1520 int64_t n = nTimeSmart;
1521 return n ? n : nTimeReceived;
1524 int CWalletTx::GetRequestCount() const
1526 // Returns -1 if it wasn't being tracked
1529 LOCK(pwallet->cs_wallet);
1533 if (!hashBlock.IsNull())
1535 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1536 if (mi != pwallet->mapRequestCount.end())
1537 nRequests = (*mi).second;
1542 // Did anyone request this transaction?
1543 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1544 if (mi != pwallet->mapRequestCount.end())
1546 nRequests = (*mi).second;
1548 // How about the block it's in?
1549 if (nRequests == 0 && !hashBlock.IsNull())
1551 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1552 if (mi != pwallet->mapRequestCount.end())
1553 nRequests = (*mi).second;
1555 nRequests = 1; // If it's in someone else's block it must have got out
1563 // GetAmounts will determine the transparent debits and credits for a given wallet tx.
1564 void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
1565 list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
1568 listReceived.clear();
1570 strSentAccount = strFromAccount;
1572 // Is this tx sent/signed by me?
1573 CAmount nDebit = GetDebit(filter);
1574 bool isFromMyTaddr = nDebit > 0; // debit>0 means we signed/sent this transaction
1576 // Does this tx spend my notes?
1577 bool isFromMyZaddr = false;
1578 for (const JSDescription& js : vjoinsplit) {
1579 for (const uint256& nullifier : js.nullifiers) {
1580 if (pwallet->IsFromMe(nullifier)) {
1581 isFromMyZaddr = true;
1585 if (isFromMyZaddr) {
1590 // Compute fee if we sent this transaction.
1591 if (isFromMyTaddr) {
1592 CAmount nValueOut = GetValueOut(); // transparent outputs plus all vpub_old
1593 CAmount nValueIn = 0;
1594 for (const JSDescription & js : vjoinsplit) {
1595 nValueIn += js.vpub_new;
1597 nFee = nDebit - nValueOut + nValueIn;
1600 // Create output entry for vpub_old/new, if we sent utxos from this transaction
1601 if (isFromMyTaddr) {
1602 CAmount myVpubOld = 0;
1603 CAmount myVpubNew = 0;
1604 for (const JSDescription& js : vjoinsplit) {
1605 bool fMyJSDesc = false;
1608 for (const uint256& nullifier : js.nullifiers) {
1609 if (pwallet->IsFromMe(nullifier)) {
1615 // Check output side
1617 for (const std::pair<JSOutPoint, CNoteData> nd : this->mapNoteData) {
1618 if (nd.first.js < vjoinsplit.size() && nd.first.n < vjoinsplit[nd.first.js].ciphertexts.size()) {
1626 myVpubOld += js.vpub_old;
1627 myVpubNew += js.vpub_new;
1630 if (!MoneyRange(js.vpub_old) || !MoneyRange(js.vpub_new) || !MoneyRange(myVpubOld) || !MoneyRange(myVpubNew)) {
1631 throw std::runtime_error("CWalletTx::GetAmounts: value out of range");
1635 // Create an output for the value taken from or added to the transparent value pool by JoinSplits
1636 if (myVpubOld > myVpubNew) {
1637 COutputEntry output = {CNoDestination(), myVpubOld - myVpubNew, (int)vout.size()};
1638 listSent.push_back(output);
1639 } else if (myVpubNew > myVpubOld) {
1640 COutputEntry output = {CNoDestination(), myVpubNew - myVpubOld, (int)vout.size()};
1641 listReceived.push_back(output);
1646 for (unsigned int i = 0; i < vout.size(); ++i)
1648 const CTxOut& txout = vout[i];
1649 isminetype fIsMine = pwallet->IsMine(txout);
1650 // Only need to handle txouts if AT LEAST one of these is true:
1651 // 1) they debit from us (sent)
1652 // 2) the output is to us (received)
1655 // Don't report 'change' txouts
1656 if (pwallet->IsChange(txout))
1659 else if (!(fIsMine & filter))
1662 // In either case, we need to get the destination address
1663 CTxDestination address;
1664 if (!ExtractDestination(txout.scriptPubKey, address))
1666 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1667 this->GetHash().ToString());
1668 address = CNoDestination();
1671 COutputEntry output = {address, txout.nValue, (int)i};
1673 // If we are debited by the transaction, add the output as a "sent" entry
1675 listSent.push_back(output);
1677 // If we are receiving the output, add it as a "received" entry
1678 if (fIsMine & filter)
1679 listReceived.push_back(output);
1684 void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
1685 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
1687 nReceived = nSent = nFee = 0;
1690 string strSentAccount;
1691 list<COutputEntry> listReceived;
1692 list<COutputEntry> listSent;
1693 GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
1695 if (strAccount == strSentAccount)
1697 BOOST_FOREACH(const COutputEntry& s, listSent)
1702 LOCK(pwallet->cs_wallet);
1703 BOOST_FOREACH(const COutputEntry& r, listReceived)
1705 if (pwallet->mapAddressBook.count(r.destination))
1707 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
1708 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
1709 nReceived += r.amount;
1711 else if (strAccount.empty())
1713 nReceived += r.amount;
1720 bool CWalletTx::WriteToDisk(CWalletDB *pwalletdb)
1722 return pwalletdb->WriteTx(GetHash(), *this);
1725 void CWallet::WitnessNoteCommitment(std::vector<uint256> commitments,
1726 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
1727 uint256 &final_anchor)
1729 witnesses.resize(commitments.size());
1730 CBlockIndex* pindex = chainActive.Genesis();
1731 ZCIncrementalMerkleTree tree;
1735 ReadBlockFromDisk(block, pindex);
1737 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1739 BOOST_FOREACH(const JSDescription& jsdesc, tx.vjoinsplit)
1741 BOOST_FOREACH(const uint256 ¬e_commitment, jsdesc.commitments)
1743 tree.append(note_commitment);
1745 BOOST_FOREACH(boost::optional<ZCIncrementalWitness>& wit, witnesses) {
1747 wit->append(note_commitment);
1752 BOOST_FOREACH(uint256& commitment, commitments) {
1753 if (note_commitment == commitment) {
1754 witnesses.at(i) = tree.witness();
1762 uint256 current_anchor = tree.root();
1764 // Consistency check: we should be able to find the current tree
1765 // in our CCoins view.
1766 ZCIncrementalMerkleTree dummy_tree;
1767 assert(pcoinsTip->GetAnchorAt(current_anchor, dummy_tree));
1769 pindex = chainActive.Next(pindex);
1772 // TODO: #93; Select a root via some heuristic.
1773 final_anchor = tree.root();
1775 BOOST_FOREACH(boost::optional<ZCIncrementalWitness>& wit, witnesses) {
1777 assert(final_anchor == wit->root());
1783 * Scan the block chain (starting in pindexStart) for transactions
1784 * from or to us. If fUpdate is true, found transactions that already
1785 * exist in the wallet will be updated.
1787 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1790 int64_t nNow = GetTime();
1791 const CChainParams& chainParams = Params();
1793 CBlockIndex* pindex = pindexStart;
1795 LOCK2(cs_main, cs_wallet);
1797 // no need to read and scan block, if block was created before
1798 // our wallet birthday (as adjusted for block time variability)
1799 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
1800 pindex = chainActive.Next(pindex);
1802 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1803 double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
1804 double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip(), false);
1807 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1808 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1811 ReadBlockFromDisk(block, pindex);
1812 BOOST_FOREACH(CTransaction& tx, block.vtx)
1814 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1818 ZCIncrementalMerkleTree tree;
1819 // This should never fail: we should always be able to get the tree
1820 // state on the path to the tip of our chain
1821 assert(pcoinsTip->GetAnchorAt(pindex->hashAnchor, tree));
1822 // Increment note witness caches
1823 IncrementNoteWitnesses(pindex, &block, tree);
1825 pindex = chainActive.Next(pindex);
1826 if (GetTime() >= nNow + 60) {
1828 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex));
1831 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1836 void CWallet::ReacceptWalletTransactions()
1838 // If transactions aren't being broadcasted, don't let them into local mempool either
1839 if (!fBroadcastTransactions)
1841 LOCK2(cs_main, cs_wallet);
1842 std::map<int64_t, CWalletTx*> mapSorted;
1844 // Sort pending wallet transactions based on their initial wallet insertion order
1845 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1847 const uint256& wtxid = item.first;
1848 CWalletTx& wtx = item.second;
1849 assert(wtx.GetHash() == wtxid);
1851 int nDepth = wtx.GetDepthInMainChain();
1853 if (!wtx.IsCoinBase() && nDepth < 0) {
1854 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1858 // Try to add wallet transactions to memory pool
1859 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1861 CWalletTx& wtx = *(item.second);
1864 wtx.AcceptToMemoryPool(false);
1868 bool CWalletTx::RelayWalletTransaction()
1870 assert(pwallet->GetBroadcastTransactions());
1873 if (GetDepthInMainChain() == 0) {
1874 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1875 RelayTransaction((CTransaction)*this);
1882 set<uint256> CWalletTx::GetConflicts() const
1884 set<uint256> result;
1885 if (pwallet != NULL)
1887 uint256 myHash = GetHash();
1888 result = pwallet->GetConflicts(myHash);
1889 result.erase(myHash);
1894 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1900 if(filter & ISMINE_SPENDABLE)
1903 debit += nDebitCached;
1906 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1907 fDebitCached = true;
1908 debit += nDebitCached;
1911 if(filter & ISMINE_WATCH_ONLY)
1913 if(fWatchDebitCached)
1914 debit += nWatchDebitCached;
1917 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1918 fWatchDebitCached = true;
1919 debit += nWatchDebitCached;
1925 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1927 // Must wait until coinbase is safely deep enough in the chain before valuing it
1928 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1932 if (filter & ISMINE_SPENDABLE)
1934 // GetBalance can assume transactions in mapWallet won't change
1936 credit += nCreditCached;
1939 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1940 fCreditCached = true;
1941 credit += nCreditCached;
1944 if (filter & ISMINE_WATCH_ONLY)
1946 if (fWatchCreditCached)
1947 credit += nWatchCreditCached;
1950 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1951 fWatchCreditCached = true;
1952 credit += nWatchCreditCached;
1958 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1960 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1962 if (fUseCache && fImmatureCreditCached)
1963 return nImmatureCreditCached;
1964 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1965 fImmatureCreditCached = true;
1966 return nImmatureCreditCached;
1972 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1977 // Must wait until coinbase is safely deep enough in the chain before valuing it
1978 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1981 if (fUseCache && fAvailableCreditCached)
1982 return nAvailableCreditCached;
1984 CAmount nCredit = 0;
1985 uint256 hashTx = GetHash();
1986 for (unsigned int i = 0; i < vout.size(); i++)
1988 if (!pwallet->IsSpent(hashTx, i))
1990 const CTxOut &txout = vout[i];
1991 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1992 if (!MoneyRange(nCredit))
1993 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1997 nAvailableCreditCached = nCredit;
1998 fAvailableCreditCached = true;
2002 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
2004 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
2006 if (fUseCache && fImmatureWatchCreditCached)
2007 return nImmatureWatchCreditCached;
2008 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
2009 fImmatureWatchCreditCached = true;
2010 return nImmatureWatchCreditCached;
2016 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
2021 // Must wait until coinbase is safely deep enough in the chain before valuing it
2022 if (IsCoinBase() && GetBlocksToMaturity() > 0)
2025 if (fUseCache && fAvailableWatchCreditCached)
2026 return nAvailableWatchCreditCached;
2028 CAmount nCredit = 0;
2029 for (unsigned int i = 0; i < vout.size(); i++)
2031 if (!pwallet->IsSpent(GetHash(), i))
2033 const CTxOut &txout = vout[i];
2034 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
2035 if (!MoneyRange(nCredit))
2036 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
2040 nAvailableWatchCreditCached = nCredit;
2041 fAvailableWatchCreditCached = true;
2045 CAmount CWalletTx::GetChange() const
2048 return nChangeCached;
2049 nChangeCached = pwallet->GetChange(*this);
2050 fChangeCached = true;
2051 return nChangeCached;
2054 bool CWalletTx::IsTrusted() const
2056 // Quick answer in most cases
2057 if (!CheckFinalTx(*this))
2059 int nDepth = GetDepthInMainChain();
2064 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
2067 // Trusted if all inputs are from us and are in the mempool:
2068 BOOST_FOREACH(const CTxIn& txin, vin)
2070 // Transactions not sent by us: not trusted
2071 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
2074 const CTxOut& parentOut = parent->vout[txin.prevout.n];
2075 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
2081 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
2083 std::vector<uint256> result;
2086 // Sort them in chronological order
2087 multimap<unsigned int, CWalletTx*> mapSorted;
2088 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
2090 CWalletTx& wtx = item.second;
2091 // Don't rebroadcast if newer than nTime:
2092 if (wtx.nTimeReceived > nTime)
2094 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
2096 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
2098 CWalletTx& wtx = *item.second;
2099 if (wtx.RelayWalletTransaction())
2100 result.push_back(wtx.GetHash());
2105 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
2107 // Do this infrequently and randomly to avoid giving away
2108 // that these are our transactions.
2109 if (GetTime() < nNextResend || !fBroadcastTransactions)
2111 bool fFirst = (nNextResend == 0);
2112 nNextResend = GetTime() + GetRand(30 * 60);
2116 // Only do it if there's been a new block since last time
2117 if (nBestBlockTime < nLastResend)
2119 nLastResend = GetTime();
2121 // Rebroadcast unconfirmed txes older than 5 minutes before the last
2123 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60);
2124 if (!relayed.empty())
2125 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
2128 /** @} */ // end of mapWallet
2133 /** @defgroup Actions
2139 CAmount CWallet::GetBalance() const
2143 LOCK2(cs_main, cs_wallet);
2144 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2146 const CWalletTx* pcoin = &(*it).second;
2147 if (pcoin->IsTrusted())
2148 nTotal += pcoin->GetAvailableCredit();
2155 CAmount CWallet::GetUnconfirmedBalance() const
2159 LOCK2(cs_main, cs_wallet);
2160 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2162 const CWalletTx* pcoin = &(*it).second;
2163 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
2164 nTotal += pcoin->GetAvailableCredit();
2170 CAmount CWallet::GetImmatureBalance() const
2174 LOCK2(cs_main, cs_wallet);
2175 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2177 const CWalletTx* pcoin = &(*it).second;
2178 nTotal += pcoin->GetImmatureCredit();
2184 CAmount CWallet::GetWatchOnlyBalance() const
2188 LOCK2(cs_main, cs_wallet);
2189 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2191 const CWalletTx* pcoin = &(*it).second;
2192 if (pcoin->IsTrusted())
2193 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2200 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2204 LOCK2(cs_main, cs_wallet);
2205 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2207 const CWalletTx* pcoin = &(*it).second;
2208 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
2209 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2215 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2219 LOCK2(cs_main, cs_wallet);
2220 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2222 const CWalletTx* pcoin = &(*it).second;
2223 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2230 * populate vCoins with vector of available COutputs.
2232 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue, bool fIncludeCoinBase) const
2237 LOCK2(cs_main, cs_wallet);
2238 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2240 const uint256& wtxid = it->first;
2241 const CWalletTx* pcoin = &(*it).second;
2243 if (!CheckFinalTx(*pcoin))
2246 if (fOnlyConfirmed && !pcoin->IsTrusted())
2249 if (pcoin->IsCoinBase() && !fIncludeCoinBase)
2252 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2255 int nDepth = pcoin->GetDepthInMainChain();
2259 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
2260 isminetype mine = IsMine(pcoin->vout[i]);
2261 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
2262 !IsLockedCoin((*it).first, i) && (pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
2263 (!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected((*it).first, i)))
2264 vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO));
2270 static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2271 vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2273 vector<char> vfIncluded;
2275 vfBest.assign(vValue.size(), true);
2276 nBest = nTotalLower;
2278 seed_insecure_rand();
2280 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2282 vfIncluded.assign(vValue.size(), false);
2284 bool fReachedTarget = false;
2285 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2287 for (unsigned int i = 0; i < vValue.size(); i++)
2289 //The solver here uses a randomized algorithm,
2290 //the randomness serves no real security purpose but is just
2291 //needed to prevent degenerate behavior and it is important
2292 //that the rng is fast. We do not use a constant random sequence,
2293 //because there may be some privacy improvement by making
2294 //the selection random.
2295 if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
2297 nTotal += vValue[i].first;
2298 vfIncluded[i] = true;
2299 if (nTotal >= nTargetValue)
2301 fReachedTarget = true;
2305 vfBest = vfIncluded;
2307 nTotal -= vValue[i].first;
2308 vfIncluded[i] = false;
2316 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
2317 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
2319 setCoinsRet.clear();
2322 // List of values less than target
2323 pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
2324 coinLowestLarger.first = std::numeric_limits<CAmount>::max();
2325 coinLowestLarger.second.first = NULL;
2326 vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
2327 CAmount nTotalLower = 0;
2329 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2331 BOOST_FOREACH(const COutput &output, vCoins)
2333 if (!output.fSpendable)
2336 const CWalletTx *pcoin = output.tx;
2338 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2342 CAmount n = pcoin->vout[i].nValue;
2344 pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
2346 if (n == nTargetValue)
2348 setCoinsRet.insert(coin.second);
2349 nValueRet += coin.first;
2352 else if (n < nTargetValue + CENT)
2354 vValue.push_back(coin);
2357 else if (n < coinLowestLarger.first)
2359 coinLowestLarger = coin;
2363 if (nTotalLower == nTargetValue)
2365 for (unsigned int i = 0; i < vValue.size(); ++i)
2367 setCoinsRet.insert(vValue[i].second);
2368 nValueRet += vValue[i].first;
2373 if (nTotalLower < nTargetValue)
2375 if (coinLowestLarger.second.first == NULL)
2377 setCoinsRet.insert(coinLowestLarger.second);
2378 nValueRet += coinLowestLarger.first;
2382 // Solve subset sum by stochastic approximation
2383 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
2384 vector<char> vfBest;
2387 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
2388 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
2389 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
2391 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2392 // or the next bigger coin is closer), return the bigger coin
2393 if (coinLowestLarger.second.first &&
2394 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
2396 setCoinsRet.insert(coinLowestLarger.second);
2397 nValueRet += coinLowestLarger.first;
2400 for (unsigned int i = 0; i < vValue.size(); i++)
2403 setCoinsRet.insert(vValue[i].second);
2404 nValueRet += vValue[i].first;
2407 LogPrint("selectcoins", "SelectCoins() best subset: ");
2408 for (unsigned int i = 0; i < vValue.size(); i++)
2410 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
2411 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
2417 bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, bool& fOnlyCoinbaseCoinsRet, bool& fNeedCoinbaseCoinsRet, const CCoinControl* coinControl) const
2419 // Output parameter fOnlyCoinbaseCoinsRet is set to true when the only available coins are coinbase utxos.
2420 vector<COutput> vCoinsNoCoinbase, vCoinsWithCoinbase;
2421 AvailableCoins(vCoinsNoCoinbase, true, coinControl, false, false);
2422 AvailableCoins(vCoinsWithCoinbase, true, coinControl, false, true);
2423 fOnlyCoinbaseCoinsRet = vCoinsNoCoinbase.size() == 0 && vCoinsWithCoinbase.size() > 0;
2425 // If coinbase utxos can only be sent to zaddrs, exclude any coinbase utxos from coin selection.
2426 bool fProtectCoinbase = Params().GetConsensus().fCoinbaseMustBeProtected;
2427 vector<COutput> vCoins = (fProtectCoinbase) ? vCoinsNoCoinbase : vCoinsWithCoinbase;
2429 // Output parameter fNeedCoinbaseCoinsRet is set to true if coinbase utxos need to be spent to meet target amount
2430 if (fProtectCoinbase && vCoinsWithCoinbase.size() > vCoinsNoCoinbase.size()) {
2432 for (const COutput& out : vCoinsNoCoinbase) {
2433 if (!out.fSpendable) {
2436 value += out.tx->vout[out.i].nValue;
2438 if (value <= nTargetValue) {
2439 CAmount valueWithCoinbase = 0;
2440 for (const COutput& out : vCoinsWithCoinbase) {
2441 if (!out.fSpendable) {
2444 valueWithCoinbase += out.tx->vout[out.i].nValue;
2446 fNeedCoinbaseCoinsRet = (valueWithCoinbase >= nTargetValue);
2450 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2451 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2453 BOOST_FOREACH(const COutput& out, vCoins)
2455 if (!out.fSpendable)
2457 nValueRet += out.tx->vout[out.i].nValue;
2458 setCoinsRet.insert(make_pair(out.tx, out.i));
2460 return (nValueRet >= nTargetValue);
2463 // calculate value from preset inputs and store them
2464 set<pair<const CWalletTx*, uint32_t> > setPresetCoins;
2465 CAmount nValueFromPresetInputs = 0;
2467 std::vector<COutPoint> vPresetInputs;
2469 coinControl->ListSelected(vPresetInputs);
2470 BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
2472 map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2473 if (it != mapWallet.end())
2475 const CWalletTx* pcoin = &it->second;
2476 // Clearly invalid input, fail
2477 if (pcoin->vout.size() <= outpoint.n)
2479 nValueFromPresetInputs += pcoin->vout[outpoint.n].nValue;
2480 setPresetCoins.insert(make_pair(pcoin, outpoint.n));
2482 return false; // TODO: Allow non-wallet inputs
2485 // remove preset inputs from vCoins
2486 for (vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2488 if (setPresetCoins.count(make_pair(it->tx, it->i)))
2489 it = vCoins.erase(it);
2494 bool res = nTargetValue <= nValueFromPresetInputs ||
2495 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, vCoins, setCoinsRet, nValueRet) ||
2496 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, vCoins, setCoinsRet, nValueRet) ||
2497 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, vCoins, setCoinsRet, nValueRet));
2499 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2500 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2502 // add preset inputs to the total value selected
2503 nValueRet += nValueFromPresetInputs;
2508 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount &nFeeRet, int& nChangePosRet, std::string& strFailReason)
2510 vector<CRecipient> vecSend;
2512 // Turn the txout set into a CRecipient vector
2513 BOOST_FOREACH(const CTxOut& txOut, tx.vout)
2515 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, false};
2516 vecSend.push_back(recipient);
2519 CCoinControl coinControl;
2520 coinControl.fAllowOtherInputs = true;
2521 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2522 coinControl.Select(txin.prevout);
2524 CReserveKey reservekey(this);
2526 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosRet, strFailReason, &coinControl, false))
2529 if (nChangePosRet != -1)
2530 tx.vout.insert(tx.vout.begin() + nChangePosRet, wtx.vout[nChangePosRet]);
2532 // Add new txins (keeping original txin scriptSig/order)
2533 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
2536 BOOST_FOREACH(const CTxIn& origTxIn, tx.vin)
2538 if (txin.prevout.hash == origTxIn.prevout.hash && txin.prevout.n == origTxIn.prevout.n)
2545 tx.vin.push_back(txin);
2551 bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2552 int& nChangePosRet, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
2555 unsigned int nSubtractFeeFromAmount = 0;
2556 BOOST_FOREACH (const CRecipient& recipient, vecSend)
2558 if (nValue < 0 || recipient.nAmount < 0)
2560 strFailReason = _("Transaction amounts must be positive");
2563 nValue += recipient.nAmount;
2565 if (recipient.fSubtractFeeFromAmount)
2566 nSubtractFeeFromAmount++;
2568 if (vecSend.empty() || nValue < 0)
2570 strFailReason = _("Transaction amounts must be positive");
2574 wtxNew.fTimeReceivedIsTxTime = true;
2575 wtxNew.BindWallet(this);
2576 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(
2577 Params().GetConsensus(), chainActive.Height() + 1);
2579 // Discourage fee sniping.
2581 // However because of a off-by-one-error in previous versions we need to
2582 // neuter it by setting nLockTime to at least one less than nBestHeight.
2583 // Secondly currently propagation of transactions created for block heights
2584 // corresponding to blocks that were just mined may be iffy - transactions
2585 // aren't re-accepted into the mempool - we additionally neuter the code by
2586 // going ten blocks back. Doesn't yet do anything for sniping, but does act
2587 // to shake out wallet bugs like not showing nLockTime'd transactions at
2589 txNew.nLockTime = std::max(0, chainActive.Height() - 10);
2591 // Secondly occasionally randomly pick a nLockTime even further back, so
2592 // that transactions that are delayed after signing for whatever reason,
2593 // e.g. high-latency mix networks and some CoinJoin implementations, have
2595 if (GetRandInt(10) == 0)
2596 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2598 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2599 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2602 LOCK2(cs_main, cs_wallet);
2609 wtxNew.fFromMe = true;
2613 CAmount nTotalValue = nValue;
2614 if (nSubtractFeeFromAmount == 0)
2615 nTotalValue += nFeeRet;
2616 double dPriority = 0;
2617 // vouts to the payees
2618 BOOST_FOREACH (const CRecipient& recipient, vecSend)
2620 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2622 if (recipient.fSubtractFeeFromAmount)
2624 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2626 if (fFirst) // first receiver pays the remainder not divisible by output count
2629 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2633 if (txout.IsDust(::minRelayTxFee))
2635 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2637 if (txout.nValue < 0)
2638 strFailReason = _("The transaction amount is too small to pay the fee");
2640 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2643 strFailReason = _("Transaction amount too small");
2646 txNew.vout.push_back(txout);
2649 // Choose coins to use
2650 set<pair<const CWalletTx*,unsigned int> > setCoins;
2651 CAmount nValueIn = 0;
2652 bool fOnlyCoinbaseCoins = false;
2653 bool fNeedCoinbaseCoins = false;
2654 if (!SelectCoins(nTotalValue, setCoins, nValueIn, fOnlyCoinbaseCoins, fNeedCoinbaseCoins, coinControl))
2656 if (fOnlyCoinbaseCoins && Params().GetConsensus().fCoinbaseMustBeProtected) {
2657 strFailReason = _("Coinbase funds can only be sent to a zaddr");
2658 } else if (fNeedCoinbaseCoins) {
2659 strFailReason = _("Insufficient funds, coinbase funds can only be spent after they have been sent to a zaddr");
2661 strFailReason = _("Insufficient funds");
2665 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
2667 CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
2668 //The coin age after the next block (depth+1) is used instead of the current,
2669 //reflecting an assumption the user would accept a bit more delay for
2670 //a chance at a free transaction.
2671 //But mempool inputs might still be in the mempool, so their age stays 0
2672 int age = pcoin.first->GetDepthInMainChain();
2675 dPriority += (double)nCredit * age;
2678 CAmount nChange = nValueIn - nValue;
2679 if (nSubtractFeeFromAmount == 0)
2684 // Fill a vout to ourself
2685 // TODO: pass in scriptChange instead of reservekey so
2686 // change transaction isn't always pay-to-bitcoin-address
2687 CScript scriptChange;
2689 // coin control: send change to custom address
2690 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
2691 scriptChange = GetScriptForDestination(coinControl->destChange);
2693 // no coin control: send change to newly generated address
2696 // Note: We use a new key here to keep it from being obvious which side is the change.
2697 // The drawback is that by not reusing a previous key, the change may be lost if a
2698 // backup is restored, if the backup doesn't have the new private key for the change.
2699 // If we reused the old key, it would be possible to add code to look for and
2700 // rediscover unknown transactions that were written with keys of ours to recover
2701 // post-backup change.
2703 // Reserve a new key pair from key pool
2706 ret = reservekey.GetReservedKey(vchPubKey);
2707 assert(ret); // should never fail, as we just unlocked
2709 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2712 CTxOut newTxOut(nChange, scriptChange);
2714 // We do not move dust-change to fees, because the sender would end up paying more than requested.
2715 // This would be against the purpose of the all-inclusive feature.
2716 // So instead we raise the change and deduct from the recipient.
2717 if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust(::minRelayTxFee))
2719 CAmount nDust = newTxOut.GetDustThreshold(::minRelayTxFee) - newTxOut.nValue;
2720 newTxOut.nValue += nDust; // raise change until no more dust
2721 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
2723 if (vecSend[i].fSubtractFeeFromAmount)
2725 txNew.vout[i].nValue -= nDust;
2726 if (txNew.vout[i].IsDust(::minRelayTxFee))
2728 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2736 // Never create dust outputs; if we would, just
2737 // add the dust to the fee.
2738 if (newTxOut.IsDust(::minRelayTxFee))
2741 reservekey.ReturnKey();
2745 // Insert change txn at random position:
2746 nChangePosRet = GetRandInt(txNew.vout.size()+1);
2747 vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosRet;
2748 txNew.vout.insert(position, newTxOut);
2752 reservekey.ReturnKey();
2756 // Note how the sequence number is set to max()-1 so that the
2757 // nLockTime set above actually works.
2758 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2759 txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
2760 std::numeric_limits<unsigned int>::max()-1));
2762 // Check mempooltxinputlimit to avoid creating a transaction which the local mempool rejects
2763 size_t limit = (size_t)GetArg("-mempooltxinputlimit", 0);
2765 size_t n = txNew.vin.size();
2767 strFailReason = _(strprintf("Too many transparent inputs %zu > limit %zu", n, limit).c_str());
2772 // Grab the current consensus branch ID
2773 auto consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus());
2777 CTransaction txNewConst(txNew);
2778 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2781 const CScript& scriptPubKey = coin.first->vout[coin.second].scriptPubKey;
2782 SignatureData sigdata;
2784 signSuccess = ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.first->vout[coin.second].nValue, SIGHASH_ALL), scriptPubKey, sigdata, consensusBranchId);
2786 signSuccess = ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata, consensusBranchId);
2790 strFailReason = _("Signing transaction failed");
2793 UpdateTransaction(txNew, nIn, sigdata);
2799 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2801 // Remove scriptSigs if we used dummy signatures for fee calculation
2803 BOOST_FOREACH (CTxIn& vin, txNew.vin)
2804 vin.scriptSig = CScript();
2807 // Embed the constructed transaction data in wtxNew.
2808 *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
2811 if (nBytes >= MAX_TX_SIZE)
2813 strFailReason = _("Transaction too large");
2817 dPriority = wtxNew.ComputePriority(dPriority, nBytes);
2819 // Can we complete this as a free transaction?
2820 if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
2822 // Not enough fee: enough priority?
2823 double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
2824 // Not enough mempool history to estimate: use hard-coded AllowFree.
2825 if (dPriorityNeeded <= 0 && AllowFree(dPriority))
2828 // Small enough, and priority high enough, to send for free
2829 if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
2833 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
2835 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2836 // because we must be at the maximum allowed fee.
2837 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2839 strFailReason = _("Transaction too large for fee policy");
2843 if (nFeeRet >= nFeeNeeded)
2844 break; // Done, enough fee included.
2846 // Include more fee and try again.
2847 nFeeRet = nFeeNeeded;
2857 * Call after CreateTransaction unless you want to abort
2859 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2862 LOCK2(cs_main, cs_wallet);
2863 LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
2865 // This is only to keep the database open to defeat the auto-flush for the
2866 // duration of this scope. This is the only place where this optimization
2867 // maybe makes sense; please don't do it anywhere else.
2868 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r+") : NULL;
2870 // Take key pair from key pool so it won't be used again
2871 reservekey.KeepKey();
2873 // Add tx to wallet, because if it has change it's also ours,
2874 // otherwise just for transaction history.
2875 AddToWallet(wtxNew, false, pwalletdb);
2877 // Notify that old coins are spent
2878 set<CWalletTx*> setCoins;
2879 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2881 CWalletTx &coin = mapWallet[txin.prevout.hash];
2882 coin.BindWallet(this);
2883 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2890 // Track how many getdata requests our transaction gets
2891 mapRequestCount[wtxNew.GetHash()] = 0;
2893 if (fBroadcastTransactions)
2896 if (!wtxNew.AcceptToMemoryPool(false))
2898 // This must not fail. The transaction has already been signed and recorded.
2899 LogPrintf("CommitTransaction(): Error: Transaction not valid\n");
2902 wtxNew.RelayWalletTransaction();
2908 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
2910 // payTxFee is user-set "I want to pay this much"
2911 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
2912 // user selected total at least (default=true)
2913 if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
2914 nFeeNeeded = payTxFee.GetFeePerK();
2915 // User didn't set: use -txconfirmtarget to estimate...
2916 if (nFeeNeeded == 0)
2917 nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
2918 // ... unless we don't have enough mempool data, in which case fall
2919 // back to a hard-coded fee
2920 if (nFeeNeeded == 0)
2921 nFeeNeeded = minTxFee.GetFee(nTxBytes);
2922 // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
2923 if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
2924 nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
2925 // But always obey the maximum
2926 if (nFeeNeeded > maxTxFee)
2927 nFeeNeeded = maxTxFee;
2934 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2938 fFirstRunRet = false;
2939 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2940 if (nLoadWalletRet == DB_NEED_REWRITE)
2942 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2946 // Note: can't top-up keypool here, because wallet is locked.
2947 // User will be prompted to unlock wallet the next operation
2948 // that requires a new key.
2952 if (nLoadWalletRet != DB_LOAD_OK)
2953 return nLoadWalletRet;
2954 fFirstRunRet = !vchDefaultKey.IsValid();
2956 uiInterface.LoadWallet(this);
2962 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
2966 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
2967 if (nZapWalletTxRet == DB_NEED_REWRITE)
2969 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2973 // Note: can't top-up keypool here, because wallet is locked.
2974 // User will be prompted to unlock wallet the next operation
2975 // that requires a new key.
2979 if (nZapWalletTxRet != DB_LOAD_OK)
2980 return nZapWalletTxRet;
2986 bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
2988 bool fUpdated = false;
2990 LOCK(cs_wallet); // mapAddressBook
2991 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
2992 fUpdated = mi != mapAddressBook.end();
2993 mapAddressBook[address].name = strName;
2994 if (!strPurpose.empty()) /* update purpose only if requested */
2995 mapAddressBook[address].purpose = strPurpose;
2997 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
2998 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3001 if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
3003 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
3006 bool CWallet::DelAddressBook(const CTxDestination& address)
3009 LOCK(cs_wallet); // mapAddressBook
3013 // Delete destdata tuples associated with address
3014 std::string strAddress = CBitcoinAddress(address).ToString();
3015 BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
3017 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
3020 mapAddressBook.erase(address);
3023 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3027 CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
3028 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
3031 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3035 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
3038 vchDefaultKey = vchPubKey;
3043 * Mark old keypool keys as used,
3044 * and generate all new keys
3046 bool CWallet::NewKeyPool()
3050 CWalletDB walletdb(strWalletFile);
3051 BOOST_FOREACH(int64_t nIndex, setKeyPool)
3052 walletdb.ErasePool(nIndex);
3058 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
3059 for (int i = 0; i < nKeys; i++)
3061 int64_t nIndex = i+1;
3062 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
3063 setKeyPool.insert(nIndex);
3065 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
3070 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3078 CWalletDB walletdb(strWalletFile);
3081 unsigned int nTargetSize;
3083 nTargetSize = kpSize;
3085 nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0);
3087 while (setKeyPool.size() < (nTargetSize + 1))
3090 if (!setKeyPool.empty())
3091 nEnd = *(--setKeyPool.end()) + 1;
3092 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
3093 throw runtime_error("TopUpKeyPool(): writing generated key failed");
3094 setKeyPool.insert(nEnd);
3095 LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
3101 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
3104 keypool.vchPubKey = CPubKey();
3111 // Get the oldest key
3112 if(setKeyPool.empty())
3115 CWalletDB walletdb(strWalletFile);
3117 nIndex = *(setKeyPool.begin());
3118 setKeyPool.erase(setKeyPool.begin());
3119 if (!walletdb.ReadPool(nIndex, keypool))
3120 throw runtime_error("ReserveKeyFromKeyPool(): read failed");
3121 if (!HaveKey(keypool.vchPubKey.GetID()))
3122 throw runtime_error("ReserveKeyFromKeyPool(): unknown key in key pool");
3123 assert(keypool.vchPubKey.IsValid());
3124 LogPrintf("keypool reserve %d\n", nIndex);
3128 void CWallet::KeepKey(int64_t nIndex)
3130 // Remove from key pool
3133 CWalletDB walletdb(strWalletFile);
3134 walletdb.ErasePool(nIndex);
3136 LogPrintf("keypool keep %d\n", nIndex);
3139 void CWallet::ReturnKey(int64_t nIndex)
3141 // Return to key pool
3144 setKeyPool.insert(nIndex);
3146 LogPrintf("keypool return %d\n", nIndex);
3149 bool CWallet::GetKeyFromPool(CPubKey& result)
3155 ReserveKeyFromKeyPool(nIndex, keypool);
3158 if (IsLocked()) return false;
3159 result = GenerateNewKey();
3163 result = keypool.vchPubKey;
3168 int64_t CWallet::GetOldestKeyPoolTime()
3172 ReserveKeyFromKeyPool(nIndex, keypool);
3176 return keypool.nTime;
3179 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3181 map<CTxDestination, CAmount> balances;
3185 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3187 CWalletTx *pcoin = &walletEntry.second;
3189 if (!CheckFinalTx(*pcoin) || !pcoin->IsTrusted())
3192 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3195 int nDepth = pcoin->GetDepthInMainChain();
3196 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3199 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
3201 CTxDestination addr;
3202 if (!IsMine(pcoin->vout[i]))
3204 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
3207 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
3209 if (!balances.count(addr))
3211 balances[addr] += n;
3219 set< set<CTxDestination> > CWallet::GetAddressGroupings()
3221 AssertLockHeld(cs_wallet); // mapWallet
3222 set< set<CTxDestination> > groupings;
3223 set<CTxDestination> grouping;
3225 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3227 CWalletTx *pcoin = &walletEntry.second;
3229 if (pcoin->vin.size() > 0)
3231 bool any_mine = false;
3232 // group all input addresses with each other
3233 BOOST_FOREACH(CTxIn txin, pcoin->vin)
3235 CTxDestination address;
3236 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3238 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
3240 grouping.insert(address);
3244 // group change with input addresses
3247 BOOST_FOREACH(CTxOut txout, pcoin->vout)
3248 if (IsChange(txout))
3250 CTxDestination txoutAddr;
3251 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3253 grouping.insert(txoutAddr);
3256 if (grouping.size() > 0)
3258 groupings.insert(grouping);
3263 // group lone addrs by themselves
3264 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
3265 if (IsMine(pcoin->vout[i]))
3267 CTxDestination address;
3268 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
3270 grouping.insert(address);
3271 groupings.insert(grouping);
3276 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3277 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3278 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
3280 // make a set of all the groups hit by this new group
3281 set< set<CTxDestination>* > hits;
3282 map< CTxDestination, set<CTxDestination>* >::iterator it;
3283 BOOST_FOREACH(CTxDestination address, grouping)
3284 if ((it = setmap.find(address)) != setmap.end())
3285 hits.insert((*it).second);
3287 // merge all hit groups into a new single group and delete old groups
3288 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
3289 BOOST_FOREACH(set<CTxDestination>* hit, hits)
3291 merged->insert(hit->begin(), hit->end());
3292 uniqueGroupings.erase(hit);
3295 uniqueGroupings.insert(merged);
3298 BOOST_FOREACH(CTxDestination element, *merged)
3299 setmap[element] = merged;
3302 set< set<CTxDestination> > ret;
3303 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
3305 ret.insert(*uniqueGrouping);
3306 delete uniqueGrouping;
3312 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3315 set<CTxDestination> result;
3316 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
3318 const CTxDestination& address = item.first;
3319 const string& strName = item.second.name;
3320 if (strName == strAccount)
3321 result.insert(address);
3326 bool CReserveKey::GetReservedKey(CPubKey& pubkey)
3331 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
3333 vchPubKey = keypool.vchPubKey;
3338 assert(vchPubKey.IsValid());
3343 void CReserveKey::KeepKey()
3346 pwallet->KeepKey(nIndex);
3348 vchPubKey = CPubKey();
3351 void CReserveKey::ReturnKey()
3354 pwallet->ReturnKey(nIndex);
3356 vchPubKey = CPubKey();
3359 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
3363 CWalletDB walletdb(strWalletFile);
3365 LOCK2(cs_main, cs_wallet);
3366 BOOST_FOREACH(const int64_t& id, setKeyPool)
3369 if (!walletdb.ReadPool(id, keypool))
3370 throw runtime_error("GetAllReserveKeyHashes(): read failed");
3371 assert(keypool.vchPubKey.IsValid());
3372 CKeyID keyID = keypool.vchPubKey.GetID();
3373 if (!HaveKey(keyID))
3374 throw runtime_error("GetAllReserveKeyHashes(): unknown key in key pool");
3375 setAddress.insert(keyID);
3379 void CWallet::UpdatedTransaction(const uint256 &hashTx)
3383 // Only notify UI if this transaction is in this wallet
3384 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
3385 if (mi != mapWallet.end())
3386 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
3390 void CWallet::LockCoin(COutPoint& output)
3392 AssertLockHeld(cs_wallet); // setLockedCoins
3393 setLockedCoins.insert(output);
3396 void CWallet::UnlockCoin(COutPoint& output)
3398 AssertLockHeld(cs_wallet); // setLockedCoins
3399 setLockedCoins.erase(output);
3402 void CWallet::UnlockAllCoins()
3404 AssertLockHeld(cs_wallet); // setLockedCoins
3405 setLockedCoins.clear();
3408 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3410 AssertLockHeld(cs_wallet); // setLockedCoins
3411 COutPoint outpt(hash, n);
3413 return (setLockedCoins.count(outpt) > 0);
3416 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
3418 AssertLockHeld(cs_wallet); // setLockedCoins
3419 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3420 it != setLockedCoins.end(); it++) {
3421 COutPoint outpt = (*it);
3422 vOutpts.push_back(outpt);
3426 /** @} */ // end of Actions
3428 class CAffectedKeysVisitor : public boost::static_visitor<void> {
3430 const CKeyStore &keystore;
3431 std::vector<CKeyID> &vKeys;
3434 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
3436 void Process(const CScript &script) {
3438 std::vector<CTxDestination> vDest;
3440 if (ExtractDestinations(script, type, vDest, nRequired)) {
3441 BOOST_FOREACH(const CTxDestination &dest, vDest)
3442 boost::apply_visitor(*this, dest);
3446 void operator()(const CKeyID &keyId) {
3447 if (keystore.HaveKey(keyId))
3448 vKeys.push_back(keyId);
3451 void operator()(const CScriptID &scriptId) {
3453 if (keystore.GetCScript(scriptId, script))
3457 void operator()(const CNoDestination &none) {}
3460 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
3461 AssertLockHeld(cs_wallet); // mapKeyMetadata
3462 mapKeyBirth.clear();
3464 // get birth times for keys with metadata
3465 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
3466 if (it->second.nCreateTime)
3467 mapKeyBirth[it->first] = it->second.nCreateTime;
3469 // map in which we'll infer heights of other keys
3470 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
3471 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3472 std::set<CKeyID> setKeys;
3474 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
3475 if (mapKeyBirth.count(keyid) == 0)
3476 mapKeyFirstBlock[keyid] = pindexMax;
3480 // if there are no such keys, we're done
3481 if (mapKeyFirstBlock.empty())
3484 // find first block that affects those keys, if there are any left
3485 std::vector<CKeyID> vAffected;
3486 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3487 // iterate over all wallet transactions...
3488 const CWalletTx &wtx = (*it).second;
3489 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3490 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3491 // ... which are already in a block
3492 int nHeight = blit->second->nHeight;
3493 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
3494 // iterate over all their outputs
3495 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3496 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
3497 // ... and all their affected keys
3498 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3499 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3500 rit->second = blit->second;
3507 // Extract block timestamps for those keys
3508 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3509 mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
3512 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3514 if (boost::get<CNoDestination>(&dest))
3517 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3520 return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3523 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3525 if (!mapAddressBook[dest].destdata.erase(key))
3529 return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3532 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3534 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3538 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3540 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3541 if(i != mapAddressBook.end())
3543 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3544 if(j != i->second.destdata.end())
3554 CKeyPool::CKeyPool()
3559 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
3562 vchPubKey = vchPubKeyIn;
3565 CWalletKey::CWalletKey(int64_t nExpires)
3567 nTimeCreated = (nExpires ? GetTime() : 0);
3568 nTimeExpires = nExpires;
3571 int CMerkleTx::SetMerkleBranch(const CBlock& block)
3573 AssertLockHeld(cs_main);
3576 // Update the tx's hashBlock
3577 hashBlock = block.GetHash();
3579 // Locate the transaction
3580 for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
3581 if (block.vtx[nIndex] == *(CTransaction*)this)
3583 if (nIndex == (int)block.vtx.size())
3585 vMerkleBranch.clear();
3587 LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
3591 // Fill in merkle branch
3592 vMerkleBranch = block.GetMerkleBranch(nIndex);
3594 // Is the tx in a block that's in the main chain
3595 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
3596 if (mi == mapBlockIndex.end())
3598 const CBlockIndex* pindex = (*mi).second;
3599 if (!pindex || !chainActive.Contains(pindex))
3602 return chainActive.Height() - pindex->nHeight + 1;
3605 int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const
3607 if (hashBlock.IsNull() || nIndex == -1)
3609 AssertLockHeld(cs_main);
3611 // Find the block it claims to be in
3612 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
3613 if (mi == mapBlockIndex.end())
3615 CBlockIndex* pindex = (*mi).second;
3616 if (!pindex || !chainActive.Contains(pindex))
3619 // Make sure the merkle branch connects to this block
3620 if (!fMerkleVerified)
3622 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
3624 fMerkleVerified = true;
3628 return chainActive.Height() - pindex->nHeight + 1;
3631 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
3633 AssertLockHeld(cs_main);
3634 int nResult = GetDepthInMainChainINTERNAL(pindexRet);
3635 if (nResult == 0 && !mempool.exists(GetHash()))
3636 return -1; // Not in chain, not in mempool
3641 int CMerkleTx::GetBlocksToMaturity() const
3645 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
3649 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectAbsurdFee)
3651 CValidationState state;
3652 return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectAbsurdFee);
3656 * Find notes in the wallet filtered by payment address, min depth and ability to spend.
3657 * These notes are decrypted and added to the output parameter vector, outEntries.
3659 void CWallet::GetFilteredNotes(std::vector<CNotePlaintextEntry> & outEntries, std::string address, int minDepth, bool ignoreSpent, bool ignoreUnspendable)
3661 bool fFilterAddress = false;
3662 libzcash::PaymentAddress filterPaymentAddress;
3663 if (address.length() > 0) {
3664 filterPaymentAddress = CZCPaymentAddress(address).Get();
3665 fFilterAddress = true;
3668 LOCK2(cs_main, cs_wallet);
3670 for (auto & p : mapWallet) {
3671 CWalletTx wtx = p.second;
3673 // Filter the transactions before checking for notes
3674 if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < minDepth) {
3678 if (wtx.mapNoteData.size() == 0) {
3682 for (auto & pair : wtx.mapNoteData) {
3683 JSOutPoint jsop = pair.first;
3684 CNoteData nd = pair.second;
3685 PaymentAddress pa = nd.address;
3687 // skip notes which belong to a different payment address in the wallet
3688 if (fFilterAddress && !(pa == filterPaymentAddress)) {
3692 // skip note which has been spent
3693 if (ignoreSpent && nd.nullifier && IsSpent(*nd.nullifier)) {
3697 // skip notes which cannot be spent
3698 if (ignoreUnspendable && !HaveSpendingKey(pa)) {
3702 int i = jsop.js; // Index into CTransaction.vjoinsplit
3703 int j = jsop.n; // Index into JSDescription.ciphertexts
3705 // Get cached decryptor
3706 ZCNoteDecryption decryptor;
3707 if (!GetNoteDecryptor(pa, decryptor)) {
3708 // Note decryptors are created when the wallet is loaded, so it should always exist
3709 throw std::runtime_error(strprintf("Could not find note decryptor for payment address %s", CZCPaymentAddress(pa).ToString()));
3712 // determine amount of funds in the note
3713 auto hSig = wtx.vjoinsplit[i].h_sig(*pzcashParams, wtx.joinSplitPubKey);
3715 NotePlaintext plaintext = NotePlaintext::decrypt(
3717 wtx.vjoinsplit[i].ciphertexts[j],
3718 wtx.vjoinsplit[i].ephemeralKey,
3722 outEntries.push_back(CNotePlaintextEntry{jsop, plaintext});
3724 } catch (const note_decryption_failed &err) {
3725 // Couldn't decrypt with this spending key
3726 throw std::runtime_error(strprintf("Could not decrypt note for payment address %s", CZCPaymentAddress(pa).ToString()));
3727 } catch (const std::exception &exc) {
3728 // Unexpected failure
3729 throw std::runtime_error(strprintf("Error while decrypting note for payment address %s: %s", CZCPaymentAddress(pa).ToString(), exc.what()));