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 https://www.opensource.org/licenses/mit-license.php .
6 #include "wallet/wallet.h"
8 #include "asyncrpcqueue.h"
9 #include "checkpoints.h"
10 #include "coincontrol.h"
12 #include "consensus/upgrades.h"
13 #include "consensus/validation.h"
14 #include "consensus/consensus.h"
19 #include "rpc/protocol.h"
20 #include "rpc/server.h"
21 #include "script/script.h"
22 #include "script/sign.h"
24 #include "utilmoneystr.h"
25 #include "zcash/Note.hpp"
27 #include "wallet/asyncrpcoperation_saplingmigration.h"
28 #include "zcash/zip32.h"
32 #include <boost/algorithm/string/replace.hpp>
33 #include <boost/filesystem.hpp>
34 #include <boost/thread.hpp>
37 using namespace libzcash;
42 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
43 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
44 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
45 bool bSpendZeroConfChange = true;
46 bool fSendFreeTransactions = false;
47 bool fPayAtLeastCustomFee = true;
50 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
51 * Override with -mintxfee
53 CFeeRate CWallet::minTxFee = CFeeRate(1000);
55 /** @defgroup mapWallet
60 struct CompareValueOnly
62 bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
63 const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
65 return t1.first < t2.first;
69 std::string JSOutPoint::ToString() const
71 return strprintf("JSOutPoint(%s, %d, %d)", hash.ToString().substr(0,10), js, n);
74 std::string COutput::ToString() const
76 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
79 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
82 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
83 if (it == mapWallet.end())
88 // Generate a new spending key and return its public payment address
89 libzcash::SproutPaymentAddress CWallet::GenerateNewSproutZKey()
91 AssertLockHeld(cs_wallet); // mapSproutZKeyMetadata
93 auto k = SproutSpendingKey::random();
94 auto addr = k.address();
96 // Check for collision, even though it is unlikely to ever occur
97 if (CCryptoKeyStore::HaveSproutSpendingKey(addr))
98 throw std::runtime_error("CWallet::GenerateNewSproutZKey(): Collision detected");
100 // Create new metadata
101 int64_t nCreationTime = GetTime();
102 mapSproutZKeyMetadata[addr] = CKeyMetadata(nCreationTime);
104 if (!AddSproutZKey(k))
105 throw std::runtime_error("CWallet::GenerateNewSproutZKey(): AddSproutZKey failed");
109 // Generate a new Sapling spending key and return its public payment address
110 SaplingPaymentAddress CWallet::GenerateNewSaplingZKey()
112 AssertLockHeld(cs_wallet); // mapSaplingZKeyMetadata
114 // Create new metadata
115 int64_t nCreationTime = GetTime();
116 CKeyMetadata metadata(nCreationTime);
118 // Try to get the seed
120 if (!GetHDSeed(seed))
121 throw std::runtime_error("CWallet::GenerateNewSaplingZKey(): HD seed not found");
123 auto m = libzcash::SaplingExtendedSpendingKey::Master(seed);
124 uint32_t bip44CoinType = Params().BIP44CoinType();
126 // We use a fixed keypath scheme of m/32'/coin_type'/account'
128 auto m_32h = m.Derive(32 | ZIP32_HARDENED_KEY_LIMIT);
129 // Derive m/32'/coin_type'
130 auto m_32h_cth = m_32h.Derive(bip44CoinType | ZIP32_HARDENED_KEY_LIMIT);
132 // Derive account key at next index, skip keys already known to the wallet
133 libzcash::SaplingExtendedSpendingKey xsk;
136 xsk = m_32h_cth.Derive(hdChain.saplingAccountCounter | ZIP32_HARDENED_KEY_LIMIT);
137 metadata.hdKeypath = "m/32'/" + std::to_string(bip44CoinType) + "'/" + std::to_string(hdChain.saplingAccountCounter) + "'";
138 metadata.seedFp = hdChain.seedFp;
139 // Increment childkey index
140 hdChain.saplingAccountCounter++;
141 } while (HaveSaplingSpendingKey(xsk.expsk.full_viewing_key()));
143 // Update the chain model in the database
144 if (fFileBacked && !CWalletDB(strWalletFile).WriteHDChain(hdChain))
145 throw std::runtime_error("CWallet::GenerateNewSaplingZKey(): Writing HD chain model failed");
147 auto ivk = xsk.expsk.full_viewing_key().in_viewing_key();
148 mapSaplingZKeyMetadata[ivk] = metadata;
150 auto addr = xsk.DefaultAddress();
151 if (!AddSaplingZKey(xsk, addr)) {
152 throw std::runtime_error("CWallet::GenerateNewSaplingZKey(): AddSaplingZKey failed");
154 // return default sapling payment address.
158 // Add spending key to keystore
159 bool CWallet::AddSaplingZKey(
160 const libzcash::SaplingExtendedSpendingKey &sk,
161 const libzcash::SaplingPaymentAddress &defaultAddr)
163 AssertLockHeld(cs_wallet); // mapSaplingZKeyMetadata
165 if (!CCryptoKeyStore::AddSaplingSpendingKey(sk, defaultAddr)) {
174 auto ivk = sk.expsk.full_viewing_key().in_viewing_key();
175 return CWalletDB(strWalletFile).WriteSaplingZKey(ivk, sk, mapSaplingZKeyMetadata[ivk]);
181 // Add payment address -> incoming viewing key map entry
182 bool CWallet::AddSaplingIncomingViewingKey(
183 const libzcash::SaplingIncomingViewingKey &ivk,
184 const libzcash::SaplingPaymentAddress &addr)
186 AssertLockHeld(cs_wallet); // mapSaplingZKeyMetadata
188 if (!CCryptoKeyStore::AddSaplingIncomingViewingKey(ivk, addr)) {
197 return CWalletDB(strWalletFile).WriteSaplingPaymentAddress(addr, ivk);
204 // Add spending key to keystore and persist to disk
205 bool CWallet::AddSproutZKey(const libzcash::SproutSpendingKey &key)
207 AssertLockHeld(cs_wallet); // mapSproutZKeyMetadata
208 auto addr = key.address();
210 if (!CCryptoKeyStore::AddSproutSpendingKey(key))
213 // check if we need to remove from viewing keys
214 if (HaveSproutViewingKey(addr))
215 RemoveSproutViewingKey(key.viewing_key());
221 return CWalletDB(strWalletFile).WriteZKey(addr,
223 mapSproutZKeyMetadata[addr]);
228 CPubKey CWallet::GenerateNewKey()
230 AssertLockHeld(cs_wallet); // mapKeyMetadata
231 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
234 secret.MakeNewKey(fCompressed);
236 // Compressed public keys were introduced in version 0.6.0
238 SetMinVersion(FEATURE_COMPRPUBKEY);
240 CPubKey pubkey = secret.GetPubKey();
241 assert(secret.VerifyPubKey(pubkey));
243 // Create new metadata
244 int64_t nCreationTime = GetTime();
245 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
246 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
247 nTimeFirstKey = nCreationTime;
249 if (!AddKeyPubKey(secret, pubkey))
250 throw std::runtime_error("CWallet::GenerateNewKey(): AddKey failed");
254 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
256 AssertLockHeld(cs_wallet); // mapKeyMetadata
257 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
260 // check if we need to remove from watch-only
262 script = GetScriptForDestination(pubkey.GetID());
263 if (HaveWatchOnly(script))
264 RemoveWatchOnly(script);
269 return CWalletDB(strWalletFile).WriteKey(pubkey,
271 mapKeyMetadata[pubkey.GetID()]);
276 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
277 const vector<unsigned char> &vchCryptedSecret)
280 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
286 if (pwalletdbEncryption)
287 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
289 mapKeyMetadata[vchPubKey.GetID()]);
291 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
293 mapKeyMetadata[vchPubKey.GetID()]);
299 bool CWallet::AddCryptedSproutSpendingKey(
300 const libzcash::SproutPaymentAddress &address,
301 const libzcash::ReceivingKey &rk,
302 const std::vector<unsigned char> &vchCryptedSecret)
304 if (!CCryptoKeyStore::AddCryptedSproutSpendingKey(address, rk, vchCryptedSecret))
310 if (pwalletdbEncryption) {
311 return pwalletdbEncryption->WriteCryptedZKey(address,
314 mapSproutZKeyMetadata[address]);
316 return CWalletDB(strWalletFile).WriteCryptedZKey(address,
319 mapSproutZKeyMetadata[address]);
325 bool CWallet::AddCryptedSaplingSpendingKey(const libzcash::SaplingExtendedFullViewingKey &extfvk,
326 const std::vector<unsigned char> &vchCryptedSecret,
327 const libzcash::SaplingPaymentAddress &defaultAddr)
329 if (!CCryptoKeyStore::AddCryptedSaplingSpendingKey(extfvk, vchCryptedSecret, defaultAddr))
335 if (pwalletdbEncryption) {
336 return pwalletdbEncryption->WriteCryptedSaplingZKey(extfvk,
338 mapSaplingZKeyMetadata[extfvk.fvk.in_viewing_key()]);
340 return CWalletDB(strWalletFile).WriteCryptedSaplingZKey(extfvk,
342 mapSaplingZKeyMetadata[extfvk.fvk.in_viewing_key()]);
348 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
350 AssertLockHeld(cs_wallet); // mapKeyMetadata
351 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
352 nTimeFirstKey = meta.nCreateTime;
354 mapKeyMetadata[pubkey.GetID()] = meta;
358 bool CWallet::LoadZKeyMetadata(const SproutPaymentAddress &addr, const CKeyMetadata &meta)
360 AssertLockHeld(cs_wallet); // mapSproutZKeyMetadata
361 mapSproutZKeyMetadata[addr] = meta;
365 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
367 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
370 bool CWallet::LoadCryptedZKey(const libzcash::SproutPaymentAddress &addr, const libzcash::ReceivingKey &rk, const std::vector<unsigned char> &vchCryptedSecret)
372 return CCryptoKeyStore::AddCryptedSproutSpendingKey(addr, rk, vchCryptedSecret);
375 bool CWallet::LoadCryptedSaplingZKey(
376 const libzcash::SaplingExtendedFullViewingKey &extfvk,
377 const std::vector<unsigned char> &vchCryptedSecret)
379 return CCryptoKeyStore::AddCryptedSaplingSpendingKey(extfvk, vchCryptedSecret, extfvk.DefaultAddress());
382 bool CWallet::LoadSaplingZKeyMetadata(const libzcash::SaplingIncomingViewingKey &ivk, const CKeyMetadata &meta)
384 AssertLockHeld(cs_wallet); // mapSaplingZKeyMetadata
385 mapSaplingZKeyMetadata[ivk] = meta;
389 bool CWallet::LoadSaplingZKey(const libzcash::SaplingExtendedSpendingKey &key)
391 return CCryptoKeyStore::AddSaplingSpendingKey(key, key.DefaultAddress());
394 bool CWallet::LoadSaplingPaymentAddress(
395 const libzcash::SaplingPaymentAddress &addr,
396 const libzcash::SaplingIncomingViewingKey &ivk)
398 return CCryptoKeyStore::AddSaplingIncomingViewingKey(ivk, addr);
401 bool CWallet::LoadZKey(const libzcash::SproutSpendingKey &key)
403 return CCryptoKeyStore::AddSproutSpendingKey(key);
406 bool CWallet::AddSproutViewingKey(const libzcash::SproutViewingKey &vk)
408 if (!CCryptoKeyStore::AddSproutViewingKey(vk)) {
411 nTimeFirstKey = 1; // No birthday information for viewing keys.
415 return CWalletDB(strWalletFile).WriteSproutViewingKey(vk);
418 bool CWallet::RemoveSproutViewingKey(const libzcash::SproutViewingKey &vk)
420 AssertLockHeld(cs_wallet);
421 if (!CCryptoKeyStore::RemoveSproutViewingKey(vk)) {
425 if (!CWalletDB(strWalletFile).EraseSproutViewingKey(vk)) {
433 bool CWallet::LoadSproutViewingKey(const libzcash::SproutViewingKey &vk)
435 return CCryptoKeyStore::AddSproutViewingKey(vk);
438 bool CWallet::AddCScript(const CScript& redeemScript)
440 if (!CCryptoKeyStore::AddCScript(redeemScript))
444 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
447 bool CWallet::LoadCScript(const CScript& redeemScript)
449 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
450 * that never can be redeemed. However, old wallets may still contain
451 * these. Do not add them to the wallet and warn. */
452 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
454 std::string strAddr = EncodeDestination(CScriptID(redeemScript));
455 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",
456 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
460 return CCryptoKeyStore::AddCScript(redeemScript);
463 bool CWallet::AddWatchOnly(const CScript &dest)
465 if (!CCryptoKeyStore::AddWatchOnly(dest))
467 nTimeFirstKey = 1; // No birthday information for watch-only keys.
468 NotifyWatchonlyChanged(true);
471 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
474 bool CWallet::RemoveWatchOnly(const CScript &dest)
476 AssertLockHeld(cs_wallet);
477 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
479 if (!HaveWatchOnly())
480 NotifyWatchonlyChanged(false);
482 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
488 bool CWallet::LoadWatchOnly(const CScript &dest)
490 return CCryptoKeyStore::AddWatchOnly(dest);
493 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
496 CKeyingMaterial vMasterKey;
500 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
502 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
504 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
505 continue; // try another master key
506 if (CCryptoKeyStore::Unlock(vMasterKey)) {
507 // Now that the wallet is decrypted, ensure we have an HD seed.
508 // https://github.com/zcash/zcash/issues/3607
509 if (!this->HaveHDSeed()) {
510 this->GenerateNewSeed();
519 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
521 bool fWasLocked = IsLocked();
528 CKeyingMaterial vMasterKey;
529 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
531 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
533 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
535 if (CCryptoKeyStore::Unlock(vMasterKey))
537 int64_t nStartTime = GetTimeMillis();
538 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
539 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
541 nStartTime = GetTimeMillis();
542 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
543 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
545 if (pMasterKey.second.nDeriveIterations < 25000)
546 pMasterKey.second.nDeriveIterations = 25000;
548 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
550 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
552 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
554 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
565 void CWallet::ChainTipAdded(const CBlockIndex *pindex,
566 const CBlock *pblock,
567 SproutMerkleTree sproutTree,
568 SaplingMerkleTree saplingTree)
570 IncrementNoteWitnesses(pindex, pblock, sproutTree, saplingTree);
571 UpdateSaplingNullifierNoteMapForBlock(pblock);
574 void CWallet::ChainTip(const CBlockIndex *pindex,
575 const CBlock *pblock,
576 SproutMerkleTree sproutTree,
577 SaplingMerkleTree saplingTree,
581 ChainTipAdded(pindex, pblock, sproutTree, saplingTree);
582 // Prevent migration transactions from being created when node is syncing after launch,
583 // and also when node wakes up from suspension/hibernation and incoming blocks are old.
584 if (!IsInitialBlockDownload(Params()) &&
585 pblock->GetBlockTime() > GetAdjustedTime() - 3 * 60 * 60)
587 RunSaplingMigration(pindex->nHeight);
590 DecrementNoteWitnesses(pindex);
591 UpdateSaplingNullifierNoteMapForBlock(pblock);
595 void CWallet::RunSaplingMigration(int blockHeight) {
596 if (!Params().GetConsensus().NetworkUpgradeActive(blockHeight, Consensus::UPGRADE_SAPLING)) {
600 if (!fSaplingMigrationEnabled) {
603 // The migration transactions to be sent in a particular batch can take
604 // significant time to generate, and this time depends on the speed of the user's
605 // computer. If they were generated only after a block is seen at the target
606 // height minus 1, then this could leak information. Therefore, for target
607 // height N, implementations SHOULD start generating the transactions at around
609 if (blockHeight % 500 == 495) {
610 std::shared_ptr<AsyncRPCQueue> q = getAsyncRPCQueue();
611 std::shared_ptr<AsyncRPCOperation> lastOperation = q->getOperationForId(saplingMigrationOperationId);
612 if (lastOperation != nullptr) {
613 lastOperation->cancel();
615 pendingSaplingMigrationTxs.clear();
616 std::shared_ptr<AsyncRPCOperation> operation(new AsyncRPCOperation_saplingmigration(blockHeight + 5));
617 saplingMigrationOperationId = operation->getId();
618 q->addOperation(operation);
619 } else if (blockHeight % 500 == 499) {
620 std::shared_ptr<AsyncRPCQueue> q = getAsyncRPCQueue();
621 std::shared_ptr<AsyncRPCOperation> lastOperation = q->getOperationForId(saplingMigrationOperationId);
622 if (lastOperation != nullptr) {
623 lastOperation->cancel();
625 for (const CTransaction& transaction : pendingSaplingMigrationTxs) {
626 // Send the transaction
627 CWalletTx wtx(this, transaction);
628 CommitTransaction(wtx, boost::none);
630 pendingSaplingMigrationTxs.clear();
634 void CWallet::AddPendingSaplingMigrationTx(const CTransaction& tx) {
636 pendingSaplingMigrationTxs.push_back(tx);
639 void CWallet::SetBestChain(const CBlockLocator& loc)
641 CWalletDB walletdb(strWalletFile);
642 SetBestChainINTERNAL(walletdb, loc);
645 std::set<std::pair<libzcash::PaymentAddress, uint256>> CWallet::GetNullifiersForAddresses(
646 const std::set<libzcash::PaymentAddress> & addresses)
648 std::set<std::pair<libzcash::PaymentAddress, uint256>> nullifierSet;
649 // Sapling ivk -> list of addrs map
650 // (There may be more than one diversified address for a given ivk.)
651 std::map<libzcash::SaplingIncomingViewingKey, std::vector<libzcash::SaplingPaymentAddress>> ivkMap;
652 for (const auto & addr : addresses) {
653 auto saplingAddr = boost::get<libzcash::SaplingPaymentAddress>(&addr);
654 if (saplingAddr != nullptr) {
655 libzcash::SaplingIncomingViewingKey ivk;
656 this->GetSaplingIncomingViewingKey(*saplingAddr, ivk);
657 ivkMap[ivk].push_back(*saplingAddr);
660 for (const auto & txPair : mapWallet) {
662 for (const auto & noteDataPair : txPair.second.mapSproutNoteData) {
663 auto & noteData = noteDataPair.second;
664 auto & nullifier = noteData.nullifier;
665 auto & address = noteData.address;
666 if (nullifier && addresses.count(address)) {
667 nullifierSet.insert(std::make_pair(address, nullifier.get()));
671 for (const auto & noteDataPair : txPair.second.mapSaplingNoteData) {
672 auto & noteData = noteDataPair.second;
673 auto & nullifier = noteData.nullifier;
674 auto & ivk = noteData.ivk;
675 if (nullifier && ivkMap.count(ivk)) {
676 for (const auto & addr : ivkMap[ivk]) {
677 nullifierSet.insert(std::make_pair(addr, nullifier.get()));
685 bool CWallet::IsNoteSproutChange(
686 const std::set<std::pair<libzcash::PaymentAddress, uint256>> & nullifierSet,
687 const PaymentAddress & address,
688 const JSOutPoint & jsop)
690 // A Note is marked as "change" if the address that received it
691 // also spent Notes in the same transaction. This will catch,
693 // - Change created by spending fractions of Notes (because
694 // z_sendmany sends change to the originating z-address).
695 // - "Chaining Notes" used to connect JoinSplits together.
696 // - Notes created by consolidation transactions (e.g. using
697 // z_mergetoaddress).
698 // - Notes sent from one address to itself.
699 for (const JSDescription & jsd : mapWallet[jsop.hash].vJoinSplit) {
700 for (const uint256 & nullifier : jsd.nullifiers) {
701 if (nullifierSet.count(std::make_pair(address, nullifier))) {
709 bool CWallet::IsNoteSaplingChange(const std::set<std::pair<libzcash::PaymentAddress, uint256>> & nullifierSet,
710 const libzcash::PaymentAddress & address,
711 const SaplingOutPoint & op)
713 // A Note is marked as "change" if the address that received it
714 // also spent Notes in the same transaction. This will catch,
716 // - Change created by spending fractions of Notes (because
717 // z_sendmany sends change to the originating z-address).
718 // - Notes created by consolidation transactions (e.g. using
719 // z_mergetoaddress).
720 // - Notes sent from one address to itself.
721 for (const SpendDescription &spend : mapWallet[op.hash].vShieldedSpend) {
722 if (nullifierSet.count(std::make_pair(address, spend.nullifier))) {
729 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
731 LOCK(cs_wallet); // nWalletVersion
732 if (nWalletVersion >= nVersion)
735 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
736 if (fExplicit && nVersion > nWalletMaxVersion)
737 nVersion = FEATURE_LATEST;
739 nWalletVersion = nVersion;
741 if (nVersion > nWalletMaxVersion)
742 nWalletMaxVersion = nVersion;
746 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
747 if (nWalletVersion > 40000)
748 pwalletdb->WriteMinVersion(nWalletVersion);
756 bool CWallet::SetMaxVersion(int nVersion)
758 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
759 // cannot downgrade below current version
760 if (nWalletVersion > nVersion)
763 nWalletMaxVersion = nVersion;
768 set<uint256> CWallet::GetConflicts(const uint256& txid) const
771 AssertLockHeld(cs_wallet);
773 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
774 if (it == mapWallet.end())
776 const CWalletTx& wtx = it->second;
778 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
780 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
782 if (mapTxSpends.count(txin.prevout) <= 1)
783 continue; // No conflict if zero or one spends
784 range = mapTxSpends.equal_range(txin.prevout);
785 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
786 result.insert(it->second);
789 std::pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range_n;
791 for (const JSDescription& jsdesc : wtx.vJoinSplit) {
792 for (const uint256& nullifier : jsdesc.nullifiers) {
793 if (mapTxSproutNullifiers.count(nullifier) <= 1) {
794 continue; // No conflict if zero or one spends
796 range_n = mapTxSproutNullifiers.equal_range(nullifier);
797 for (TxNullifiers::const_iterator it = range_n.first; it != range_n.second; ++it) {
798 result.insert(it->second);
803 std::pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range_o;
805 for (const SpendDescription &spend : wtx.vShieldedSpend) {
806 uint256 nullifier = spend.nullifier;
807 if (mapTxSaplingNullifiers.count(nullifier) <= 1) {
808 continue; // No conflict if zero or one spends
810 range_o = mapTxSaplingNullifiers.equal_range(nullifier);
811 for (TxNullifiers::const_iterator it = range_o.first; it != range_o.second; ++it) {
812 result.insert(it->second);
818 void CWallet::Flush(bool shutdown)
820 bitdb.Flush(shutdown);
823 bool CWallet::Verify(const string& walletFile, string& warningString, string& errorString)
825 if (!bitdb.Open(GetDataDir()))
827 // try moving the database env out of the way
828 boost::filesystem::path pathDatabase = GetDataDir() / "database";
829 boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
831 boost::filesystem::rename(pathDatabase, pathDatabaseBak);
832 LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
833 } catch (const boost::filesystem::filesystem_error&) {
834 // failure is ok (well, not really, but it's not worse than what we started with)
838 if (!bitdb.Open(GetDataDir())) {
839 // if it still fails, it probably means we can't even create the database env
840 string msg = strprintf(_("Error initializing wallet database environment %s!"), GetDataDir());
846 if (GetBoolArg("-salvagewallet", false))
848 // Recover readable keypairs:
849 if (!CWalletDB::Recover(bitdb, walletFile, true))
853 if (boost::filesystem::exists(GetDataDir() / walletFile))
855 CDBEnv::VerifyResult r = bitdb.Verify(walletFile, CWalletDB::Recover);
856 if (r == CDBEnv::RECOVER_OK)
858 warningString += strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
859 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
860 " your balance or transactions are incorrect you should"
861 " restore from a backup."), GetDataDir());
863 if (r == CDBEnv::RECOVER_FAIL)
864 errorString += _("wallet.dat corrupt, salvage failed");
871 void CWallet::SyncMetaData(pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator> range)
873 // We want all the wallet transactions in range to have the same metadata as
874 // the oldest (smallest nOrderPos).
875 // So: find smallest nOrderPos:
877 int nMinOrderPos = std::numeric_limits<int>::max();
878 const CWalletTx* copyFrom = NULL;
879 for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
881 const uint256& hash = it->second;
882 int n = mapWallet[hash].nOrderPos;
883 if (n < nMinOrderPos)
886 copyFrom = &mapWallet[hash];
889 // Now copy data from copyFrom to rest:
890 for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
892 const uint256& hash = it->second;
893 CWalletTx* copyTo = &mapWallet[hash];
894 if (copyFrom == copyTo) continue;
895 copyTo->mapValue = copyFrom->mapValue;
896 // mapSproutNoteData and mapSaplingNoteData not copied on purpose
897 // (it is always set correctly for each CWalletTx)
898 copyTo->vOrderForm = copyFrom->vOrderForm;
899 // fTimeReceivedIsTxTime not copied on purpose
900 // nTimeReceived not copied on purpose
901 copyTo->nTimeSmart = copyFrom->nTimeSmart;
902 copyTo->fFromMe = copyFrom->fFromMe;
903 copyTo->strFromAccount = copyFrom->strFromAccount;
904 // nOrderPos not copied on purpose
905 // cached members not copied on purpose
910 * Outpoint is spent if any non-conflicted transaction
913 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
915 const COutPoint outpoint(hash, n);
916 pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
917 range = mapTxSpends.equal_range(outpoint);
919 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
921 const uint256& wtxid = it->second;
922 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
923 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
924 return true; // Spent
930 * Note is spent if any non-conflicted transaction
933 bool CWallet::IsSproutSpent(const uint256& nullifier) const {
934 pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range;
935 range = mapTxSproutNullifiers.equal_range(nullifier);
937 for (TxNullifiers::const_iterator it = range.first; it != range.second; ++it) {
938 const uint256& wtxid = it->second;
939 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
940 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) {
941 return true; // Spent
947 bool CWallet::IsSaplingSpent(const uint256& nullifier) const {
948 pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range;
949 range = mapTxSaplingNullifiers.equal_range(nullifier);
951 for (TxNullifiers::const_iterator it = range.first; it != range.second; ++it) {
952 const uint256& wtxid = it->second;
953 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
954 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) {
955 return true; // Spent
961 void CWallet::AddToTransparentSpends(const COutPoint& outpoint, const uint256& wtxid)
963 mapTxSpends.insert(make_pair(outpoint, wtxid));
965 pair<TxSpends::iterator, TxSpends::iterator> range;
966 range = mapTxSpends.equal_range(outpoint);
967 SyncMetaData<COutPoint>(range);
970 void CWallet::AddToSproutSpends(const uint256& nullifier, const uint256& wtxid)
972 mapTxSproutNullifiers.insert(make_pair(nullifier, wtxid));
974 pair<TxNullifiers::iterator, TxNullifiers::iterator> range;
975 range = mapTxSproutNullifiers.equal_range(nullifier);
976 SyncMetaData<uint256>(range);
979 void CWallet::AddToSaplingSpends(const uint256& nullifier, const uint256& wtxid)
981 mapTxSaplingNullifiers.insert(make_pair(nullifier, wtxid));
983 pair<TxNullifiers::iterator, TxNullifiers::iterator> range;
984 range = mapTxSaplingNullifiers.equal_range(nullifier);
985 SyncMetaData<uint256>(range);
988 void CWallet::AddToSpends(const uint256& wtxid)
990 assert(mapWallet.count(wtxid));
991 CWalletTx& thisTx = mapWallet[wtxid];
992 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
995 for (const CTxIn& txin : thisTx.vin) {
996 AddToTransparentSpends(txin.prevout, wtxid);
998 for (const JSDescription& jsdesc : thisTx.vJoinSplit) {
999 for (const uint256& nullifier : jsdesc.nullifiers) {
1000 AddToSproutSpends(nullifier, wtxid);
1003 for (const SpendDescription &spend : thisTx.vShieldedSpend) {
1004 AddToSaplingSpends(spend.nullifier, wtxid);
1008 void CWallet::ClearNoteWitnessCache()
1011 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1012 for (mapSproutNoteData_t::value_type& item : wtxItem.second.mapSproutNoteData) {
1013 item.second.witnesses.clear();
1014 item.second.witnessHeight = -1;
1016 for (mapSaplingNoteData_t::value_type& item : wtxItem.second.mapSaplingNoteData) {
1017 item.second.witnesses.clear();
1018 item.second.witnessHeight = -1;
1021 nWitnessCacheSize = 0;
1024 template<typename NoteDataMap>
1025 void CopyPreviousWitnesses(NoteDataMap& noteDataMap, int indexHeight, int64_t nWitnessCacheSize)
1027 for (auto& item : noteDataMap) {
1028 auto* nd = &(item.second);
1029 // Only increment witnesses that are behind the current height
1030 if (nd->witnessHeight < indexHeight) {
1031 // Check the validity of the cache
1032 // The only time a note witnessed above the current height
1033 // would be invalid here is during a reindex when blocks
1034 // have been decremented, and we are incrementing the blocks
1035 // immediately after.
1036 assert(nWitnessCacheSize >= nd->witnesses.size());
1037 // Witnesses being incremented should always be either -1
1038 // (never incremented or decremented) or one below indexHeight
1039 assert((nd->witnessHeight == -1) || (nd->witnessHeight == indexHeight - 1));
1040 // Copy the witness for the previous block if we have one
1041 if (nd->witnesses.size() > 0) {
1042 nd->witnesses.push_front(nd->witnesses.front());
1044 if (nd->witnesses.size() > WITNESS_CACHE_SIZE) {
1045 nd->witnesses.pop_back();
1051 template<typename NoteDataMap>
1052 void AppendNoteCommitment(NoteDataMap& noteDataMap, int indexHeight, int64_t nWitnessCacheSize, const uint256& note_commitment)
1054 for (auto& item : noteDataMap) {
1055 auto* nd = &(item.second);
1056 if (nd->witnessHeight < indexHeight && nd->witnesses.size() > 0) {
1057 // Check the validity of the cache
1058 // See comment in CopyPreviousWitnesses about validity.
1059 assert(nWitnessCacheSize >= nd->witnesses.size());
1060 nd->witnesses.front().append(note_commitment);
1065 template<typename OutPoint, typename NoteData, typename Witness>
1066 void WitnessNoteIfMine(std::map<OutPoint, NoteData>& noteDataMap, int indexHeight, int64_t nWitnessCacheSize, const OutPoint& key, const Witness& witness)
1068 if (noteDataMap.count(key) && noteDataMap[key].witnessHeight < indexHeight) {
1069 auto* nd = &(noteDataMap[key]);
1070 if (nd->witnesses.size() > 0) {
1071 // We think this can happen because we write out the
1072 // witness cache state after every block increment or
1073 // decrement, but the block index itself is written in
1074 // batches. So if the node crashes in between these two
1075 // operations, it is possible for IncrementNoteWitnesses
1076 // to be called again on previously-cached blocks. This
1077 // doesn't affect existing cached notes because of the
1078 // NoteData::witnessHeight checks. See #1378 for details.
1079 LogPrintf("Inconsistent witness cache state found for %s\n- Cache size: %d\n- Top (height %d): %s\n- New (height %d): %s\n",
1080 key.ToString(), nd->witnesses.size(),
1082 nd->witnesses.front().root().GetHex(),
1084 witness.root().GetHex());
1085 nd->witnesses.clear();
1087 nd->witnesses.push_front(witness);
1088 // Set height to one less than pindex so it gets incremented
1089 nd->witnessHeight = indexHeight - 1;
1090 // Check the validity of the cache
1091 assert(nWitnessCacheSize >= nd->witnesses.size());
1096 template<typename NoteDataMap>
1097 void UpdateWitnessHeights(NoteDataMap& noteDataMap, int indexHeight, int64_t nWitnessCacheSize)
1099 for (auto& item : noteDataMap) {
1100 auto* nd = &(item.second);
1101 if (nd->witnessHeight < indexHeight) {
1102 nd->witnessHeight = indexHeight;
1103 // Check the validity of the cache
1104 // See comment in CopyPreviousWitnesses about validity.
1105 assert(nWitnessCacheSize >= nd->witnesses.size());
1110 void CWallet::IncrementNoteWitnesses(const CBlockIndex* pindex,
1111 const CBlock* pblockIn,
1112 SproutMerkleTree& sproutTree,
1113 SaplingMerkleTree& saplingTree)
1116 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1117 ::CopyPreviousWitnesses(wtxItem.second.mapSproutNoteData, pindex->nHeight, nWitnessCacheSize);
1118 ::CopyPreviousWitnesses(wtxItem.second.mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize);
1121 if (nWitnessCacheSize < WITNESS_CACHE_SIZE) {
1122 nWitnessCacheSize += 1;
1125 const CBlock* pblock {pblockIn};
1128 ReadBlockFromDisk(block, pindex, Params().GetConsensus());
1132 for (const CTransaction& tx : pblock->vtx) {
1133 auto hash = tx.GetHash();
1134 bool txIsOurs = mapWallet.count(hash);
1136 for (size_t i = 0; i < tx.vJoinSplit.size(); i++) {
1137 const JSDescription& jsdesc = tx.vJoinSplit[i];
1138 for (uint8_t j = 0; j < jsdesc.commitments.size(); j++) {
1139 const uint256& note_commitment = jsdesc.commitments[j];
1140 sproutTree.append(note_commitment);
1142 // Increment existing witnesses
1143 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1144 ::AppendNoteCommitment(wtxItem.second.mapSproutNoteData, pindex->nHeight, nWitnessCacheSize, note_commitment);
1147 // If this is our note, witness it
1149 JSOutPoint jsoutpt {hash, i, j};
1150 ::WitnessNoteIfMine(mapWallet[hash].mapSproutNoteData, pindex->nHeight, nWitnessCacheSize, jsoutpt, sproutTree.witness());
1155 for (uint32_t i = 0; i < tx.vShieldedOutput.size(); i++) {
1156 const uint256& note_commitment = tx.vShieldedOutput[i].cm;
1157 saplingTree.append(note_commitment);
1159 // Increment existing witnesses
1160 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1161 ::AppendNoteCommitment(wtxItem.second.mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize, note_commitment);
1164 // If this is our note, witness it
1166 SaplingOutPoint outPoint {hash, i};
1167 ::WitnessNoteIfMine(mapWallet[hash].mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize, outPoint, saplingTree.witness());
1172 // Update witness heights
1173 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1174 ::UpdateWitnessHeights(wtxItem.second.mapSproutNoteData, pindex->nHeight, nWitnessCacheSize);
1175 ::UpdateWitnessHeights(wtxItem.second.mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize);
1178 // For performance reasons, we write out the witness cache in
1179 // CWallet::SetBestChain() (which also ensures that overall consistency
1180 // of the wallet.dat is maintained).
1183 template<typename NoteDataMap>
1184 void DecrementNoteWitnesses(NoteDataMap& noteDataMap, int indexHeight, int64_t nWitnessCacheSize)
1186 for (auto& item : noteDataMap) {
1187 auto* nd = &(item.second);
1188 // Only decrement witnesses that are not above the current height
1189 if (nd->witnessHeight <= indexHeight) {
1190 // Check the validity of the cache
1191 // See comment below (this would be invalid if there were a
1192 // prior decrement).
1193 assert(nWitnessCacheSize >= nd->witnesses.size());
1194 // Witnesses being decremented should always be either -1
1195 // (never incremented or decremented) or equal to the height
1196 // of the block being removed (indexHeight)
1197 assert((nd->witnessHeight == -1) || (nd->witnessHeight == indexHeight));
1198 if (nd->witnesses.size() > 0) {
1199 nd->witnesses.pop_front();
1201 // indexHeight is the height of the block being removed, so
1202 // the new witness cache height is one below it.
1203 nd->witnessHeight = indexHeight - 1;
1205 // Check the validity of the cache
1206 // Technically if there are notes witnessed above the current
1207 // height, their cache will now be invalid (relative to the new
1208 // value of nWitnessCacheSize). However, this would only occur
1209 // during a reindex, and by the time the reindex reaches the tip
1210 // of the chain again, the existing witness caches will be valid
1212 // We don't set nWitnessCacheSize to zero at the start of the
1213 // reindex because the on-disk blocks had already resulted in a
1214 // chain that didn't trigger the assertion below.
1215 if (nd->witnessHeight < indexHeight) {
1216 // Subtract 1 to compare to what nWitnessCacheSize will be after
1218 assert((nWitnessCacheSize - 1) >= nd->witnesses.size());
1223 void CWallet::DecrementNoteWitnesses(const CBlockIndex* pindex)
1226 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1227 ::DecrementNoteWitnesses(wtxItem.second.mapSproutNoteData, pindex->nHeight, nWitnessCacheSize);
1228 ::DecrementNoteWitnesses(wtxItem.second.mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize);
1230 nWitnessCacheSize -= 1;
1231 // TODO: If nWitnessCache is zero, we need to regenerate the caches (#1302)
1232 assert(nWitnessCacheSize > 0);
1234 // For performance reasons, we write out the witness cache in
1235 // CWallet::SetBestChain() (which also ensures that overall consistency
1236 // of the wallet.dat is maintained).
1239 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
1244 CKeyingMaterial vMasterKey;
1246 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
1247 GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
1249 CMasterKey kMasterKey;
1251 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
1252 GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
1255 int64_t nStartTime = GetTimeMillis();
1256 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
1257 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
1259 nStartTime = GetTimeMillis();
1260 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
1261 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
1263 if (kMasterKey.nDeriveIterations < 25000)
1264 kMasterKey.nDeriveIterations = 25000;
1266 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
1268 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
1270 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
1275 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
1278 assert(!pwalletdbEncryption);
1279 pwalletdbEncryption = new CWalletDB(strWalletFile);
1280 if (!pwalletdbEncryption->TxnBegin()) {
1281 delete pwalletdbEncryption;
1282 pwalletdbEncryption = NULL;
1285 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
1288 if (!EncryptKeys(vMasterKey))
1291 pwalletdbEncryption->TxnAbort();
1292 delete pwalletdbEncryption;
1294 // We now probably have half of our keys encrypted in memory, and half not...
1295 // die and let the user reload the unencrypted wallet.
1299 // Encryption was introduced in version 0.4.0
1300 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
1304 if (!pwalletdbEncryption->TxnCommit()) {
1305 delete pwalletdbEncryption;
1306 // We now have keys encrypted in memory, but not on disk...
1307 // die to avoid confusion and let the user reload the unencrypted wallet.
1311 delete pwalletdbEncryption;
1312 pwalletdbEncryption = NULL;
1316 Unlock(strWalletPassphrase);
1320 // Need to completely rewrite the wallet file; if we don't, bdb might keep
1321 // bits of the unencrypted private key in slack space in the database file.
1322 CDB::Rewrite(strWalletFile);
1325 NotifyStatusChanged(this);
1330 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
1332 AssertLockHeld(cs_wallet); // nOrderPosNext
1333 int64_t nRet = nOrderPosNext++;
1335 pwalletdb->WriteOrderPosNext(nOrderPosNext);
1337 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
1342 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
1344 AssertLockHeld(cs_wallet); // mapWallet
1345 CWalletDB walletdb(strWalletFile);
1347 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
1350 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
1351 // would make this much faster for applications that do this a lot.
1352 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1354 CWalletTx* wtx = &((*it).second);
1355 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
1358 walletdb.ListAccountCreditDebit(strAccount, acentries);
1359 BOOST_FOREACH(CAccountingEntry& entry, acentries)
1361 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
1367 void CWallet::MarkDirty()
1371 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1372 item.second.MarkDirty();
1377 * Ensure that every note in the wallet (for which we possess a spending key)
1378 * has a cached nullifier.
1380 bool CWallet::UpdateNullifierNoteMap()
1388 ZCNoteDecryption dec;
1389 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1390 for (mapSproutNoteData_t::value_type& item : wtxItem.second.mapSproutNoteData) {
1391 if (!item.second.nullifier) {
1392 if (GetNoteDecryptor(item.second.address, dec)) {
1393 auto i = item.first.js;
1394 auto hSig = wtxItem.second.vJoinSplit[i].h_sig(
1395 *pzcashParams, wtxItem.second.joinSplitPubKey);
1396 item.second.nullifier = GetSproutNoteNullifier(
1397 wtxItem.second.vJoinSplit[i],
1398 item.second.address,
1406 // TODO: Sapling. This method is only called from RPC walletpassphrase, which is currently unsupported
1407 // as RPC encryptwallet is hidden behind two flags: -developerencryptwallet -experimentalfeatures
1409 UpdateNullifierNoteMapWithTx(wtxItem.second);
1416 * Update mapSproutNullifiersToNotes and mapSaplingNullifiersToNotes
1417 * with the cached nullifiers in this tx.
1419 void CWallet::UpdateNullifierNoteMapWithTx(const CWalletTx& wtx)
1423 for (const mapSproutNoteData_t::value_type& item : wtx.mapSproutNoteData) {
1424 if (item.second.nullifier) {
1425 mapSproutNullifiersToNotes[*item.second.nullifier] = item.first;
1429 for (const mapSaplingNoteData_t::value_type& item : wtx.mapSaplingNoteData) {
1430 if (item.second.nullifier) {
1431 mapSaplingNullifiersToNotes[*item.second.nullifier] = item.first;
1438 * Update mapSaplingNullifiersToNotes, computing the nullifier from a cached witness if necessary.
1440 void CWallet::UpdateSaplingNullifierNoteMapWithTx(CWalletTx& wtx) {
1443 for (mapSaplingNoteData_t::value_type &item : wtx.mapSaplingNoteData) {
1444 SaplingOutPoint op = item.first;
1445 SaplingNoteData nd = item.second;
1447 if (nd.witnesses.empty()) {
1448 // If there are no witnesses, erase the nullifier and associated mapping.
1449 if (item.second.nullifier) {
1450 mapSaplingNullifiersToNotes.erase(item.second.nullifier.get());
1452 item.second.nullifier = boost::none;
1455 uint64_t position = nd.witnesses.front().position();
1456 SaplingFullViewingKey fvk = mapSaplingFullViewingKeys.at(nd.ivk);
1457 OutputDescription output = wtx.vShieldedOutput[op.n];
1458 auto optPlaintext = SaplingNotePlaintext::decrypt(output.encCiphertext, nd.ivk, output.ephemeralKey, output.cm);
1459 if (!optPlaintext) {
1460 // An item in mapSaplingNoteData must have already been successfully decrypted,
1461 // otherwise the item would not exist in the first place.
1464 auto optNote = optPlaintext.get().note(nd.ivk);
1468 auto optNullifier = optNote.get().nullifier(fvk, position);
1469 if (!optNullifier) {
1470 // This should not happen. If it does, maybe the position has been corrupted or miscalculated?
1473 uint256 nullifier = optNullifier.get();
1474 mapSaplingNullifiersToNotes[nullifier] = op;
1475 item.second.nullifier = nullifier;
1481 * Iterate over transactions in a block and update the cached Sapling nullifiers
1482 * for transactions which belong to the wallet.
1484 void CWallet::UpdateSaplingNullifierNoteMapForBlock(const CBlock *pblock) {
1487 for (const CTransaction& tx : pblock->vtx) {
1488 auto hash = tx.GetHash();
1489 bool txIsOurs = mapWallet.count(hash);
1491 UpdateSaplingNullifierNoteMapWithTx(mapWallet[hash]);
1496 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb)
1498 uint256 hash = wtxIn.GetHash();
1500 if (fFromLoadWallet)
1502 mapWallet[hash] = wtxIn;
1503 mapWallet[hash].BindWallet(this);
1504 UpdateNullifierNoteMapWithTx(mapWallet[hash]);
1510 // Inserts only if not already there, returns tx inserted or tx found
1511 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
1512 CWalletTx& wtx = (*ret.first).second;
1513 wtx.BindWallet(this);
1514 UpdateNullifierNoteMapWithTx(wtx);
1515 bool fInsertedNew = ret.second;
1518 wtx.nTimeReceived = GetAdjustedTime();
1519 wtx.nOrderPos = IncOrderPosNext(pwalletdb);
1521 wtx.nTimeSmart = wtx.nTimeReceived;
1522 if (!wtxIn.hashBlock.IsNull())
1524 if (mapBlockIndex.count(wtxIn.hashBlock))
1526 int64_t latestNow = wtx.nTimeReceived;
1527 int64_t latestEntry = 0;
1529 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
1530 int64_t latestTolerated = latestNow + 300;
1531 std::list<CAccountingEntry> acentries;
1532 TxItems txOrdered = OrderedTxItems(acentries);
1533 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
1535 CWalletTx *const pwtx = (*it).second.first;
1538 CAccountingEntry *const pacentry = (*it).second.second;
1542 nSmartTime = pwtx->nTimeSmart;
1544 nSmartTime = pwtx->nTimeReceived;
1547 nSmartTime = pacentry->nTime;
1548 if (nSmartTime <= latestTolerated)
1550 latestEntry = nSmartTime;
1551 if (nSmartTime > latestNow)
1552 latestNow = nSmartTime;
1558 int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
1559 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
1562 LogPrintf("AddToWallet(): found %s in block %s not in index\n",
1563 wtxIn.GetHash().ToString(),
1564 wtxIn.hashBlock.ToString());
1569 bool fUpdated = false;
1573 if (!wtxIn.hashBlock.IsNull() && wtxIn.hashBlock != wtx.hashBlock)
1575 wtx.hashBlock = wtxIn.hashBlock;
1578 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
1580 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
1581 wtx.nIndex = wtxIn.nIndex;
1584 if (UpdatedNoteData(wtxIn, wtx)) {
1587 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
1589 wtx.fFromMe = wtxIn.fFromMe;
1595 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
1598 if (fInsertedNew || fUpdated)
1599 if (!wtx.WriteToDisk(pwalletdb))
1602 // Break debit/credit balance caches:
1605 // Notify UI of new or updated transaction
1606 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
1608 // notify an external script when a wallet transaction comes in or is updated
1609 std::string strCmd = GetArg("-walletnotify", "");
1611 if ( !strCmd.empty())
1613 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
1614 boost::thread t(runCommand, strCmd); // thread runs free
1621 bool CWallet::UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx)
1623 bool unchangedSproutFlag = (wtxIn.mapSproutNoteData.empty() || wtxIn.mapSproutNoteData == wtx.mapSproutNoteData);
1624 if (!unchangedSproutFlag) {
1625 auto tmp = wtxIn.mapSproutNoteData;
1626 // Ensure we keep any cached witnesses we may already have
1627 for (const std::pair <JSOutPoint, SproutNoteData> nd : wtx.mapSproutNoteData) {
1628 if (tmp.count(nd.first) && nd.second.witnesses.size() > 0) {
1629 tmp.at(nd.first).witnesses.assign(
1630 nd.second.witnesses.cbegin(), nd.second.witnesses.cend());
1632 tmp.at(nd.first).witnessHeight = nd.second.witnessHeight;
1634 // Now copy over the updated note data
1635 wtx.mapSproutNoteData = tmp;
1638 bool unchangedSaplingFlag = (wtxIn.mapSaplingNoteData.empty() || wtxIn.mapSaplingNoteData == wtx.mapSaplingNoteData);
1639 if (!unchangedSaplingFlag) {
1640 auto tmp = wtxIn.mapSaplingNoteData;
1641 // Ensure we keep any cached witnesses we may already have
1643 for (const std::pair <SaplingOutPoint, SaplingNoteData> nd : wtx.mapSaplingNoteData) {
1644 if (tmp.count(nd.first) && nd.second.witnesses.size() > 0) {
1645 tmp.at(nd.first).witnesses.assign(
1646 nd.second.witnesses.cbegin(), nd.second.witnesses.cend());
1648 tmp.at(nd.first).witnessHeight = nd.second.witnessHeight;
1651 // Now copy over the updated note data
1652 wtx.mapSaplingNoteData = tmp;
1655 return !unchangedSproutFlag || !unchangedSaplingFlag;
1659 * Add a transaction to the wallet, or update it.
1660 * pblock is optional, but should be provided if the transaction is known to be in a block.
1661 * If fUpdate is true, existing transactions will be updated.
1663 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
1666 AssertLockHeld(cs_wallet);
1667 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1668 if (fExisted && !fUpdate) return false;
1669 auto sproutNoteData = FindMySproutNotes(tx);
1670 auto saplingNoteDataAndAddressesToAdd = FindMySaplingNotes(tx);
1671 auto saplingNoteData = saplingNoteDataAndAddressesToAdd.first;
1672 auto addressesToAdd = saplingNoteDataAndAddressesToAdd.second;
1673 for (const auto &addressToAdd : addressesToAdd) {
1674 if (!AddSaplingIncomingViewingKey(addressToAdd.second, addressToAdd.first)) {
1678 if (fExisted || IsMine(tx) || IsFromMe(tx) || sproutNoteData.size() > 0 || saplingNoteData.size() > 0)
1680 CWalletTx wtx(this,tx);
1682 if (sproutNoteData.size() > 0) {
1683 wtx.SetSproutNoteData(sproutNoteData);
1686 if (saplingNoteData.size() > 0) {
1687 wtx.SetSaplingNoteData(saplingNoteData);
1690 // Get merkle branch if transaction was found in a block
1692 wtx.SetMerkleBranch(*pblock);
1694 // Do not flush the wallet here for performance reasons
1695 // this is safe, as in case of a crash, we rescan the necessary blocks on startup through our SetBestChain-mechanism
1696 CWalletDB walletdb(strWalletFile, "r+", false);
1698 return AddToWallet(wtx, false, &walletdb);
1704 void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
1706 LOCK2(cs_main, cs_wallet);
1707 if (!AddToWalletIfInvolvingMe(tx, pblock, true))
1708 return; // Not one of ours
1710 MarkAffectedTransactionsDirty(tx);
1713 void CWallet::MarkAffectedTransactionsDirty(const CTransaction& tx)
1715 // If a transaction changes 'conflicted' state, that changes the balance
1716 // available of the outputs it spends. So force those to be
1717 // recomputed, also:
1718 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1720 if (mapWallet.count(txin.prevout.hash))
1721 mapWallet[txin.prevout.hash].MarkDirty();
1723 for (const JSDescription& jsdesc : tx.vJoinSplit) {
1724 for (const uint256& nullifier : jsdesc.nullifiers) {
1725 if (mapSproutNullifiersToNotes.count(nullifier) &&
1726 mapWallet.count(mapSproutNullifiersToNotes[nullifier].hash)) {
1727 mapWallet[mapSproutNullifiersToNotes[nullifier].hash].MarkDirty();
1732 for (const SpendDescription &spend : tx.vShieldedSpend) {
1733 uint256 nullifier = spend.nullifier;
1734 if (mapSaplingNullifiersToNotes.count(nullifier) &&
1735 mapWallet.count(mapSaplingNullifiersToNotes[nullifier].hash)) {
1736 mapWallet[mapSaplingNullifiersToNotes[nullifier].hash].MarkDirty();
1741 void CWallet::EraseFromWallet(const uint256 &hash)
1747 if (mapWallet.erase(hash))
1748 CWalletDB(strWalletFile).EraseTx(hash);
1755 * Returns a nullifier if the SpendingKey is available
1756 * Throws std::runtime_error if the decryptor doesn't match this note
1758 boost::optional<uint256> CWallet::GetSproutNoteNullifier(const JSDescription &jsdesc,
1759 const libzcash::SproutPaymentAddress &address,
1760 const ZCNoteDecryption &dec,
1761 const uint256 &hSig,
1764 boost::optional<uint256> ret;
1765 auto note_pt = libzcash::SproutNotePlaintext::decrypt(
1767 jsdesc.ciphertexts[n],
1768 jsdesc.ephemeralKey,
1771 auto note = note_pt.note(address);
1773 // Check note plaintext against note commitment
1774 if (note.cm() != jsdesc.commitments[n]) {
1775 throw libzcash::note_decryption_failed();
1778 // SpendingKeys are only available if:
1779 // - We have them (this isn't a viewing key)
1780 // - The wallet is unlocked
1781 libzcash::SproutSpendingKey key;
1782 if (GetSproutSpendingKey(address, key)) {
1783 ret = note.nullifier(key);
1789 * Finds all output notes in the given transaction that have been sent to
1790 * PaymentAddresses in this wallet.
1792 * It should never be necessary to call this method with a CWalletTx, because
1793 * the result of FindMySproutNotes (for the addresses available at the time) will
1794 * already have been cached in CWalletTx.mapSproutNoteData.
1796 mapSproutNoteData_t CWallet::FindMySproutNotes(const CTransaction &tx) const
1798 LOCK(cs_SpendingKeyStore);
1799 uint256 hash = tx.GetHash();
1801 mapSproutNoteData_t noteData;
1802 for (size_t i = 0; i < tx.vJoinSplit.size(); i++) {
1803 auto hSig = tx.vJoinSplit[i].h_sig(*pzcashParams, tx.joinSplitPubKey);
1804 for (uint8_t j = 0; j < tx.vJoinSplit[i].ciphertexts.size(); j++) {
1805 for (const NoteDecryptorMap::value_type& item : mapNoteDecryptors) {
1807 auto address = item.first;
1808 JSOutPoint jsoutpt {hash, i, j};
1809 auto nullifier = GetSproutNoteNullifier(
1815 SproutNoteData nd {address, *nullifier};
1816 noteData.insert(std::make_pair(jsoutpt, nd));
1818 SproutNoteData nd {address};
1819 noteData.insert(std::make_pair(jsoutpt, nd));
1822 } catch (const note_decryption_failed &err) {
1823 // Couldn't decrypt with this decryptor
1824 } catch (const std::exception &exc) {
1825 // Unexpected failure
1826 LogPrintf("FindMySproutNotes(): Unexpected error while testing decrypt:\n");
1827 LogPrintf("%s\n", exc.what());
1837 * Finds all output notes in the given transaction that have been sent to
1838 * SaplingPaymentAddresses in this wallet.
1840 * It should never be necessary to call this method with a CWalletTx, because
1841 * the result of FindMySaplingNotes (for the addresses available at the time) will
1842 * already have been cached in CWalletTx.mapSaplingNoteData.
1844 std::pair<mapSaplingNoteData_t, SaplingIncomingViewingKeyMap> CWallet::FindMySaplingNotes(const CTransaction &tx) const
1846 LOCK(cs_SpendingKeyStore);
1847 uint256 hash = tx.GetHash();
1849 mapSaplingNoteData_t noteData;
1850 SaplingIncomingViewingKeyMap viewingKeysToAdd;
1852 // Protocol Spec: 4.19 Block Chain Scanning (Sapling)
1853 for (uint32_t i = 0; i < tx.vShieldedOutput.size(); ++i) {
1854 const OutputDescription output = tx.vShieldedOutput[i];
1855 for (auto it = mapSaplingFullViewingKeys.begin(); it != mapSaplingFullViewingKeys.end(); ++it) {
1856 SaplingIncomingViewingKey ivk = it->first;
1857 auto result = SaplingNotePlaintext::decrypt(output.encCiphertext, ivk, output.ephemeralKey, output.cm);
1861 auto address = ivk.address(result.get().d);
1862 if (address && mapSaplingIncomingViewingKeys.count(address.get()) == 0) {
1863 viewingKeysToAdd[address.get()] = ivk;
1865 // We don't cache the nullifier here as computing it requires knowledge of the note position
1866 // in the commitment tree, which can only be determined when the transaction has been mined.
1867 SaplingOutPoint op {hash, i};
1870 noteData.insert(std::make_pair(op, nd));
1875 return std::make_pair(noteData, viewingKeysToAdd);
1878 bool CWallet::IsSproutNullifierFromMe(const uint256& nullifier) const
1882 if (mapSproutNullifiersToNotes.count(nullifier) &&
1883 mapWallet.count(mapSproutNullifiersToNotes.at(nullifier).hash)) {
1890 bool CWallet::IsSaplingNullifierFromMe(const uint256& nullifier) const
1894 if (mapSaplingNullifiersToNotes.count(nullifier) &&
1895 mapWallet.count(mapSaplingNullifiersToNotes.at(nullifier).hash)) {
1902 void CWallet::GetSproutNoteWitnesses(std::vector<JSOutPoint> notes,
1903 std::vector<boost::optional<SproutWitness>>& witnesses,
1904 uint256 &final_anchor)
1907 witnesses.resize(notes.size());
1908 boost::optional<uint256> rt;
1910 for (JSOutPoint note : notes) {
1911 if (mapWallet.count(note.hash) &&
1912 mapWallet[note.hash].mapSproutNoteData.count(note) &&
1913 mapWallet[note.hash].mapSproutNoteData[note].witnesses.size() > 0) {
1914 witnesses[i] = mapWallet[note.hash].mapSproutNoteData[note].witnesses.front();
1916 rt = witnesses[i]->root();
1918 assert(*rt == witnesses[i]->root());
1923 // All returned witnesses have the same anchor
1929 void CWallet::GetSaplingNoteWitnesses(std::vector<SaplingOutPoint> notes,
1930 std::vector<boost::optional<SaplingWitness>>& witnesses,
1931 uint256 &final_anchor)
1934 witnesses.resize(notes.size());
1935 boost::optional<uint256> rt;
1937 for (SaplingOutPoint note : notes) {
1938 if (mapWallet.count(note.hash) &&
1939 mapWallet[note.hash].mapSaplingNoteData.count(note) &&
1940 mapWallet[note.hash].mapSaplingNoteData[note].witnesses.size() > 0) {
1941 witnesses[i] = mapWallet[note.hash].mapSaplingNoteData[note].witnesses.front();
1943 rt = witnesses[i]->root();
1945 assert(*rt == witnesses[i]->root());
1950 // All returned witnesses have the same anchor
1956 isminetype CWallet::IsMine(const CTxIn &txin) const
1960 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1961 if (mi != mapWallet.end())
1963 const CWalletTx& prev = (*mi).second;
1964 if (txin.prevout.n < prev.vout.size())
1965 return IsMine(prev.vout[txin.prevout.n]);
1971 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1975 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1976 if (mi != mapWallet.end())
1978 const CWalletTx& prev = (*mi).second;
1979 if (txin.prevout.n < prev.vout.size())
1980 if (IsMine(prev.vout[txin.prevout.n]) & filter)
1981 return prev.vout[txin.prevout.n].nValue;
1987 isminetype CWallet::IsMine(const CTxOut& txout) const
1989 return ::IsMine(*this, txout.scriptPubKey);
1992 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1994 if (!MoneyRange(txout.nValue))
1995 throw std::runtime_error("CWallet::GetCredit(): value out of range");
1996 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1999 bool CWallet::IsChange(const CTxOut& txout) const
2001 // TODO: fix handling of 'change' outputs. The assumption is that any
2002 // payment to a script that is ours, but is not in the address book
2003 // is change. That assumption is likely to break when we implement multisignature
2004 // wallets that return change back into a multi-signature-protected address;
2005 // a better way of identifying which outputs are 'the send' and which are
2006 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
2007 // which output, if any, was change).
2008 if (::IsMine(*this, txout.scriptPubKey))
2010 CTxDestination address;
2011 if (!ExtractDestination(txout.scriptPubKey, address))
2015 if (!mapAddressBook.count(address))
2021 CAmount CWallet::GetChange(const CTxOut& txout) const
2023 if (!MoneyRange(txout.nValue))
2024 throw std::runtime_error("CWallet::GetChange(): value out of range");
2025 return (IsChange(txout) ? txout.nValue : 0);
2028 bool CWallet::IsMine(const CTransaction& tx) const
2030 BOOST_FOREACH(const CTxOut& txout, tx.vout)
2036 bool CWallet::IsFromMe(const CTransaction& tx) const
2038 if (GetDebit(tx, ISMINE_ALL) > 0) {
2041 for (const JSDescription& jsdesc : tx.vJoinSplit) {
2042 for (const uint256& nullifier : jsdesc.nullifiers) {
2043 if (IsSproutNullifierFromMe(nullifier)) {
2048 for (const SpendDescription &spend : tx.vShieldedSpend) {
2049 if (IsSaplingNullifierFromMe(spend.nullifier)) {
2056 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
2059 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2061 nDebit += GetDebit(txin, filter);
2062 if (!MoneyRange(nDebit))
2063 throw std::runtime_error("CWallet::GetDebit(): value out of range");
2068 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
2070 CAmount nCredit = 0;
2071 BOOST_FOREACH(const CTxOut& txout, tx.vout)
2073 nCredit += GetCredit(txout, filter);
2074 if (!MoneyRange(nCredit))
2075 throw std::runtime_error("CWallet::GetCredit(): value out of range");
2080 CAmount CWallet::GetChange(const CTransaction& tx) const
2082 CAmount nChange = 0;
2083 BOOST_FOREACH(const CTxOut& txout, tx.vout)
2085 nChange += GetChange(txout);
2086 if (!MoneyRange(nChange))
2087 throw std::runtime_error("CWallet::GetChange(): value out of range");
2092 bool CWallet::IsHDFullyEnabled() const
2094 // Only Sapling addresses are HD for now
2098 void CWallet::GenerateNewSeed()
2102 auto seed = HDSeed::Random(HD_WALLET_SEED_LENGTH);
2104 int64_t nCreationTime = GetTime();
2106 // If the wallet is encrypted and locked, this will fail.
2107 if (!SetHDSeed(seed))
2108 throw std::runtime_error(std::string(__func__) + ": SetHDSeed failed");
2110 // store the key creation time together with
2111 // the child index counter in the database
2112 // as a hdchain object
2113 CHDChain newHdChain;
2114 newHdChain.nVersion = CHDChain::VERSION_HD_BASE;
2115 newHdChain.seedFp = seed.Fingerprint();
2116 newHdChain.nCreateTime = nCreationTime;
2117 SetHDChain(newHdChain, false);
2120 bool CWallet::SetHDSeed(const HDSeed& seed)
2122 if (!CCryptoKeyStore::SetHDSeed(seed)) {
2133 return CWalletDB(strWalletFile).WriteHDSeed(seed);
2139 bool CWallet::SetCryptedHDSeed(const uint256& seedFp, const std::vector<unsigned char> &vchCryptedSecret)
2141 if (!CCryptoKeyStore::SetCryptedHDSeed(seedFp, vchCryptedSecret)) {
2151 if (pwalletdbEncryption)
2152 return pwalletdbEncryption->WriteCryptedHDSeed(seedFp, vchCryptedSecret);
2154 return CWalletDB(strWalletFile).WriteCryptedHDSeed(seedFp, vchCryptedSecret);
2159 HDSeed CWallet::GetHDSeedForRPC() const {
2161 if (!pwalletMain->GetHDSeed(seed)) {
2162 throw JSONRPCError(RPC_WALLET_ERROR, "HD seed not found");
2167 void CWallet::SetHDChain(const CHDChain& chain, bool memonly)
2170 if (!memonly && fFileBacked && !CWalletDB(strWalletFile).WriteHDChain(chain))
2171 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
2176 bool CWallet::LoadHDSeed(const HDSeed& seed)
2178 return CBasicKeyStore::SetHDSeed(seed);
2181 bool CWallet::LoadCryptedHDSeed(const uint256& seedFp, const std::vector<unsigned char>& seed)
2183 return CCryptoKeyStore::SetCryptedHDSeed(seedFp, seed);
2186 void CWalletTx::SetSproutNoteData(mapSproutNoteData_t ¬eData)
2188 mapSproutNoteData.clear();
2189 for (const std::pair<JSOutPoint, SproutNoteData> nd : noteData) {
2190 if (nd.first.js < vJoinSplit.size() &&
2191 nd.first.n < vJoinSplit[nd.first.js].ciphertexts.size()) {
2192 // Store the address and nullifier for the Note
2193 mapSproutNoteData[nd.first] = nd.second;
2195 // If FindMySproutNotes() was used to obtain noteData,
2196 // this should never happen
2197 throw std::logic_error("CWalletTx::SetSproutNoteData(): Invalid note");
2202 void CWalletTx::SetSaplingNoteData(mapSaplingNoteData_t ¬eData)
2204 mapSaplingNoteData.clear();
2205 for (const std::pair<SaplingOutPoint, SaplingNoteData> nd : noteData) {
2206 if (nd.first.n < vShieldedOutput.size()) {
2207 mapSaplingNoteData[nd.first] = nd.second;
2209 throw std::logic_error("CWalletTx::SetSaplingNoteData(): Invalid note");
2214 int64_t CWalletTx::GetTxTime() const
2216 int64_t n = nTimeSmart;
2217 return n ? n : nTimeReceived;
2220 int CWalletTx::GetRequestCount() const
2222 // Returns -1 if it wasn't being tracked
2225 LOCK(pwallet->cs_wallet);
2229 if (!hashBlock.IsNull())
2231 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
2232 if (mi != pwallet->mapRequestCount.end())
2233 nRequests = (*mi).second;
2238 // Did anyone request this transaction?
2239 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
2240 if (mi != pwallet->mapRequestCount.end())
2242 nRequests = (*mi).second;
2244 // How about the block it's in?
2245 if (nRequests == 0 && !hashBlock.IsNull())
2247 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
2248 if (mi != pwallet->mapRequestCount.end())
2249 nRequests = (*mi).second;
2251 nRequests = 1; // If it's in someone else's block it must have got out
2259 // GetAmounts will determine the transparent debits and credits for a given wallet tx.
2260 void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
2261 list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
2264 listReceived.clear();
2266 strSentAccount = strFromAccount;
2268 // Is this tx sent/signed by me?
2269 CAmount nDebit = GetDebit(filter);
2270 bool isFromMyTaddr = nDebit > 0; // debit>0 means we signed/sent this transaction
2272 // Compute fee if we sent this transaction.
2273 if (isFromMyTaddr) {
2274 CAmount nValueOut = GetValueOut(); // transparent outputs plus all Sprout vpub_old and negative Sapling valueBalance
2275 CAmount nValueIn = GetShieldedValueIn();
2276 nFee = nDebit - nValueOut + nValueIn;
2279 // Create output entry for vpub_old/new, if we sent utxos from this transaction
2280 if (isFromMyTaddr) {
2281 CAmount myVpubOld = 0;
2282 CAmount myVpubNew = 0;
2283 for (const JSDescription& js : vJoinSplit) {
2284 bool fMyJSDesc = false;
2287 for (const uint256& nullifier : js.nullifiers) {
2288 if (pwallet->IsSproutNullifierFromMe(nullifier)) {
2294 // Check output side
2296 for (const std::pair<JSOutPoint, SproutNoteData> nd : this->mapSproutNoteData) {
2297 if (nd.first.js < vJoinSplit.size() && nd.first.n < vJoinSplit[nd.first.js].ciphertexts.size()) {
2305 myVpubOld += js.vpub_old;
2306 myVpubNew += js.vpub_new;
2309 if (!MoneyRange(js.vpub_old) || !MoneyRange(js.vpub_new) || !MoneyRange(myVpubOld) || !MoneyRange(myVpubNew)) {
2310 throw std::runtime_error("CWalletTx::GetAmounts: value out of range");
2314 // Create an output for the value taken from or added to the transparent value pool by JoinSplits
2315 if (myVpubOld > myVpubNew) {
2316 COutputEntry output = {CNoDestination(), myVpubOld - myVpubNew, (int)vout.size()};
2317 listSent.push_back(output);
2318 } else if (myVpubNew > myVpubOld) {
2319 COutputEntry output = {CNoDestination(), myVpubNew - myVpubOld, (int)vout.size()};
2320 listReceived.push_back(output);
2324 // If we sent utxos from this transaction, create output for value taken from (negative valueBalance)
2325 // or added (positive valueBalance) to the transparent value pool by Sapling shielding and unshielding.
2326 if (isFromMyTaddr) {
2327 if (valueBalance < 0) {
2328 COutputEntry output = {CNoDestination(), -valueBalance, (int) vout.size()};
2329 listSent.push_back(output);
2330 } else if (valueBalance > 0) {
2331 COutputEntry output = {CNoDestination(), valueBalance, (int) vout.size()};
2332 listReceived.push_back(output);
2337 for (unsigned int i = 0; i < vout.size(); ++i)
2339 const CTxOut& txout = vout[i];
2340 isminetype fIsMine = pwallet->IsMine(txout);
2341 // Only need to handle txouts if AT LEAST one of these is true:
2342 // 1) they debit from us (sent)
2343 // 2) the output is to us (received)
2346 // Don't report 'change' txouts
2347 if (pwallet->IsChange(txout))
2350 else if (!(fIsMine & filter))
2353 // In either case, we need to get the destination address
2354 CTxDestination address;
2355 if (!ExtractDestination(txout.scriptPubKey, address))
2357 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
2358 this->GetHash().ToString());
2359 address = CNoDestination();
2362 COutputEntry output = {address, txout.nValue, (int)i};
2364 // If we are debited by the transaction, add the output as a "sent" entry
2366 listSent.push_back(output);
2368 // If we are receiving the output, add it as a "received" entry
2369 if (fIsMine & filter)
2370 listReceived.push_back(output);
2375 void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
2376 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
2378 nReceived = nSent = nFee = 0;
2381 string strSentAccount;
2382 list<COutputEntry> listReceived;
2383 list<COutputEntry> listSent;
2384 GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
2386 if (strAccount == strSentAccount)
2388 BOOST_FOREACH(const COutputEntry& s, listSent)
2393 LOCK(pwallet->cs_wallet);
2394 BOOST_FOREACH(const COutputEntry& r, listReceived)
2396 if (pwallet->mapAddressBook.count(r.destination))
2398 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
2399 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
2400 nReceived += r.amount;
2402 else if (strAccount.empty())
2404 nReceived += r.amount;
2411 bool CWalletTx::WriteToDisk(CWalletDB *pwalletdb)
2413 return pwalletdb->WriteTx(GetHash(), *this);
2416 void CWallet::WitnessNoteCommitment(std::vector<uint256> commitments,
2417 std::vector<boost::optional<SproutWitness>>& witnesses,
2418 uint256 &final_anchor)
2420 witnesses.resize(commitments.size());
2421 CBlockIndex* pindex = chainActive.Genesis();
2422 SproutMerkleTree tree;
2426 ReadBlockFromDisk(block, pindex, Params().GetConsensus());
2428 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2430 BOOST_FOREACH(const JSDescription& jsdesc, tx.vJoinSplit)
2432 BOOST_FOREACH(const uint256 ¬e_commitment, jsdesc.commitments)
2434 tree.append(note_commitment);
2436 BOOST_FOREACH(boost::optional<SproutWitness>& wit, witnesses) {
2438 wit->append(note_commitment);
2443 BOOST_FOREACH(uint256& commitment, commitments) {
2444 if (note_commitment == commitment) {
2445 witnesses.at(i) = tree.witness();
2453 uint256 current_anchor = tree.root();
2455 // Consistency check: we should be able to find the current tree
2456 // in our CCoins view.
2457 SproutMerkleTree dummy_tree;
2458 assert(pcoinsTip->GetSproutAnchorAt(current_anchor, dummy_tree));
2460 pindex = chainActive.Next(pindex);
2463 // TODO: #93; Select a root via some heuristic.
2464 final_anchor = tree.root();
2466 BOOST_FOREACH(boost::optional<SproutWitness>& wit, witnesses) {
2468 assert(final_anchor == wit->root());
2474 * Scan the block chain (starting in pindexStart) for transactions
2475 * from or to us. If fUpdate is true, found transactions that already
2476 * exist in the wallet will be updated.
2478 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
2481 int64_t nNow = GetTime();
2482 const CChainParams& chainParams = Params();
2484 CBlockIndex* pindex = pindexStart;
2486 std::vector<uint256> myTxHashes;
2489 LOCK2(cs_main, cs_wallet);
2491 // no need to read and scan block, if block was created before
2492 // our wallet birthday (as adjusted for block time variability)
2493 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
2494 pindex = chainActive.Next(pindex);
2496 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
2497 double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
2498 double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip(), false);
2501 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
2502 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
2505 ReadBlockFromDisk(block, pindex, Params().GetConsensus());
2506 BOOST_FOREACH(CTransaction& tx, block.vtx)
2508 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) {
2509 myTxHashes.push_back(tx.GetHash());
2514 SproutMerkleTree sproutTree;
2515 SaplingMerkleTree saplingTree;
2516 // This should never fail: we should always be able to get the tree
2517 // state on the path to the tip of our chain
2518 assert(pcoinsTip->GetSproutAnchorAt(pindex->hashSproutAnchor, sproutTree));
2519 if (pindex->pprev) {
2520 if (Params().GetConsensus().NetworkUpgradeActive(pindex->pprev->nHeight, Consensus::UPGRADE_SAPLING)) {
2521 assert(pcoinsTip->GetSaplingAnchorAt(pindex->pprev->hashFinalSaplingRoot, saplingTree));
2524 // Increment note witness caches
2525 ChainTipAdded(pindex, &block, sproutTree, saplingTree);
2527 pindex = chainActive.Next(pindex);
2528 if (GetTime() >= nNow + 60) {
2530 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex));
2534 // After rescanning, persist Sapling note data that might have changed, e.g. nullifiers.
2535 // Do not flush the wallet here for performance reasons.
2536 CWalletDB walletdb(strWalletFile, "r+", false);
2537 for (auto hash : myTxHashes) {
2538 CWalletTx wtx = mapWallet[hash];
2539 if (!wtx.mapSaplingNoteData.empty()) {
2540 if (!wtx.WriteToDisk(&walletdb)) {
2541 LogPrintf("Rescanning... WriteToDisk failed to update Sapling note data for: %s\n", hash.ToString());
2546 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
2551 void CWallet::ReacceptWalletTransactions()
2553 // If transactions aren't being broadcasted, don't let them into local mempool either
2554 if (!fBroadcastTransactions)
2556 LOCK2(cs_main, cs_wallet);
2557 std::map<int64_t, CWalletTx*> mapSorted;
2559 // Sort pending wallet transactions based on their initial wallet insertion order
2560 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
2562 const uint256& wtxid = item.first;
2563 CWalletTx& wtx = item.second;
2564 assert(wtx.GetHash() == wtxid);
2566 int nDepth = wtx.GetDepthInMainChain();
2568 if (!wtx.IsCoinBase() && nDepth < 0) {
2569 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
2573 // Try to add wallet transactions to memory pool
2574 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
2576 CWalletTx& wtx = *(item.second);
2579 wtx.AcceptToMemoryPool(false);
2583 bool CWalletTx::RelayWalletTransaction()
2585 assert(pwallet->GetBroadcastTransactions());
2588 if (GetDepthInMainChain() == 0) {
2589 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
2590 RelayTransaction((CTransaction)*this);
2597 set<uint256> CWalletTx::GetConflicts() const
2599 set<uint256> result;
2600 if (pwallet != NULL)
2602 uint256 myHash = GetHash();
2603 result = pwallet->GetConflicts(myHash);
2604 result.erase(myHash);
2609 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
2615 if(filter & ISMINE_SPENDABLE)
2618 debit += nDebitCached;
2621 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
2622 fDebitCached = true;
2623 debit += nDebitCached;
2626 if(filter & ISMINE_WATCH_ONLY)
2628 if(fWatchDebitCached)
2629 debit += nWatchDebitCached;
2632 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
2633 fWatchDebitCached = true;
2634 debit += nWatchDebitCached;
2640 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
2642 // Must wait until coinbase is safely deep enough in the chain before valuing it
2643 if (IsCoinBase() && GetBlocksToMaturity() > 0)
2647 if (filter & ISMINE_SPENDABLE)
2649 // GetBalance can assume transactions in mapWallet won't change
2651 credit += nCreditCached;
2654 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
2655 fCreditCached = true;
2656 credit += nCreditCached;
2659 if (filter & ISMINE_WATCH_ONLY)
2661 if (fWatchCreditCached)
2662 credit += nWatchCreditCached;
2665 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
2666 fWatchCreditCached = true;
2667 credit += nWatchCreditCached;
2673 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
2675 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
2677 if (fUseCache && fImmatureCreditCached)
2678 return nImmatureCreditCached;
2679 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
2680 fImmatureCreditCached = true;
2681 return nImmatureCreditCached;
2687 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
2692 // Must wait until coinbase is safely deep enough in the chain before valuing it
2693 if (IsCoinBase() && GetBlocksToMaturity() > 0)
2696 if (fUseCache && fAvailableCreditCached)
2697 return nAvailableCreditCached;
2699 CAmount nCredit = 0;
2700 uint256 hashTx = GetHash();
2701 for (unsigned int i = 0; i < vout.size(); i++)
2703 if (!pwallet->IsSpent(hashTx, i))
2705 const CTxOut &txout = vout[i];
2706 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
2707 if (!MoneyRange(nCredit))
2708 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
2712 nAvailableCreditCached = nCredit;
2713 fAvailableCreditCached = true;
2717 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
2719 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
2721 if (fUseCache && fImmatureWatchCreditCached)
2722 return nImmatureWatchCreditCached;
2723 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
2724 fImmatureWatchCreditCached = true;
2725 return nImmatureWatchCreditCached;
2731 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
2736 // Must wait until coinbase is safely deep enough in the chain before valuing it
2737 if (IsCoinBase() && GetBlocksToMaturity() > 0)
2740 if (fUseCache && fAvailableWatchCreditCached)
2741 return nAvailableWatchCreditCached;
2743 CAmount nCredit = 0;
2744 for (unsigned int i = 0; i < vout.size(); i++)
2746 if (!pwallet->IsSpent(GetHash(), i))
2748 const CTxOut &txout = vout[i];
2749 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
2750 if (!MoneyRange(nCredit))
2751 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
2755 nAvailableWatchCreditCached = nCredit;
2756 fAvailableWatchCreditCached = true;
2760 CAmount CWalletTx::GetChange() const
2763 return nChangeCached;
2764 nChangeCached = pwallet->GetChange(*this);
2765 fChangeCached = true;
2766 return nChangeCached;
2769 bool CWalletTx::IsTrusted() const
2771 // Quick answer in most cases
2772 if (!CheckFinalTx(*this))
2774 int nDepth = GetDepthInMainChain();
2779 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
2782 // Trusted if all inputs are from us and are in the mempool:
2783 BOOST_FOREACH(const CTxIn& txin, vin)
2785 // Transactions not sent by us: not trusted
2786 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
2789 const CTxOut& parentOut = parent->vout[txin.prevout.n];
2790 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
2796 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
2798 std::vector<uint256> result;
2801 // Sort them in chronological order
2802 multimap<unsigned int, CWalletTx*> mapSorted;
2803 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
2805 CWalletTx& wtx = item.second;
2806 // Don't rebroadcast if newer than nTime:
2807 if (wtx.nTimeReceived > nTime)
2809 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
2811 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
2813 CWalletTx& wtx = *item.second;
2814 if (wtx.RelayWalletTransaction())
2815 result.push_back(wtx.GetHash());
2820 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
2822 // Do this infrequently and randomly to avoid giving away
2823 // that these are our transactions.
2824 if (GetTime() < nNextResend || !fBroadcastTransactions)
2826 bool fFirst = (nNextResend == 0);
2827 nNextResend = GetTime() + GetRand(30 * 60);
2831 // Only do it if there's been a new block since last time
2832 if (nBestBlockTime < nLastResend)
2834 nLastResend = GetTime();
2836 // Rebroadcast unconfirmed txes older than 5 minutes before the last
2838 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60);
2839 if (!relayed.empty())
2840 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
2843 /** @} */ // end of mapWallet
2848 /** @defgroup Actions
2854 CAmount CWallet::GetBalance() const
2858 LOCK2(cs_main, cs_wallet);
2859 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2861 const CWalletTx* pcoin = &(*it).second;
2862 if (pcoin->IsTrusted())
2863 nTotal += pcoin->GetAvailableCredit();
2870 CAmount CWallet::GetUnconfirmedBalance() const
2874 LOCK2(cs_main, cs_wallet);
2875 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2877 const CWalletTx* pcoin = &(*it).second;
2878 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
2879 nTotal += pcoin->GetAvailableCredit();
2885 CAmount CWallet::GetImmatureBalance() const
2889 LOCK2(cs_main, cs_wallet);
2890 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2892 const CWalletTx* pcoin = &(*it).second;
2893 nTotal += pcoin->GetImmatureCredit();
2899 CAmount CWallet::GetWatchOnlyBalance() const
2903 LOCK2(cs_main, cs_wallet);
2904 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2906 const CWalletTx* pcoin = &(*it).second;
2907 if (pcoin->IsTrusted())
2908 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2915 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2919 LOCK2(cs_main, cs_wallet);
2920 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2922 const CWalletTx* pcoin = &(*it).second;
2923 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
2924 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2930 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2934 LOCK2(cs_main, cs_wallet);
2935 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2937 const CWalletTx* pcoin = &(*it).second;
2938 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2945 * populate vCoins with vector of available COutputs.
2947 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue, bool fIncludeCoinBase) const
2952 LOCK2(cs_main, cs_wallet);
2953 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2955 const uint256& wtxid = it->first;
2956 const CWalletTx* pcoin = &(*it).second;
2958 if (!CheckFinalTx(*pcoin))
2961 if (fOnlyConfirmed && !pcoin->IsTrusted())
2964 if (pcoin->IsCoinBase() && !fIncludeCoinBase)
2967 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2970 int nDepth = pcoin->GetDepthInMainChain();
2974 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
2975 isminetype mine = IsMine(pcoin->vout[i]);
2976 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
2977 !IsLockedCoin((*it).first, i) && (pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
2978 (!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected((*it).first, i)))
2979 vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO));
2985 static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2986 vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2988 vector<char> vfIncluded;
2990 vfBest.assign(vValue.size(), true);
2991 nBest = nTotalLower;
2993 seed_insecure_rand();
2995 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2997 vfIncluded.assign(vValue.size(), false);
2999 bool fReachedTarget = false;
3000 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3002 for (unsigned int i = 0; i < vValue.size(); i++)
3004 //The solver here uses a randomized algorithm,
3005 //the randomness serves no real security purpose but is just
3006 //needed to prevent degenerate behavior and it is important
3007 //that the rng is fast. We do not use a constant random sequence,
3008 //because there may be some privacy improvement by making
3009 //the selection random.
3010 if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
3012 nTotal += vValue[i].first;
3013 vfIncluded[i] = true;
3014 if (nTotal >= nTargetValue)
3016 fReachedTarget = true;
3020 vfBest = vfIncluded;
3022 nTotal -= vValue[i].first;
3023 vfIncluded[i] = false;
3031 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
3032 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
3034 setCoinsRet.clear();
3037 // List of values less than target
3038 pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
3039 coinLowestLarger.first = std::numeric_limits<CAmount>::max();
3040 coinLowestLarger.second.first = NULL;
3041 vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
3042 CAmount nTotalLower = 0;
3044 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3046 BOOST_FOREACH(const COutput &output, vCoins)
3048 if (!output.fSpendable)
3051 const CWalletTx *pcoin = output.tx;
3053 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
3057 CAmount n = pcoin->vout[i].nValue;
3059 pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
3061 if (n == nTargetValue)
3063 setCoinsRet.insert(coin.second);
3064 nValueRet += coin.first;
3067 else if (n < nTargetValue + CENT)
3069 vValue.push_back(coin);
3072 else if (n < coinLowestLarger.first)
3074 coinLowestLarger = coin;
3078 if (nTotalLower == nTargetValue)
3080 for (unsigned int i = 0; i < vValue.size(); ++i)
3082 setCoinsRet.insert(vValue[i].second);
3083 nValueRet += vValue[i].first;
3088 if (nTotalLower < nTargetValue)
3090 if (coinLowestLarger.second.first == NULL)
3092 setCoinsRet.insert(coinLowestLarger.second);
3093 nValueRet += coinLowestLarger.first;
3097 // Solve subset sum by stochastic approximation
3098 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
3099 vector<char> vfBest;
3102 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
3103 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
3104 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
3106 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
3107 // or the next bigger coin is closer), return the bigger coin
3108 if (coinLowestLarger.second.first &&
3109 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
3111 setCoinsRet.insert(coinLowestLarger.second);
3112 nValueRet += coinLowestLarger.first;
3115 for (unsigned int i = 0; i < vValue.size(); i++)
3118 setCoinsRet.insert(vValue[i].second);
3119 nValueRet += vValue[i].first;
3122 LogPrint("selectcoins", "SelectCoins() best subset: ");
3123 for (unsigned int i = 0; i < vValue.size(); i++)
3125 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
3126 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
3132 bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, bool& fOnlyCoinbaseCoinsRet, bool& fNeedCoinbaseCoinsRet, const CCoinControl* coinControl) const
3134 // Output parameter fOnlyCoinbaseCoinsRet is set to true when the only available coins are coinbase utxos.
3135 vector<COutput> vCoinsNoCoinbase, vCoinsWithCoinbase;
3136 AvailableCoins(vCoinsNoCoinbase, true, coinControl, false, false);
3137 AvailableCoins(vCoinsWithCoinbase, true, coinControl, false, true);
3138 fOnlyCoinbaseCoinsRet = vCoinsNoCoinbase.size() == 0 && vCoinsWithCoinbase.size() > 0;
3140 // If coinbase utxos can only be sent to zaddrs, exclude any coinbase utxos from coin selection.
3141 bool fProtectCoinbase = Params().GetConsensus().fCoinbaseMustBeProtected;
3142 vector<COutput> vCoins = (fProtectCoinbase) ? vCoinsNoCoinbase : vCoinsWithCoinbase;
3144 // Output parameter fNeedCoinbaseCoinsRet is set to true if coinbase utxos need to be spent to meet target amount
3145 if (fProtectCoinbase && vCoinsWithCoinbase.size() > vCoinsNoCoinbase.size()) {
3147 for (const COutput& out : vCoinsNoCoinbase) {
3148 if (!out.fSpendable) {
3151 value += out.tx->vout[out.i].nValue;
3153 if (value <= nTargetValue) {
3154 CAmount valueWithCoinbase = 0;
3155 for (const COutput& out : vCoinsWithCoinbase) {
3156 if (!out.fSpendable) {
3159 valueWithCoinbase += out.tx->vout[out.i].nValue;
3161 fNeedCoinbaseCoinsRet = (valueWithCoinbase >= nTargetValue);
3165 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
3166 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
3168 BOOST_FOREACH(const COutput& out, vCoins)
3170 if (!out.fSpendable)
3172 nValueRet += out.tx->vout[out.i].nValue;
3173 setCoinsRet.insert(make_pair(out.tx, out.i));
3175 return (nValueRet >= nTargetValue);
3178 // calculate value from preset inputs and store them
3179 set<pair<const CWalletTx*, uint32_t> > setPresetCoins;
3180 CAmount nValueFromPresetInputs = 0;
3182 std::vector<COutPoint> vPresetInputs;
3184 coinControl->ListSelected(vPresetInputs);
3185 BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
3187 map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
3188 if (it != mapWallet.end())
3190 const CWalletTx* pcoin = &it->second;
3191 // Clearly invalid input, fail
3192 if (pcoin->vout.size() <= outpoint.n)
3194 nValueFromPresetInputs += pcoin->vout[outpoint.n].nValue;
3195 setPresetCoins.insert(make_pair(pcoin, outpoint.n));
3197 return false; // TODO: Allow non-wallet inputs
3200 // remove preset inputs from vCoins
3201 for (vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
3203 if (setPresetCoins.count(make_pair(it->tx, it->i)))
3204 it = vCoins.erase(it);
3209 bool res = nTargetValue <= nValueFromPresetInputs ||
3210 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, vCoins, setCoinsRet, nValueRet) ||
3211 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, vCoins, setCoinsRet, nValueRet) ||
3212 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, vCoins, setCoinsRet, nValueRet));
3214 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
3215 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
3217 // add preset inputs to the total value selected
3218 nValueRet += nValueFromPresetInputs;
3223 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount &nFeeRet, int& nChangePosRet, std::string& strFailReason)
3225 vector<CRecipient> vecSend;
3227 // Turn the txout set into a CRecipient vector
3228 BOOST_FOREACH(const CTxOut& txOut, tx.vout)
3230 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, false};
3231 vecSend.push_back(recipient);
3234 CCoinControl coinControl;
3235 coinControl.fAllowOtherInputs = true;
3236 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3237 coinControl.Select(txin.prevout);
3239 CReserveKey reservekey(this);
3242 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosRet, strFailReason, &coinControl, false))
3245 if (nChangePosRet != -1)
3246 tx.vout.insert(tx.vout.begin() + nChangePosRet, wtx.vout[nChangePosRet]);
3248 // Add new txins (keeping original txin scriptSig/order)
3249 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
3252 BOOST_FOREACH(const CTxIn& origTxIn, tx.vin)
3254 if (txin.prevout.hash == origTxIn.prevout.hash && txin.prevout.n == origTxIn.prevout.n)
3261 tx.vin.push_back(txin);
3267 bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
3268 int& nChangePosRet, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
3271 unsigned int nSubtractFeeFromAmount = 0;
3272 BOOST_FOREACH (const CRecipient& recipient, vecSend)
3274 if (nValue < 0 || recipient.nAmount < 0)
3276 strFailReason = _("Transaction amounts must be positive");
3279 nValue += recipient.nAmount;
3281 if (recipient.fSubtractFeeFromAmount)
3282 nSubtractFeeFromAmount++;
3284 if (vecSend.empty() || nValue < 0)
3286 strFailReason = _("Transaction amounts must be positive");
3290 wtxNew.fTimeReceivedIsTxTime = true;
3291 wtxNew.BindWallet(this);
3292 int nextBlockHeight = chainActive.Height() + 1;
3293 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(
3294 Params().GetConsensus(), nextBlockHeight);
3296 // Activates after Overwinter network upgrade
3297 if (Params().GetConsensus().NetworkUpgradeActive(nextBlockHeight, Consensus::UPGRADE_OVERWINTER)) {
3298 if (txNew.nExpiryHeight >= TX_EXPIRY_HEIGHT_THRESHOLD){
3299 strFailReason = _("nExpiryHeight must be less than TX_EXPIRY_HEIGHT_THRESHOLD.");
3304 unsigned int max_tx_size = MAX_TX_SIZE_AFTER_SAPLING;
3305 if (!Params().GetConsensus().NetworkUpgradeActive(nextBlockHeight, Consensus::UPGRADE_SAPLING)) {
3306 max_tx_size = MAX_TX_SIZE_BEFORE_SAPLING;
3309 // Discourage fee sniping.
3311 // However because of a off-by-one-error in previous versions we need to
3312 // neuter it by setting nLockTime to at least one less than nBestHeight.
3313 // Secondly currently propagation of transactions created for block heights
3314 // corresponding to blocks that were just mined may be iffy - transactions
3315 // aren't re-accepted into the mempool - we additionally neuter the code by
3316 // going ten blocks back. Doesn't yet do anything for sniping, but does act
3317 // to shake out wallet bugs like not showing nLockTime'd transactions at
3319 txNew.nLockTime = std::max(0, chainActive.Height() - 10);
3321 // Secondly occasionally randomly pick a nLockTime even further back, so
3322 // that transactions that are delayed after signing for whatever reason,
3323 // e.g. high-latency mix networks and some CoinJoin implementations, have
3325 if (GetRandInt(10) == 0)
3326 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
3328 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
3329 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
3332 LOCK2(cs_main, cs_wallet);
3339 wtxNew.fFromMe = true;
3343 CAmount nTotalValue = nValue;
3344 if (nSubtractFeeFromAmount == 0)
3345 nTotalValue += nFeeRet;
3346 double dPriority = 0;
3347 // vouts to the payees
3348 BOOST_FOREACH (const CRecipient& recipient, vecSend)
3350 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
3352 if (recipient.fSubtractFeeFromAmount)
3354 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
3356 if (fFirst) // first receiver pays the remainder not divisible by output count
3359 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
3363 if (txout.IsDust(::minRelayTxFee))
3365 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
3367 if (txout.nValue < 0)
3368 strFailReason = _("The transaction amount is too small to pay the fee");
3370 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
3373 strFailReason = _("Transaction amount too small");
3376 txNew.vout.push_back(txout);
3379 // Choose coins to use
3380 set<pair<const CWalletTx*,unsigned int> > setCoins;
3381 CAmount nValueIn = 0;
3382 bool fOnlyCoinbaseCoins = false;
3383 bool fNeedCoinbaseCoins = false;
3384 if (!SelectCoins(nTotalValue, setCoins, nValueIn, fOnlyCoinbaseCoins, fNeedCoinbaseCoins, coinControl))
3386 if (fOnlyCoinbaseCoins && Params().GetConsensus().fCoinbaseMustBeProtected) {
3387 strFailReason = _("Coinbase funds can only be sent to a zaddr");
3388 } else if (fNeedCoinbaseCoins) {
3389 strFailReason = _("Insufficient funds, coinbase funds can only be spent after they have been sent to a zaddr");
3391 strFailReason = _("Insufficient funds");
3395 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
3397 CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
3398 //The coin age after the next block (depth+1) is used instead of the current,
3399 //reflecting an assumption the user would accept a bit more delay for
3400 //a chance at a free transaction.
3401 //But mempool inputs might still be in the mempool, so their age stays 0
3402 int age = pcoin.first->GetDepthInMainChain();
3405 dPriority += (double)nCredit * age;
3408 CAmount nChange = nValueIn - nValue;
3409 if (nSubtractFeeFromAmount == 0)
3414 // Fill a vout to ourself
3415 // TODO: pass in scriptChange instead of reservekey so
3416 // change transaction isn't always pay-to-bitcoin-address
3417 CScript scriptChange;
3419 // coin control: send change to custom address
3420 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
3421 scriptChange = GetScriptForDestination(coinControl->destChange);
3423 // no coin control: send change to newly generated address
3426 // Note: We use a new key here to keep it from being obvious which side is the change.
3427 // The drawback is that by not reusing a previous key, the change may be lost if a
3428 // backup is restored, if the backup doesn't have the new private key for the change.
3429 // If we reused the old key, it would be possible to add code to look for and
3430 // rediscover unknown transactions that were written with keys of ours to recover
3431 // post-backup change.
3433 // Reserve a new key pair from key pool
3436 ret = reservekey.GetReservedKey(vchPubKey);
3437 assert(ret); // should never fail, as we just unlocked
3439 scriptChange = GetScriptForDestination(vchPubKey.GetID());
3442 CTxOut newTxOut(nChange, scriptChange);
3444 // We do not move dust-change to fees, because the sender would end up paying more than requested.
3445 // This would be against the purpose of the all-inclusive feature.
3446 // So instead we raise the change and deduct from the recipient.
3447 if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust(::minRelayTxFee))
3449 CAmount nDust = newTxOut.GetDustThreshold(::minRelayTxFee) - newTxOut.nValue;
3450 newTxOut.nValue += nDust; // raise change until no more dust
3451 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
3453 if (vecSend[i].fSubtractFeeFromAmount)
3455 txNew.vout[i].nValue -= nDust;
3456 if (txNew.vout[i].IsDust(::minRelayTxFee))
3458 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
3466 // Never create dust outputs; if we would, just
3467 // add the dust to the fee.
3468 if (newTxOut.IsDust(::minRelayTxFee))
3471 reservekey.ReturnKey();
3475 // Insert change txn at random position:
3476 nChangePosRet = GetRandInt(txNew.vout.size()+1);
3477 vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosRet;
3478 txNew.vout.insert(position, newTxOut);
3482 reservekey.ReturnKey();
3486 // Note how the sequence number is set to max()-1 so that the
3487 // nLockTime set above actually works.
3488 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
3489 txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
3490 std::numeric_limits<unsigned int>::max()-1));
3492 // Check mempooltxinputlimit to avoid creating a transaction which the local mempool rejects
3493 size_t limit = (size_t)GetArg("-mempooltxinputlimit", 0);
3496 if (Params().GetConsensus().NetworkUpgradeActive(chainActive.Height() + 1, Consensus::UPGRADE_OVERWINTER)) {
3501 size_t n = txNew.vin.size();
3503 strFailReason = _(strprintf("Too many transparent inputs %zu > limit %zu", n, limit).c_str());
3508 // Grab the current consensus branch ID
3509 auto consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus());
3513 CTransaction txNewConst(txNew);
3514 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
3517 const CScript& scriptPubKey = coin.first->vout[coin.second].scriptPubKey;
3518 SignatureData sigdata;
3520 signSuccess = ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.first->vout[coin.second].nValue, SIGHASH_ALL), scriptPubKey, sigdata, consensusBranchId);
3522 signSuccess = ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata, consensusBranchId);
3526 strFailReason = _("Signing transaction failed");
3529 UpdateTransaction(txNew, nIn, sigdata);
3535 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
3537 // Remove scriptSigs if we used dummy signatures for fee calculation
3539 BOOST_FOREACH (CTxIn& vin, txNew.vin)
3540 vin.scriptSig = CScript();
3543 // Embed the constructed transaction data in wtxNew.
3544 *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
3547 if (nBytes >= max_tx_size)
3549 strFailReason = _("Transaction too large");
3553 dPriority = wtxNew.ComputePriority(dPriority, nBytes);
3555 // Can we complete this as a free transaction?
3556 if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
3558 // Not enough fee: enough priority?
3559 double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
3560 // Not enough mempool history to estimate: use hard-coded AllowFree.
3561 if (dPriorityNeeded <= 0 && AllowFree(dPriority))
3564 // Small enough, and priority high enough, to send for free
3565 if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
3569 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
3571 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
3572 // because we must be at the maximum allowed fee.
3573 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
3575 strFailReason = _("Transaction too large for fee policy");
3579 if (nFeeRet >= nFeeNeeded)
3580 break; // Done, enough fee included.
3582 // Include more fee and try again.
3583 nFeeRet = nFeeNeeded;
3593 * Call after CreateTransaction unless you want to abort
3595 bool CWallet::CommitTransaction(CWalletTx& wtxNew, boost::optional<CReserveKey&> reservekey)
3598 LOCK2(cs_main, cs_wallet);
3599 LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
3601 // This is only to keep the database open to defeat the auto-flush for the
3602 // duration of this scope. This is the only place where this optimization
3603 // maybe makes sense; please don't do it anywhere else.
3604 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r+") : NULL;
3607 // Take key pair from key pool so it won't be used again
3608 reservekey.get().KeepKey();
3611 // Add tx to wallet, because if it has change it's also ours,
3612 // otherwise just for transaction history.
3613 AddToWallet(wtxNew, false, pwalletdb);
3615 // Notify that old coins are spent
3616 set<CWalletTx*> setCoins;
3617 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
3619 CWalletTx &coin = mapWallet[txin.prevout.hash];
3620 coin.BindWallet(this);
3621 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
3628 // Track how many getdata requests our transaction gets
3629 mapRequestCount[wtxNew.GetHash()] = 0;
3631 if (fBroadcastTransactions)
3634 if (!wtxNew.AcceptToMemoryPool(false))
3636 // This must not fail. The transaction has already been signed and recorded.
3637 LogPrintf("CommitTransaction(): Error: Transaction not valid\n");
3640 wtxNew.RelayWalletTransaction();
3646 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
3648 // payTxFee is user-set "I want to pay this much"
3649 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
3650 // user selected total at least (default=true)
3651 if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
3652 nFeeNeeded = payTxFee.GetFeePerK();
3653 // User didn't set: use -txconfirmtarget to estimate...
3654 if (nFeeNeeded == 0)
3655 nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
3656 // ... unless we don't have enough mempool data, in which case fall
3657 // back to a hard-coded fee
3658 if (nFeeNeeded == 0)
3659 nFeeNeeded = minTxFee.GetFee(nTxBytes);
3660 // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
3661 if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
3662 nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
3663 // But always obey the maximum
3664 if (nFeeNeeded > maxTxFee)
3665 nFeeNeeded = maxTxFee;
3672 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3676 fFirstRunRet = false;
3677 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
3678 if (nLoadWalletRet == DB_NEED_REWRITE)
3680 if (CDB::Rewrite(strWalletFile, "\x04pool"))
3684 // Note: can't top-up keypool here, because wallet is locked.
3685 // User will be prompted to unlock wallet the next operation
3686 // that requires a new key.
3690 if (nLoadWalletRet != DB_LOAD_OK)
3691 return nLoadWalletRet;
3692 fFirstRunRet = !vchDefaultKey.IsValid();
3694 uiInterface.LoadWallet(this);
3700 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3704 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
3705 if (nZapWalletTxRet == DB_NEED_REWRITE)
3707 if (CDB::Rewrite(strWalletFile, "\x04pool"))
3711 // Note: can't top-up keypool here, because wallet is locked.
3712 // User will be prompted to unlock wallet the next operation
3713 // that requires a new key.
3717 if (nZapWalletTxRet != DB_LOAD_OK)
3718 return nZapWalletTxRet;
3724 bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
3726 bool fUpdated = false;
3728 LOCK(cs_wallet); // mapAddressBook
3729 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3730 fUpdated = mi != mapAddressBook.end();
3731 mapAddressBook[address].name = strName;
3732 if (!strPurpose.empty()) /* update purpose only if requested */
3733 mapAddressBook[address].purpose = strPurpose;
3735 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3736 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3739 if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(EncodeDestination(address), strPurpose))
3741 return CWalletDB(strWalletFile).WriteName(EncodeDestination(address), strName);
3744 bool CWallet::DelAddressBook(const CTxDestination& address)
3747 LOCK(cs_wallet); // mapAddressBook
3751 // Delete destdata tuples associated with address
3752 std::string strAddress = EncodeDestination(address);
3753 BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
3755 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
3758 mapAddressBook.erase(address);
3761 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3765 CWalletDB(strWalletFile).ErasePurpose(EncodeDestination(address));
3766 return CWalletDB(strWalletFile).EraseName(EncodeDestination(address));
3769 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3773 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
3776 vchDefaultKey = vchPubKey;
3781 * Mark old keypool keys as used,
3782 * and generate all new keys
3784 bool CWallet::NewKeyPool()
3788 CWalletDB walletdb(strWalletFile);
3789 BOOST_FOREACH(int64_t nIndex, setKeyPool)
3790 walletdb.ErasePool(nIndex);
3796 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
3797 for (int i = 0; i < nKeys; i++)
3799 int64_t nIndex = i+1;
3800 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
3801 setKeyPool.insert(nIndex);
3803 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
3808 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3816 CWalletDB walletdb(strWalletFile);
3819 unsigned int nTargetSize;
3821 nTargetSize = kpSize;
3823 nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0);
3825 while (setKeyPool.size() < (nTargetSize + 1))
3828 if (!setKeyPool.empty())
3829 nEnd = *(--setKeyPool.end()) + 1;
3830 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
3831 throw runtime_error("TopUpKeyPool(): writing generated key failed");
3832 setKeyPool.insert(nEnd);
3833 LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
3839 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
3842 keypool.vchPubKey = CPubKey();
3849 // Get the oldest key
3850 if(setKeyPool.empty())
3853 CWalletDB walletdb(strWalletFile);
3855 nIndex = *(setKeyPool.begin());
3856 setKeyPool.erase(setKeyPool.begin());
3857 if (!walletdb.ReadPool(nIndex, keypool))
3858 throw runtime_error("ReserveKeyFromKeyPool(): read failed");
3859 if (!HaveKey(keypool.vchPubKey.GetID()))
3860 throw runtime_error("ReserveKeyFromKeyPool(): unknown key in key pool");
3861 assert(keypool.vchPubKey.IsValid());
3862 LogPrintf("keypool reserve %d\n", nIndex);
3866 void CWallet::KeepKey(int64_t nIndex)
3868 // Remove from key pool
3871 CWalletDB walletdb(strWalletFile);
3872 walletdb.ErasePool(nIndex);
3874 LogPrintf("keypool keep %d\n", nIndex);
3877 void CWallet::ReturnKey(int64_t nIndex)
3879 // Return to key pool
3882 setKeyPool.insert(nIndex);
3884 LogPrintf("keypool return %d\n", nIndex);
3887 bool CWallet::GetKeyFromPool(CPubKey& result)
3893 ReserveKeyFromKeyPool(nIndex, keypool);
3896 if (IsLocked()) return false;
3897 result = GenerateNewKey();
3901 result = keypool.vchPubKey;
3906 int64_t CWallet::GetOldestKeyPoolTime()
3910 ReserveKeyFromKeyPool(nIndex, keypool);
3914 return keypool.nTime;
3917 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3919 map<CTxDestination, CAmount> balances;
3923 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3925 CWalletTx *pcoin = &walletEntry.second;
3927 if (!CheckFinalTx(*pcoin) || !pcoin->IsTrusted())
3930 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3933 int nDepth = pcoin->GetDepthInMainChain();
3934 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3937 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
3939 CTxDestination addr;
3940 if (!IsMine(pcoin->vout[i]))
3942 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
3945 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
3947 if (!balances.count(addr))
3949 balances[addr] += n;
3957 set< set<CTxDestination> > CWallet::GetAddressGroupings()
3959 AssertLockHeld(cs_wallet); // mapWallet
3960 set< set<CTxDestination> > groupings;
3961 set<CTxDestination> grouping;
3963 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3965 CWalletTx *pcoin = &walletEntry.second;
3967 if (pcoin->vin.size() > 0)
3969 bool any_mine = false;
3970 // group all input addresses with each other
3971 BOOST_FOREACH(CTxIn txin, pcoin->vin)
3973 CTxDestination address;
3974 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3976 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
3978 grouping.insert(address);
3982 // group change with input addresses
3985 BOOST_FOREACH(CTxOut txout, pcoin->vout)
3986 if (IsChange(txout))
3988 CTxDestination txoutAddr;
3989 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3991 grouping.insert(txoutAddr);
3994 if (grouping.size() > 0)
3996 groupings.insert(grouping);
4001 // group lone addrs by themselves
4002 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
4003 if (IsMine(pcoin->vout[i]))
4005 CTxDestination address;
4006 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
4008 grouping.insert(address);
4009 groupings.insert(grouping);
4014 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
4015 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
4016 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
4018 // make a set of all the groups hit by this new group
4019 set< set<CTxDestination>* > hits;
4020 map< CTxDestination, set<CTxDestination>* >::iterator it;
4021 BOOST_FOREACH(CTxDestination address, grouping)
4022 if ((it = setmap.find(address)) != setmap.end())
4023 hits.insert((*it).second);
4025 // merge all hit groups into a new single group and delete old groups
4026 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
4027 BOOST_FOREACH(set<CTxDestination>* hit, hits)
4029 merged->insert(hit->begin(), hit->end());
4030 uniqueGroupings.erase(hit);
4033 uniqueGroupings.insert(merged);
4036 BOOST_FOREACH(CTxDestination element, *merged)
4037 setmap[element] = merged;
4040 set< set<CTxDestination> > ret;
4041 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
4043 ret.insert(*uniqueGrouping);
4044 delete uniqueGrouping;
4050 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
4053 set<CTxDestination> result;
4054 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
4056 const CTxDestination& address = item.first;
4057 const string& strName = item.second.name;
4058 if (strName == strAccount)
4059 result.insert(address);
4064 bool CReserveKey::GetReservedKey(CPubKey& pubkey)
4069 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
4071 vchPubKey = keypool.vchPubKey;
4076 assert(vchPubKey.IsValid());
4081 void CReserveKey::KeepKey()
4084 pwallet->KeepKey(nIndex);
4086 vchPubKey = CPubKey();
4089 void CReserveKey::ReturnKey()
4092 pwallet->ReturnKey(nIndex);
4094 vchPubKey = CPubKey();
4097 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
4101 CWalletDB walletdb(strWalletFile);
4103 LOCK2(cs_main, cs_wallet);
4104 BOOST_FOREACH(const int64_t& id, setKeyPool)
4107 if (!walletdb.ReadPool(id, keypool))
4108 throw runtime_error("GetAllReserveKeyHashes(): read failed");
4109 assert(keypool.vchPubKey.IsValid());
4110 CKeyID keyID = keypool.vchPubKey.GetID();
4111 if (!HaveKey(keyID))
4112 throw runtime_error("GetAllReserveKeyHashes(): unknown key in key pool");
4113 setAddress.insert(keyID);
4117 void CWallet::UpdatedTransaction(const uint256 &hashTx)
4121 // Only notify UI if this transaction is in this wallet
4122 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
4123 if (mi != mapWallet.end())
4124 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
4128 void CWallet::GetScriptForMining(boost::shared_ptr<CReserveScript> &script)
4130 if (!GetArg("-mineraddress", "").empty()) {
4134 boost::shared_ptr<CReserveKey> rKey(new CReserveKey(this));
4136 if (!rKey->GetReservedKey(pubkey))
4140 script->reserveScript = CScript() << OP_DUP << OP_HASH160 << ToByteVector(pubkey.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG;
4143 void CWallet::LockCoin(COutPoint& output)
4145 AssertLockHeld(cs_wallet); // setLockedCoins
4146 setLockedCoins.insert(output);
4149 void CWallet::UnlockCoin(COutPoint& output)
4151 AssertLockHeld(cs_wallet); // setLockedCoins
4152 setLockedCoins.erase(output);
4155 void CWallet::UnlockAllCoins()
4157 AssertLockHeld(cs_wallet); // setLockedCoins
4158 setLockedCoins.clear();
4161 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
4163 AssertLockHeld(cs_wallet); // setLockedCoins
4164 COutPoint outpt(hash, n);
4166 return (setLockedCoins.count(outpt) > 0);
4169 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
4171 AssertLockHeld(cs_wallet); // setLockedCoins
4172 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
4173 it != setLockedCoins.end(); it++) {
4174 COutPoint outpt = (*it);
4175 vOutpts.push_back(outpt);
4180 // Note Locking Operations
4182 void CWallet::LockNote(const JSOutPoint& output)
4184 AssertLockHeld(cs_wallet); // setLockedSproutNotes
4185 setLockedSproutNotes.insert(output);
4188 void CWallet::UnlockNote(const JSOutPoint& output)
4190 AssertLockHeld(cs_wallet); // setLockedSproutNotes
4191 setLockedSproutNotes.erase(output);
4194 void CWallet::UnlockAllSproutNotes()
4196 AssertLockHeld(cs_wallet); // setLockedSproutNotes
4197 setLockedSproutNotes.clear();
4200 bool CWallet::IsLockedNote(const JSOutPoint& outpt) const
4202 AssertLockHeld(cs_wallet); // setLockedSproutNotes
4204 return (setLockedSproutNotes.count(outpt) > 0);
4207 std::vector<JSOutPoint> CWallet::ListLockedSproutNotes()
4209 AssertLockHeld(cs_wallet); // setLockedSproutNotes
4210 std::vector<JSOutPoint> vOutpts(setLockedSproutNotes.begin(), setLockedSproutNotes.end());
4214 void CWallet::LockNote(const SaplingOutPoint& output)
4216 AssertLockHeld(cs_wallet);
4217 setLockedSaplingNotes.insert(output);
4220 void CWallet::UnlockNote(const SaplingOutPoint& output)
4222 AssertLockHeld(cs_wallet);
4223 setLockedSaplingNotes.erase(output);
4226 void CWallet::UnlockAllSaplingNotes()
4228 AssertLockHeld(cs_wallet);
4229 setLockedSaplingNotes.clear();
4232 bool CWallet::IsLockedNote(const SaplingOutPoint& output) const
4234 AssertLockHeld(cs_wallet);
4235 return (setLockedSaplingNotes.count(output) > 0);
4238 std::vector<SaplingOutPoint> CWallet::ListLockedSaplingNotes()
4240 AssertLockHeld(cs_wallet);
4241 std::vector<SaplingOutPoint> vOutputs(setLockedSaplingNotes.begin(), setLockedSaplingNotes.end());
4245 /** @} */ // end of Actions
4247 class CAffectedKeysVisitor : public boost::static_visitor<void> {
4249 const CKeyStore &keystore;
4250 std::vector<CKeyID> &vKeys;
4253 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
4255 void Process(const CScript &script) {
4257 std::vector<CTxDestination> vDest;
4259 if (ExtractDestinations(script, type, vDest, nRequired)) {
4260 BOOST_FOREACH(const CTxDestination &dest, vDest)
4261 boost::apply_visitor(*this, dest);
4265 void operator()(const CKeyID &keyId) {
4266 if (keystore.HaveKey(keyId))
4267 vKeys.push_back(keyId);
4270 void operator()(const CScriptID &scriptId) {
4272 if (keystore.GetCScript(scriptId, script))
4276 void operator()(const CNoDestination &none) {}
4279 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
4280 AssertLockHeld(cs_wallet); // mapKeyMetadata
4281 mapKeyBirth.clear();
4283 // get birth times for keys with metadata
4284 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
4285 if (it->second.nCreateTime)
4286 mapKeyBirth[it->first] = it->second.nCreateTime;
4288 // map in which we'll infer heights of other keys
4289 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
4290 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
4291 std::set<CKeyID> setKeys;
4293 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
4294 if (mapKeyBirth.count(keyid) == 0)
4295 mapKeyFirstBlock[keyid] = pindexMax;
4299 // if there are no such keys, we're done
4300 if (mapKeyFirstBlock.empty())
4303 // find first block that affects those keys, if there are any left
4304 std::vector<CKeyID> vAffected;
4305 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
4306 // iterate over all wallet transactions...
4307 const CWalletTx &wtx = (*it).second;
4308 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
4309 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
4310 // ... which are already in a block
4311 int nHeight = blit->second->nHeight;
4312 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
4313 // iterate over all their outputs
4314 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
4315 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
4316 // ... and all their affected keys
4317 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
4318 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
4319 rit->second = blit->second;
4326 // Extract block timestamps for those keys
4327 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
4328 mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
4331 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
4333 if (boost::get<CNoDestination>(&dest))
4336 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
4339 return CWalletDB(strWalletFile).WriteDestData(EncodeDestination(dest), key, value);
4342 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
4344 if (!mapAddressBook[dest].destdata.erase(key))
4348 return CWalletDB(strWalletFile).EraseDestData(EncodeDestination(dest), key);
4351 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
4353 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
4357 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
4359 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
4360 if(i != mapAddressBook.end())
4362 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
4363 if(j != i->second.destdata.end())
4373 CKeyPool::CKeyPool()
4378 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
4381 vchPubKey = vchPubKeyIn;
4384 CWalletKey::CWalletKey(int64_t nExpires)
4386 nTimeCreated = (nExpires ? GetTime() : 0);
4387 nTimeExpires = nExpires;
4390 void CMerkleTx::SetMerkleBranch(const CBlock& block)
4394 // Update the tx's hashBlock
4395 hashBlock = block.GetHash();
4397 // Locate the transaction
4398 for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
4399 if (block.vtx[nIndex] == *(CTransaction*)this)
4401 if (nIndex == (int)block.vtx.size())
4403 vMerkleBranch.clear();
4405 LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
4408 // Fill in merkle branch
4409 vMerkleBranch = block.GetMerkleBranch(nIndex);
4412 int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const
4414 if (hashBlock.IsNull() || nIndex == -1)
4416 AssertLockHeld(cs_main);
4418 // Find the block it claims to be in
4419 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4420 if (mi == mapBlockIndex.end())
4422 CBlockIndex* pindex = (*mi).second;
4423 if (!pindex || !chainActive.Contains(pindex))
4426 // Make sure the merkle branch connects to this block
4427 if (!fMerkleVerified)
4429 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
4431 fMerkleVerified = true;
4435 return chainActive.Height() - pindex->nHeight + 1;
4438 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4440 AssertLockHeld(cs_main);
4441 int nResult = GetDepthInMainChainINTERNAL(pindexRet);
4442 if (nResult == 0 && !mempool.exists(GetHash()))
4443 return -1; // Not in chain, not in mempool
4448 int CMerkleTx::GetBlocksToMaturity() const
4452 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4456 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectAbsurdFee)
4458 CValidationState state;
4459 return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectAbsurdFee);
4463 * Find notes in the wallet filtered by payment address, min depth and ability to spend.
4464 * These notes are decrypted and added to the output parameter vector, outEntries.
4466 void CWallet::GetFilteredNotes(
4467 std::vector<SproutNoteEntry>& sproutEntries,
4468 std::vector<SaplingNoteEntry>& saplingEntries,
4469 std::string address,
4472 bool requireSpendingKey)
4474 std::set<PaymentAddress> filterAddresses;
4476 if (address.length() > 0) {
4477 filterAddresses.insert(DecodePaymentAddress(address));
4480 GetFilteredNotes(sproutEntries, saplingEntries, filterAddresses, minDepth, INT_MAX, ignoreSpent, requireSpendingKey);
4484 * Find notes in the wallet filtered by payment addresses, min depth, max depth,
4485 * if the note is spent, if a spending key is required, and if the notes are locked.
4486 * These notes are decrypted and added to the output parameter vector, outEntries.
4488 void CWallet::GetFilteredNotes(
4489 std::vector<SproutNoteEntry>& sproutEntries,
4490 std::vector<SaplingNoteEntry>& saplingEntries,
4491 std::set<PaymentAddress>& filterAddresses,
4495 bool requireSpendingKey,
4498 LOCK2(cs_main, cs_wallet);
4500 for (auto & p : mapWallet) {
4501 CWalletTx wtx = p.second;
4503 // Filter the transactions before checking for notes
4504 if (!CheckFinalTx(wtx) ||
4505 wtx.GetBlocksToMaturity() > 0 ||
4506 wtx.GetDepthInMainChain() < minDepth ||
4507 wtx.GetDepthInMainChain() > maxDepth) {
4511 for (auto & pair : wtx.mapSproutNoteData) {
4512 JSOutPoint jsop = pair.first;
4513 SproutNoteData nd = pair.second;
4514 SproutPaymentAddress pa = nd.address;
4516 // skip notes which belong to a different payment address in the wallet
4517 if (!(filterAddresses.empty() || filterAddresses.count(pa))) {
4521 // skip note which has been spent
4522 if (ignoreSpent && nd.nullifier && IsSproutSpent(*nd.nullifier)) {
4526 // skip notes which cannot be spent
4527 if (requireSpendingKey && !HaveSproutSpendingKey(pa)) {
4531 // skip locked notes
4532 if (ignoreLocked && IsLockedNote(jsop)) {
4536 int i = jsop.js; // Index into CTransaction.vJoinSplit
4537 int j = jsop.n; // Index into JSDescription.ciphertexts
4539 // Get cached decryptor
4540 ZCNoteDecryption decryptor;
4541 if (!GetNoteDecryptor(pa, decryptor)) {
4542 // Note decryptors are created when the wallet is loaded, so it should always exist
4543 throw std::runtime_error(strprintf("Could not find note decryptor for payment address %s", EncodePaymentAddress(pa)));
4546 // determine amount of funds in the note
4547 auto hSig = wtx.vJoinSplit[i].h_sig(*pzcashParams, wtx.joinSplitPubKey);
4549 SproutNotePlaintext plaintext = SproutNotePlaintext::decrypt(
4551 wtx.vJoinSplit[i].ciphertexts[j],
4552 wtx.vJoinSplit[i].ephemeralKey,
4556 sproutEntries.push_back(SproutNoteEntry {
4557 jsop, pa, plaintext.note(pa), plaintext.memo(), wtx.GetDepthInMainChain() });
4559 } catch (const note_decryption_failed &err) {
4560 // Couldn't decrypt with this spending key
4561 throw std::runtime_error(strprintf("Could not decrypt note for payment address %s", EncodePaymentAddress(pa)));
4562 } catch (const std::exception &exc) {
4563 // Unexpected failure
4564 throw std::runtime_error(strprintf("Error while decrypting note for payment address %s: %s", EncodePaymentAddress(pa), exc.what()));
4568 for (auto & pair : wtx.mapSaplingNoteData) {
4569 SaplingOutPoint op = pair.first;
4570 SaplingNoteData nd = pair.second;
4572 auto maybe_pt = SaplingNotePlaintext::decrypt(
4573 wtx.vShieldedOutput[op.n].encCiphertext,
4575 wtx.vShieldedOutput[op.n].ephemeralKey,
4576 wtx.vShieldedOutput[op.n].cm);
4577 assert(static_cast<bool>(maybe_pt));
4578 auto notePt = maybe_pt.get();
4580 auto maybe_pa = nd.ivk.address(notePt.d);
4581 assert(static_cast<bool>(maybe_pa));
4582 auto pa = maybe_pa.get();
4584 // skip notes which belong to a different payment address in the wallet
4585 if (!(filterAddresses.empty() || filterAddresses.count(pa))) {
4589 if (ignoreSpent && nd.nullifier && IsSaplingSpent(*nd.nullifier)) {
4593 // skip notes which cannot be spent
4594 if (requireSpendingKey) {
4595 libzcash::SaplingIncomingViewingKey ivk;
4596 libzcash::SaplingFullViewingKey fvk;
4597 if (!(GetSaplingIncomingViewingKey(pa, ivk) &&
4598 GetSaplingFullViewingKey(ivk, fvk) &&
4599 HaveSaplingSpendingKey(fvk))) {
4604 // skip locked notes
4605 if (ignoreLocked && IsLockedNote(op)) {
4609 auto note = notePt.note(nd.ivk).get();
4610 saplingEntries.push_back(SaplingNoteEntry {
4611 op, pa, note, notePt.memo(), wtx.GetDepthInMainChain() });
4618 // Shielded key and address generalizations
4621 bool PaymentAddressBelongsToWallet::operator()(const libzcash::SproutPaymentAddress &zaddr) const
4623 return m_wallet->HaveSproutSpendingKey(zaddr) || m_wallet->HaveSproutViewingKey(zaddr);
4626 bool PaymentAddressBelongsToWallet::operator()(const libzcash::SaplingPaymentAddress &zaddr) const
4628 libzcash::SaplingIncomingViewingKey ivk;
4630 // If we have a SaplingExtendedSpendingKey in the wallet, then we will
4631 // also have the corresponding SaplingFullViewingKey.
4632 return m_wallet->GetSaplingIncomingViewingKey(zaddr, ivk) &&
4633 m_wallet->HaveSaplingFullViewingKey(ivk);
4636 bool PaymentAddressBelongsToWallet::operator()(const libzcash::InvalidEncoding& no) const
4641 bool HaveSpendingKeyForPaymentAddress::operator()(const libzcash::SproutPaymentAddress &zaddr) const
4643 return m_wallet->HaveSproutSpendingKey(zaddr);
4646 bool HaveSpendingKeyForPaymentAddress::operator()(const libzcash::SaplingPaymentAddress &zaddr) const
4648 libzcash::SaplingIncomingViewingKey ivk;
4649 libzcash::SaplingFullViewingKey fvk;
4651 return m_wallet->GetSaplingIncomingViewingKey(zaddr, ivk) &&
4652 m_wallet->GetSaplingFullViewingKey(ivk, fvk) &&
4653 m_wallet->HaveSaplingSpendingKey(fvk);
4656 bool HaveSpendingKeyForPaymentAddress::operator()(const libzcash::InvalidEncoding& no) const
4661 boost::optional<libzcash::SpendingKey> GetSpendingKeyForPaymentAddress::operator()(
4662 const libzcash::SproutPaymentAddress &zaddr) const
4664 libzcash::SproutSpendingKey k;
4665 if (m_wallet->GetSproutSpendingKey(zaddr, k)) {
4666 return libzcash::SpendingKey(k);
4672 boost::optional<libzcash::SpendingKey> GetSpendingKeyForPaymentAddress::operator()(
4673 const libzcash::SaplingPaymentAddress &zaddr) const
4675 libzcash::SaplingExtendedSpendingKey extsk;
4676 if (m_wallet->GetSaplingExtendedSpendingKey(zaddr, extsk)) {
4677 return libzcash::SpendingKey(extsk);
4683 boost::optional<libzcash::SpendingKey> GetSpendingKeyForPaymentAddress::operator()(
4684 const libzcash::InvalidEncoding& no) const
4686 // Defaults to InvalidEncoding
4687 return libzcash::SpendingKey();
4690 SpendingKeyAddResult AddSpendingKeyToWallet::operator()(const libzcash::SproutSpendingKey &sk) const {
4691 auto addr = sk.address();
4693 LogPrint("zrpc", "Importing zaddr %s...\n", EncodePaymentAddress(addr));
4695 if (m_wallet->HaveSproutSpendingKey(addr)) {
4696 return KeyAlreadyExists;
4697 } else if (m_wallet-> AddSproutZKey(sk)) {
4698 m_wallet->mapSproutZKeyMetadata[addr].nCreateTime = nTime;
4705 SpendingKeyAddResult AddSpendingKeyToWallet::operator()(const libzcash::SaplingExtendedSpendingKey &sk) const {
4706 auto fvk = sk.expsk.full_viewing_key();
4707 auto ivk = fvk.in_viewing_key();
4708 auto addr = sk.DefaultAddress();
4711 LogPrint("zrpc", "Importing zaddr %s...\n", EncodePaymentAddress(addr));
4713 // Don't throw error in case a key is already there
4714 if (m_wallet->HaveSaplingSpendingKey(fvk)) {
4715 return KeyAlreadyExists;
4717 if (!m_wallet-> AddSaplingZKey(sk, addr)) {
4721 // Sapling addresses can't have been used in transactions prior to activation.
4722 if (params.vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight == Consensus::NetworkUpgrade::ALWAYS_ACTIVE) {
4723 m_wallet->mapSaplingZKeyMetadata[ivk].nCreateTime = nTime;
4725 // 154051200 seconds from epoch is Friday, 26 October 2018 00:00:00 GMT - definitely before Sapling activates
4726 m_wallet->mapSaplingZKeyMetadata[ivk].nCreateTime = std::max((int64_t) 154051200, nTime);
4729 m_wallet->mapSaplingZKeyMetadata[ivk].hdKeypath = hdKeypath.get();
4733 seedFp.SetHex(seedFpStr.get());
4734 m_wallet->mapSaplingZKeyMetadata[ivk].seedFp = seedFp;
4741 SpendingKeyAddResult AddSpendingKeyToWallet::operator()(const libzcash::InvalidEncoding& no) const {
4742 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid spending key");