1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "wallet/wallet.h"
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;
39 extern UniValue sendrawtransaction(const UniValue& params, bool fHelp);
44 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
45 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
46 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
47 bool bSpendZeroConfChange = true;
48 bool fSendFreeTransactions = false;
49 bool fPayAtLeastCustomFee = true;
52 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
53 * Override with -mintxfee
55 CFeeRate CWallet::minTxFee = CFeeRate(1000);
57 /** @defgroup mapWallet
62 struct CompareValueOnly
64 bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
65 const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
67 return t1.first < t2.first;
71 std::string JSOutPoint::ToString() const
73 return strprintf("JSOutPoint(%s, %d, %d)", hash.ToString().substr(0,10), js, n);
76 std::string COutput::ToString() const
78 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
81 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
84 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
85 if (it == mapWallet.end())
90 // Generate a new spending key and return its public payment address
91 libzcash::SproutPaymentAddress CWallet::GenerateNewSproutZKey()
93 AssertLockHeld(cs_wallet); // mapSproutZKeyMetadata
95 auto k = SproutSpendingKey::random();
96 auto addr = k.address();
98 // Check for collision, even though it is unlikely to ever occur
99 if (CCryptoKeyStore::HaveSproutSpendingKey(addr))
100 throw std::runtime_error("CWallet::GenerateNewSproutZKey(): Collision detected");
102 // Create new metadata
103 int64_t nCreationTime = GetTime();
104 mapSproutZKeyMetadata[addr] = CKeyMetadata(nCreationTime);
106 if (!AddSproutZKey(k))
107 throw std::runtime_error("CWallet::GenerateNewSproutZKey(): AddSproutZKey failed");
111 // Generate a new Sapling spending key and return its public payment address
112 SaplingPaymentAddress CWallet::GenerateNewSaplingZKey()
114 AssertLockHeld(cs_wallet); // mapSaplingZKeyMetadata
116 // Create new metadata
117 int64_t nCreationTime = GetTime();
118 CKeyMetadata metadata(nCreationTime);
120 // Try to get the seed
122 if (!GetHDSeed(seed))
123 throw std::runtime_error("CWallet::GenerateNewSaplingZKey(): HD seed not found");
125 auto m = libzcash::SaplingExtendedSpendingKey::Master(seed);
126 uint32_t bip44CoinType = Params().BIP44CoinType();
128 // We use a fixed keypath scheme of m/32'/coin_type'/account'
130 auto m_32h = m.Derive(32 | ZIP32_HARDENED_KEY_LIMIT);
131 // Derive m/32'/coin_type'
132 auto m_32h_cth = m_32h.Derive(bip44CoinType | ZIP32_HARDENED_KEY_LIMIT);
134 // Derive account key at next index, skip keys already known to the wallet
135 libzcash::SaplingExtendedSpendingKey xsk;
138 xsk = m_32h_cth.Derive(hdChain.saplingAccountCounter | ZIP32_HARDENED_KEY_LIMIT);
139 metadata.hdKeypath = "m/32'/" + std::to_string(bip44CoinType) + "'/" + std::to_string(hdChain.saplingAccountCounter) + "'";
140 metadata.seedFp = hdChain.seedFp;
141 // Increment childkey index
142 hdChain.saplingAccountCounter++;
143 } while (HaveSaplingSpendingKey(xsk.expsk.full_viewing_key()));
145 // Update the chain model in the database
146 if (fFileBacked && !CWalletDB(strWalletFile).WriteHDChain(hdChain))
147 throw std::runtime_error("CWallet::GenerateNewSaplingZKey(): Writing HD chain model failed");
149 auto ivk = xsk.expsk.full_viewing_key().in_viewing_key();
150 mapSaplingZKeyMetadata[ivk] = metadata;
152 auto addr = xsk.DefaultAddress();
153 if (!AddSaplingZKey(xsk, addr)) {
154 throw std::runtime_error("CWallet::GenerateNewSaplingZKey(): AddSaplingZKey failed");
156 // return default sapling payment address.
160 // Add spending key to keystore
161 bool CWallet::AddSaplingZKey(
162 const libzcash::SaplingExtendedSpendingKey &sk,
163 const libzcash::SaplingPaymentAddress &defaultAddr)
165 AssertLockHeld(cs_wallet); // mapSaplingZKeyMetadata
167 if (!CCryptoKeyStore::AddSaplingSpendingKey(sk, defaultAddr)) {
176 auto ivk = sk.expsk.full_viewing_key().in_viewing_key();
177 return CWalletDB(strWalletFile).WriteSaplingZKey(ivk, sk, mapSaplingZKeyMetadata[ivk]);
183 // Add payment address -> incoming viewing key map entry
184 bool CWallet::AddSaplingIncomingViewingKey(
185 const libzcash::SaplingIncomingViewingKey &ivk,
186 const libzcash::SaplingPaymentAddress &addr)
188 AssertLockHeld(cs_wallet); // mapSaplingZKeyMetadata
190 if (!CCryptoKeyStore::AddSaplingIncomingViewingKey(ivk, addr)) {
199 return CWalletDB(strWalletFile).WriteSaplingPaymentAddress(addr, ivk);
206 // Add spending key to keystore and persist to disk
207 bool CWallet::AddSproutZKey(const libzcash::SproutSpendingKey &key)
209 AssertLockHeld(cs_wallet); // mapSproutZKeyMetadata
210 auto addr = key.address();
212 if (!CCryptoKeyStore::AddSproutSpendingKey(key))
215 // check if we need to remove from viewing keys
216 if (HaveSproutViewingKey(addr))
217 RemoveSproutViewingKey(key.viewing_key());
223 return CWalletDB(strWalletFile).WriteZKey(addr,
225 mapSproutZKeyMetadata[addr]);
230 CPubKey CWallet::GenerateNewKey()
232 AssertLockHeld(cs_wallet); // mapKeyMetadata
233 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
236 secret.MakeNewKey(fCompressed);
238 // Compressed public keys were introduced in version 0.6.0
240 SetMinVersion(FEATURE_COMPRPUBKEY);
242 CPubKey pubkey = secret.GetPubKey();
243 assert(secret.VerifyPubKey(pubkey));
245 // Create new metadata
246 int64_t nCreationTime = GetTime();
247 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
248 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
249 nTimeFirstKey = nCreationTime;
251 if (!AddKeyPubKey(secret, pubkey))
252 throw std::runtime_error("CWallet::GenerateNewKey(): AddKey failed");
256 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
258 AssertLockHeld(cs_wallet); // mapKeyMetadata
259 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
262 // check if we need to remove from watch-only
264 script = GetScriptForDestination(pubkey.GetID());
265 if (HaveWatchOnly(script))
266 RemoveWatchOnly(script);
271 return CWalletDB(strWalletFile).WriteKey(pubkey,
273 mapKeyMetadata[pubkey.GetID()]);
278 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
279 const vector<unsigned char> &vchCryptedSecret)
282 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
288 if (pwalletdbEncryption)
289 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
291 mapKeyMetadata[vchPubKey.GetID()]);
293 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
295 mapKeyMetadata[vchPubKey.GetID()]);
301 bool CWallet::AddCryptedSproutSpendingKey(
302 const libzcash::SproutPaymentAddress &address,
303 const libzcash::ReceivingKey &rk,
304 const std::vector<unsigned char> &vchCryptedSecret)
306 if (!CCryptoKeyStore::AddCryptedSproutSpendingKey(address, rk, vchCryptedSecret))
312 if (pwalletdbEncryption) {
313 return pwalletdbEncryption->WriteCryptedZKey(address,
316 mapSproutZKeyMetadata[address]);
318 return CWalletDB(strWalletFile).WriteCryptedZKey(address,
321 mapSproutZKeyMetadata[address]);
327 bool CWallet::AddCryptedSaplingSpendingKey(const libzcash::SaplingExtendedFullViewingKey &extfvk,
328 const std::vector<unsigned char> &vchCryptedSecret,
329 const libzcash::SaplingPaymentAddress &defaultAddr)
331 if (!CCryptoKeyStore::AddCryptedSaplingSpendingKey(extfvk, vchCryptedSecret, defaultAddr))
337 if (pwalletdbEncryption) {
338 return pwalletdbEncryption->WriteCryptedSaplingZKey(extfvk,
340 mapSaplingZKeyMetadata[extfvk.fvk.in_viewing_key()]);
342 return CWalletDB(strWalletFile).WriteCryptedSaplingZKey(extfvk,
344 mapSaplingZKeyMetadata[extfvk.fvk.in_viewing_key()]);
350 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
352 AssertLockHeld(cs_wallet); // mapKeyMetadata
353 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
354 nTimeFirstKey = meta.nCreateTime;
356 mapKeyMetadata[pubkey.GetID()] = meta;
360 bool CWallet::LoadZKeyMetadata(const SproutPaymentAddress &addr, const CKeyMetadata &meta)
362 AssertLockHeld(cs_wallet); // mapSproutZKeyMetadata
363 mapSproutZKeyMetadata[addr] = meta;
367 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
369 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
372 bool CWallet::LoadCryptedZKey(const libzcash::SproutPaymentAddress &addr, const libzcash::ReceivingKey &rk, const std::vector<unsigned char> &vchCryptedSecret)
374 return CCryptoKeyStore::AddCryptedSproutSpendingKey(addr, rk, vchCryptedSecret);
377 bool CWallet::LoadCryptedSaplingZKey(
378 const libzcash::SaplingExtendedFullViewingKey &extfvk,
379 const std::vector<unsigned char> &vchCryptedSecret)
381 return CCryptoKeyStore::AddCryptedSaplingSpendingKey(extfvk, vchCryptedSecret, extfvk.DefaultAddress());
384 bool CWallet::LoadSaplingZKeyMetadata(const libzcash::SaplingIncomingViewingKey &ivk, const CKeyMetadata &meta)
386 AssertLockHeld(cs_wallet); // mapSaplingZKeyMetadata
387 mapSaplingZKeyMetadata[ivk] = meta;
391 bool CWallet::LoadSaplingZKey(const libzcash::SaplingExtendedSpendingKey &key)
393 return CCryptoKeyStore::AddSaplingSpendingKey(key, key.DefaultAddress());
396 bool CWallet::LoadSaplingPaymentAddress(
397 const libzcash::SaplingPaymentAddress &addr,
398 const libzcash::SaplingIncomingViewingKey &ivk)
400 return CCryptoKeyStore::AddSaplingIncomingViewingKey(ivk, addr);
403 bool CWallet::LoadZKey(const libzcash::SproutSpendingKey &key)
405 return CCryptoKeyStore::AddSproutSpendingKey(key);
408 bool CWallet::AddSproutViewingKey(const libzcash::SproutViewingKey &vk)
410 if (!CCryptoKeyStore::AddSproutViewingKey(vk)) {
413 nTimeFirstKey = 1; // No birthday information for viewing keys.
417 return CWalletDB(strWalletFile).WriteSproutViewingKey(vk);
420 bool CWallet::RemoveSproutViewingKey(const libzcash::SproutViewingKey &vk)
422 AssertLockHeld(cs_wallet);
423 if (!CCryptoKeyStore::RemoveSproutViewingKey(vk)) {
427 if (!CWalletDB(strWalletFile).EraseSproutViewingKey(vk)) {
435 bool CWallet::LoadSproutViewingKey(const libzcash::SproutViewingKey &vk)
437 return CCryptoKeyStore::AddSproutViewingKey(vk);
440 bool CWallet::AddCScript(const CScript& redeemScript)
442 if (!CCryptoKeyStore::AddCScript(redeemScript))
446 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
449 bool CWallet::LoadCScript(const CScript& redeemScript)
451 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
452 * that never can be redeemed. However, old wallets may still contain
453 * these. Do not add them to the wallet and warn. */
454 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
456 std::string strAddr = EncodeDestination(CScriptID(redeemScript));
457 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",
458 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
462 return CCryptoKeyStore::AddCScript(redeemScript);
465 bool CWallet::AddWatchOnly(const CScript &dest)
467 if (!CCryptoKeyStore::AddWatchOnly(dest))
469 nTimeFirstKey = 1; // No birthday information for watch-only keys.
470 NotifyWatchonlyChanged(true);
473 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
476 bool CWallet::RemoveWatchOnly(const CScript &dest)
478 AssertLockHeld(cs_wallet);
479 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
481 if (!HaveWatchOnly())
482 NotifyWatchonlyChanged(false);
484 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
490 bool CWallet::LoadWatchOnly(const CScript &dest)
492 return CCryptoKeyStore::AddWatchOnly(dest);
495 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
498 CKeyingMaterial vMasterKey;
502 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
504 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
506 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
507 continue; // try another master key
508 if (CCryptoKeyStore::Unlock(vMasterKey)) {
509 // Now that the wallet is decrypted, ensure we have an HD seed.
510 // https://github.com/zcash/zcash/issues/3607
511 if (!this->HaveHDSeed()) {
512 this->GenerateNewSeed();
521 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
523 bool fWasLocked = IsLocked();
530 CKeyingMaterial vMasterKey;
531 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
533 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
535 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
537 if (CCryptoKeyStore::Unlock(vMasterKey))
539 int64_t nStartTime = GetTimeMillis();
540 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
541 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
543 nStartTime = GetTimeMillis();
544 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
545 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
547 if (pMasterKey.second.nDeriveIterations < 25000)
548 pMasterKey.second.nDeriveIterations = 25000;
550 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
552 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
554 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
556 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
567 void CWallet::ChainTipAdded(const CBlockIndex *pindex,
568 const CBlock *pblock,
569 SproutMerkleTree sproutTree,
570 SaplingMerkleTree saplingTree)
572 IncrementNoteWitnesses(pindex, pblock, sproutTree, saplingTree);
573 UpdateSaplingNullifierNoteMapForBlock(pblock);
576 void CWallet::ChainTip(const CBlockIndex *pindex,
577 const CBlock *pblock,
578 SproutMerkleTree sproutTree,
579 SaplingMerkleTree saplingTree,
583 ChainTipAdded(pindex, pblock, sproutTree, saplingTree);
584 // Prevent migration transactions from being created when node is syncing after launch,
585 // and also when node wakes up from suspension/hibernation and incoming blocks are old.
586 if (!IsInitialBlockDownload(Params()) &&
587 pblock->GetBlockTime() > GetAdjustedTime() - 3 * 60 * 60)
589 RunSaplingMigration(pindex->nHeight);
592 DecrementNoteWitnesses(pindex);
593 UpdateSaplingNullifierNoteMapForBlock(pblock);
597 void CWallet::RunSaplingMigration(int blockHeight) {
598 if (!NetworkUpgradeActive(blockHeight, Params().GetConsensus(), Consensus::UPGRADE_SAPLING)) {
602 if (!fSaplingMigrationEnabled) {
605 // The migration transactions to be sent in a particular batch can take
606 // significant time to generate, and this time depends on the speed of the user's
607 // computer. If they were generated only after a block is seen at the target
608 // height minus 1, then this could leak information. Therefore, for target
609 // height N, implementations SHOULD start generating the transactions at around
611 if (blockHeight % 500 == 495) {
612 std::shared_ptr<AsyncRPCQueue> q = getAsyncRPCQueue();
613 std::shared_ptr<AsyncRPCOperation> lastOperation = q->getOperationForId(saplingMigrationOperationId);
614 if (lastOperation != nullptr) {
615 lastOperation->cancel();
617 pendingSaplingMigrationTxs.clear();
618 std::shared_ptr<AsyncRPCOperation> operation(new AsyncRPCOperation_saplingmigration(blockHeight + 5));
619 saplingMigrationOperationId = operation->getId();
620 q->addOperation(operation);
621 } else if (blockHeight % 500 == 499) {
622 std::shared_ptr<AsyncRPCQueue> q = getAsyncRPCQueue();
623 std::shared_ptr<AsyncRPCOperation> lastOperation = q->getOperationForId(saplingMigrationOperationId);
624 if (lastOperation != nullptr) {
625 lastOperation->cancel();
627 for (const CTransaction& transaction : pendingSaplingMigrationTxs) {
628 // The following is taken from z_sendmany/z_mergetoaddress
629 // Send the transaction
630 // TODO: Use CWallet::CommitTransaction instead of sendrawtransaction
631 auto signedtxn = EncodeHexTx(transaction);
632 UniValue params = UniValue(UniValue::VARR);
633 params.push_back(signedtxn);
634 UniValue sendResultValue = sendrawtransaction(params, false);
635 if (sendResultValue.isNull()) {
636 throw JSONRPCError(RPC_WALLET_ERROR, "sendrawtransaction did not return an error or a txid.");
639 pendingSaplingMigrationTxs.clear();
643 void CWallet::AddPendingSaplingMigrationTx(const CTransaction& tx) {
645 pendingSaplingMigrationTxs.push_back(tx);
648 void CWallet::SetBestChain(const CBlockLocator& loc)
650 CWalletDB walletdb(strWalletFile);
651 SetBestChainINTERNAL(walletdb, loc);
654 std::set<std::pair<libzcash::PaymentAddress, uint256>> CWallet::GetNullifiersForAddresses(
655 const std::set<libzcash::PaymentAddress> & addresses)
657 std::set<std::pair<libzcash::PaymentAddress, uint256>> nullifierSet;
658 // Sapling ivk -> list of addrs map
659 // (There may be more than one diversified address for a given ivk.)
660 std::map<libzcash::SaplingIncomingViewingKey, std::vector<libzcash::SaplingPaymentAddress>> ivkMap;
661 for (const auto & addr : addresses) {
662 auto saplingAddr = boost::get<libzcash::SaplingPaymentAddress>(&addr);
663 if (saplingAddr != nullptr) {
664 libzcash::SaplingIncomingViewingKey ivk;
665 this->GetSaplingIncomingViewingKey(*saplingAddr, ivk);
666 ivkMap[ivk].push_back(*saplingAddr);
669 for (const auto & txPair : mapWallet) {
671 for (const auto & noteDataPair : txPair.second.mapSproutNoteData) {
672 auto & noteData = noteDataPair.second;
673 auto & nullifier = noteData.nullifier;
674 auto & address = noteData.address;
675 if (nullifier && addresses.count(address)) {
676 nullifierSet.insert(std::make_pair(address, nullifier.get()));
680 for (const auto & noteDataPair : txPair.second.mapSaplingNoteData) {
681 auto & noteData = noteDataPair.second;
682 auto & nullifier = noteData.nullifier;
683 auto & ivk = noteData.ivk;
684 if (nullifier && ivkMap.count(ivk)) {
685 for (const auto & addr : ivkMap[ivk]) {
686 nullifierSet.insert(std::make_pair(addr, nullifier.get()));
694 bool CWallet::IsNoteSproutChange(
695 const std::set<std::pair<libzcash::PaymentAddress, uint256>> & nullifierSet,
696 const PaymentAddress & address,
697 const JSOutPoint & jsop)
699 // A Note is marked as "change" if the address that received it
700 // also spent Notes in the same transaction. This will catch,
702 // - Change created by spending fractions of Notes (because
703 // z_sendmany sends change to the originating z-address).
704 // - "Chaining Notes" used to connect JoinSplits together.
705 // - Notes created by consolidation transactions (e.g. using
706 // z_mergetoaddress).
707 // - Notes sent from one address to itself.
708 for (const JSDescription & jsd : mapWallet[jsop.hash].vjoinsplit) {
709 for (const uint256 & nullifier : jsd.nullifiers) {
710 if (nullifierSet.count(std::make_pair(address, nullifier))) {
718 bool CWallet::IsNoteSaplingChange(const std::set<std::pair<libzcash::PaymentAddress, uint256>> & nullifierSet,
719 const libzcash::PaymentAddress & address,
720 const SaplingOutPoint & op)
722 // A Note is marked as "change" if the address that received it
723 // also spent Notes in the same transaction. This will catch,
725 // - Change created by spending fractions of Notes (because
726 // z_sendmany sends change to the originating z-address).
727 // - Notes created by consolidation transactions (e.g. using
728 // z_mergetoaddress).
729 // - Notes sent from one address to itself.
730 for (const SpendDescription &spend : mapWallet[op.hash].vShieldedSpend) {
731 if (nullifierSet.count(std::make_pair(address, spend.nullifier))) {
738 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
740 LOCK(cs_wallet); // nWalletVersion
741 if (nWalletVersion >= nVersion)
744 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
745 if (fExplicit && nVersion > nWalletMaxVersion)
746 nVersion = FEATURE_LATEST;
748 nWalletVersion = nVersion;
750 if (nVersion > nWalletMaxVersion)
751 nWalletMaxVersion = nVersion;
755 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
756 if (nWalletVersion > 40000)
757 pwalletdb->WriteMinVersion(nWalletVersion);
765 bool CWallet::SetMaxVersion(int nVersion)
767 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
768 // cannot downgrade below current version
769 if (nWalletVersion > nVersion)
772 nWalletMaxVersion = nVersion;
777 set<uint256> CWallet::GetConflicts(const uint256& txid) const
780 AssertLockHeld(cs_wallet);
782 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
783 if (it == mapWallet.end())
785 const CWalletTx& wtx = it->second;
787 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
789 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
791 if (mapTxSpends.count(txin.prevout) <= 1)
792 continue; // No conflict if zero or one spends
793 range = mapTxSpends.equal_range(txin.prevout);
794 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
795 result.insert(it->second);
798 std::pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range_n;
800 for (const JSDescription& jsdesc : wtx.vjoinsplit) {
801 for (const uint256& nullifier : jsdesc.nullifiers) {
802 if (mapTxSproutNullifiers.count(nullifier) <= 1) {
803 continue; // No conflict if zero or one spends
805 range_n = mapTxSproutNullifiers.equal_range(nullifier);
806 for (TxNullifiers::const_iterator it = range_n.first; it != range_n.second; ++it) {
807 result.insert(it->second);
812 std::pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range_o;
814 for (const SpendDescription &spend : wtx.vShieldedSpend) {
815 uint256 nullifier = spend.nullifier;
816 if (mapTxSaplingNullifiers.count(nullifier) <= 1) {
817 continue; // No conflict if zero or one spends
819 range_o = mapTxSaplingNullifiers.equal_range(nullifier);
820 for (TxNullifiers::const_iterator it = range_o.first; it != range_o.second; ++it) {
821 result.insert(it->second);
827 void CWallet::Flush(bool shutdown)
829 bitdb.Flush(shutdown);
832 bool CWallet::Verify(const string& walletFile, string& warningString, string& errorString)
834 if (!bitdb.Open(GetDataDir()))
836 // try moving the database env out of the way
837 boost::filesystem::path pathDatabase = GetDataDir() / "database";
838 boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
840 boost::filesystem::rename(pathDatabase, pathDatabaseBak);
841 LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
842 } catch (const boost::filesystem::filesystem_error&) {
843 // failure is ok (well, not really, but it's not worse than what we started with)
847 if (!bitdb.Open(GetDataDir())) {
848 // if it still fails, it probably means we can't even create the database env
849 string msg = strprintf(_("Error initializing wallet database environment %s!"), GetDataDir());
855 if (GetBoolArg("-salvagewallet", false))
857 // Recover readable keypairs:
858 if (!CWalletDB::Recover(bitdb, walletFile, true))
862 if (boost::filesystem::exists(GetDataDir() / walletFile))
864 CDBEnv::VerifyResult r = bitdb.Verify(walletFile, CWalletDB::Recover);
865 if (r == CDBEnv::RECOVER_OK)
867 warningString += strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
868 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
869 " your balance or transactions are incorrect you should"
870 " restore from a backup."), GetDataDir());
872 if (r == CDBEnv::RECOVER_FAIL)
873 errorString += _("wallet.dat corrupt, salvage failed");
880 void CWallet::SyncMetaData(pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator> range)
882 // We want all the wallet transactions in range to have the same metadata as
883 // the oldest (smallest nOrderPos).
884 // So: find smallest nOrderPos:
886 int nMinOrderPos = std::numeric_limits<int>::max();
887 const CWalletTx* copyFrom = NULL;
888 for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
890 const uint256& hash = it->second;
891 int n = mapWallet[hash].nOrderPos;
892 if (n < nMinOrderPos)
895 copyFrom = &mapWallet[hash];
898 // Now copy data from copyFrom to rest:
899 for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
901 const uint256& hash = it->second;
902 CWalletTx* copyTo = &mapWallet[hash];
903 if (copyFrom == copyTo) continue;
904 copyTo->mapValue = copyFrom->mapValue;
905 // mapSproutNoteData and mapSaplingNoteData not copied on purpose
906 // (it is always set correctly for each CWalletTx)
907 copyTo->vOrderForm = copyFrom->vOrderForm;
908 // fTimeReceivedIsTxTime not copied on purpose
909 // nTimeReceived not copied on purpose
910 copyTo->nTimeSmart = copyFrom->nTimeSmart;
911 copyTo->fFromMe = copyFrom->fFromMe;
912 copyTo->strFromAccount = copyFrom->strFromAccount;
913 // nOrderPos not copied on purpose
914 // cached members not copied on purpose
919 * Outpoint is spent if any non-conflicted transaction
922 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
924 const COutPoint outpoint(hash, n);
925 pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
926 range = mapTxSpends.equal_range(outpoint);
928 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
930 const uint256& wtxid = it->second;
931 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
932 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
933 return true; // Spent
939 * Note is spent if any non-conflicted transaction
942 bool CWallet::IsSproutSpent(const uint256& nullifier) const {
943 pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range;
944 range = mapTxSproutNullifiers.equal_range(nullifier);
946 for (TxNullifiers::const_iterator it = range.first; it != range.second; ++it) {
947 const uint256& wtxid = it->second;
948 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
949 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) {
950 return true; // Spent
956 bool CWallet::IsSaplingSpent(const uint256& nullifier) const {
957 pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range;
958 range = mapTxSaplingNullifiers.equal_range(nullifier);
960 for (TxNullifiers::const_iterator it = range.first; it != range.second; ++it) {
961 const uint256& wtxid = it->second;
962 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
963 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) {
964 return true; // Spent
970 void CWallet::AddToTransparentSpends(const COutPoint& outpoint, const uint256& wtxid)
972 mapTxSpends.insert(make_pair(outpoint, wtxid));
974 pair<TxSpends::iterator, TxSpends::iterator> range;
975 range = mapTxSpends.equal_range(outpoint);
976 SyncMetaData<COutPoint>(range);
979 void CWallet::AddToSproutSpends(const uint256& nullifier, const uint256& wtxid)
981 mapTxSproutNullifiers.insert(make_pair(nullifier, wtxid));
983 pair<TxNullifiers::iterator, TxNullifiers::iterator> range;
984 range = mapTxSproutNullifiers.equal_range(nullifier);
985 SyncMetaData<uint256>(range);
988 void CWallet::AddToSaplingSpends(const uint256& nullifier, const uint256& wtxid)
990 mapTxSaplingNullifiers.insert(make_pair(nullifier, wtxid));
992 pair<TxNullifiers::iterator, TxNullifiers::iterator> range;
993 range = mapTxSaplingNullifiers.equal_range(nullifier);
994 SyncMetaData<uint256>(range);
997 void CWallet::AddToSpends(const uint256& wtxid)
999 assert(mapWallet.count(wtxid));
1000 CWalletTx& thisTx = mapWallet[wtxid];
1001 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
1004 for (const CTxIn& txin : thisTx.vin) {
1005 AddToTransparentSpends(txin.prevout, wtxid);
1007 for (const JSDescription& jsdesc : thisTx.vjoinsplit) {
1008 for (const uint256& nullifier : jsdesc.nullifiers) {
1009 AddToSproutSpends(nullifier, wtxid);
1012 for (const SpendDescription &spend : thisTx.vShieldedSpend) {
1013 AddToSaplingSpends(spend.nullifier, wtxid);
1017 void CWallet::ClearNoteWitnessCache()
1020 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1021 for (mapSproutNoteData_t::value_type& item : wtxItem.second.mapSproutNoteData) {
1022 item.second.witnesses.clear();
1023 item.second.witnessHeight = -1;
1025 for (mapSaplingNoteData_t::value_type& item : wtxItem.second.mapSaplingNoteData) {
1026 item.second.witnesses.clear();
1027 item.second.witnessHeight = -1;
1030 nWitnessCacheSize = 0;
1033 template<typename NoteDataMap>
1034 void CopyPreviousWitnesses(NoteDataMap& noteDataMap, int indexHeight, int64_t nWitnessCacheSize)
1036 for (auto& item : noteDataMap) {
1037 auto* nd = &(item.second);
1038 // Only increment witnesses that are behind the current height
1039 if (nd->witnessHeight < indexHeight) {
1040 // Check the validity of the cache
1041 // The only time a note witnessed above the current height
1042 // would be invalid here is during a reindex when blocks
1043 // have been decremented, and we are incrementing the blocks
1044 // immediately after.
1045 assert(nWitnessCacheSize >= nd->witnesses.size());
1046 // Witnesses being incremented should always be either -1
1047 // (never incremented or decremented) or one below indexHeight
1048 assert((nd->witnessHeight == -1) || (nd->witnessHeight == indexHeight - 1));
1049 // Copy the witness for the previous block if we have one
1050 if (nd->witnesses.size() > 0) {
1051 nd->witnesses.push_front(nd->witnesses.front());
1053 if (nd->witnesses.size() > WITNESS_CACHE_SIZE) {
1054 nd->witnesses.pop_back();
1060 template<typename NoteDataMap>
1061 void AppendNoteCommitment(NoteDataMap& noteDataMap, int indexHeight, int64_t nWitnessCacheSize, const uint256& note_commitment)
1063 for (auto& item : noteDataMap) {
1064 auto* nd = &(item.second);
1065 if (nd->witnessHeight < indexHeight && nd->witnesses.size() > 0) {
1066 // Check the validity of the cache
1067 // See comment in CopyPreviousWitnesses about validity.
1068 assert(nWitnessCacheSize >= nd->witnesses.size());
1069 nd->witnesses.front().append(note_commitment);
1074 template<typename OutPoint, typename NoteData, typename Witness>
1075 void WitnessNoteIfMine(std::map<OutPoint, NoteData>& noteDataMap, int indexHeight, int64_t nWitnessCacheSize, const OutPoint& key, const Witness& witness)
1077 if (noteDataMap.count(key) && noteDataMap[key].witnessHeight < indexHeight) {
1078 auto* nd = &(noteDataMap[key]);
1079 if (nd->witnesses.size() > 0) {
1080 // We think this can happen because we write out the
1081 // witness cache state after every block increment or
1082 // decrement, but the block index itself is written in
1083 // batches. So if the node crashes in between these two
1084 // operations, it is possible for IncrementNoteWitnesses
1085 // to be called again on previously-cached blocks. This
1086 // doesn't affect existing cached notes because of the
1087 // NoteData::witnessHeight checks. See #1378 for details.
1088 LogPrintf("Inconsistent witness cache state found for %s\n- Cache size: %d\n- Top (height %d): %s\n- New (height %d): %s\n",
1089 key.ToString(), nd->witnesses.size(),
1091 nd->witnesses.front().root().GetHex(),
1093 witness.root().GetHex());
1094 nd->witnesses.clear();
1096 nd->witnesses.push_front(witness);
1097 // Set height to one less than pindex so it gets incremented
1098 nd->witnessHeight = indexHeight - 1;
1099 // Check the validity of the cache
1100 assert(nWitnessCacheSize >= nd->witnesses.size());
1105 template<typename NoteDataMap>
1106 void UpdateWitnessHeights(NoteDataMap& noteDataMap, int indexHeight, int64_t nWitnessCacheSize)
1108 for (auto& item : noteDataMap) {
1109 auto* nd = &(item.second);
1110 if (nd->witnessHeight < indexHeight) {
1111 nd->witnessHeight = indexHeight;
1112 // Check the validity of the cache
1113 // See comment in CopyPreviousWitnesses about validity.
1114 assert(nWitnessCacheSize >= nd->witnesses.size());
1119 void CWallet::IncrementNoteWitnesses(const CBlockIndex* pindex,
1120 const CBlock* pblockIn,
1121 SproutMerkleTree& sproutTree,
1122 SaplingMerkleTree& saplingTree)
1125 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1126 ::CopyPreviousWitnesses(wtxItem.second.mapSproutNoteData, pindex->nHeight, nWitnessCacheSize);
1127 ::CopyPreviousWitnesses(wtxItem.second.mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize);
1130 if (nWitnessCacheSize < WITNESS_CACHE_SIZE) {
1131 nWitnessCacheSize += 1;
1134 const CBlock* pblock {pblockIn};
1137 ReadBlockFromDisk(block, pindex, Params().GetConsensus());
1141 for (const CTransaction& tx : pblock->vtx) {
1142 auto hash = tx.GetHash();
1143 bool txIsOurs = mapWallet.count(hash);
1145 for (size_t i = 0; i < tx.vjoinsplit.size(); i++) {
1146 const JSDescription& jsdesc = tx.vjoinsplit[i];
1147 for (uint8_t j = 0; j < jsdesc.commitments.size(); j++) {
1148 const uint256& note_commitment = jsdesc.commitments[j];
1149 sproutTree.append(note_commitment);
1151 // Increment existing witnesses
1152 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1153 ::AppendNoteCommitment(wtxItem.second.mapSproutNoteData, pindex->nHeight, nWitnessCacheSize, note_commitment);
1156 // If this is our note, witness it
1158 JSOutPoint jsoutpt {hash, i, j};
1159 ::WitnessNoteIfMine(mapWallet[hash].mapSproutNoteData, pindex->nHeight, nWitnessCacheSize, jsoutpt, sproutTree.witness());
1164 for (uint32_t i = 0; i < tx.vShieldedOutput.size(); i++) {
1165 const uint256& note_commitment = tx.vShieldedOutput[i].cm;
1166 saplingTree.append(note_commitment);
1168 // Increment existing witnesses
1169 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1170 ::AppendNoteCommitment(wtxItem.second.mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize, note_commitment);
1173 // If this is our note, witness it
1175 SaplingOutPoint outPoint {hash, i};
1176 ::WitnessNoteIfMine(mapWallet[hash].mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize, outPoint, saplingTree.witness());
1181 // Update witness heights
1182 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1183 ::UpdateWitnessHeights(wtxItem.second.mapSproutNoteData, pindex->nHeight, nWitnessCacheSize);
1184 ::UpdateWitnessHeights(wtxItem.second.mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize);
1187 // For performance reasons, we write out the witness cache in
1188 // CWallet::SetBestChain() (which also ensures that overall consistency
1189 // of the wallet.dat is maintained).
1192 template<typename NoteDataMap>
1193 void DecrementNoteWitnesses(NoteDataMap& noteDataMap, int indexHeight, int64_t nWitnessCacheSize)
1195 for (auto& item : noteDataMap) {
1196 auto* nd = &(item.second);
1197 // Only decrement witnesses that are not above the current height
1198 if (nd->witnessHeight <= indexHeight) {
1199 // Check the validity of the cache
1200 // See comment below (this would be invalid if there were a
1201 // prior decrement).
1202 assert(nWitnessCacheSize >= nd->witnesses.size());
1203 // Witnesses being decremented should always be either -1
1204 // (never incremented or decremented) or equal to the height
1205 // of the block being removed (indexHeight)
1206 assert((nd->witnessHeight == -1) || (nd->witnessHeight == indexHeight));
1207 if (nd->witnesses.size() > 0) {
1208 nd->witnesses.pop_front();
1210 // indexHeight is the height of the block being removed, so
1211 // the new witness cache height is one below it.
1212 nd->witnessHeight = indexHeight - 1;
1214 // Check the validity of the cache
1215 // Technically if there are notes witnessed above the current
1216 // height, their cache will now be invalid (relative to the new
1217 // value of nWitnessCacheSize). However, this would only occur
1218 // during a reindex, and by the time the reindex reaches the tip
1219 // of the chain again, the existing witness caches will be valid
1221 // We don't set nWitnessCacheSize to zero at the start of the
1222 // reindex because the on-disk blocks had already resulted in a
1223 // chain that didn't trigger the assertion below.
1224 if (nd->witnessHeight < indexHeight) {
1225 // Subtract 1 to compare to what nWitnessCacheSize will be after
1227 assert((nWitnessCacheSize - 1) >= nd->witnesses.size());
1232 void CWallet::DecrementNoteWitnesses(const CBlockIndex* pindex)
1235 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1236 ::DecrementNoteWitnesses(wtxItem.second.mapSproutNoteData, pindex->nHeight, nWitnessCacheSize);
1237 ::DecrementNoteWitnesses(wtxItem.second.mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize);
1239 nWitnessCacheSize -= 1;
1240 // TODO: If nWitnessCache is zero, we need to regenerate the caches (#1302)
1241 assert(nWitnessCacheSize > 0);
1243 // For performance reasons, we write out the witness cache in
1244 // CWallet::SetBestChain() (which also ensures that overall consistency
1245 // of the wallet.dat is maintained).
1248 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
1253 CKeyingMaterial vMasterKey;
1255 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
1256 GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
1258 CMasterKey kMasterKey;
1260 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
1261 GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
1264 int64_t nStartTime = GetTimeMillis();
1265 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
1266 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
1268 nStartTime = GetTimeMillis();
1269 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
1270 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
1272 if (kMasterKey.nDeriveIterations < 25000)
1273 kMasterKey.nDeriveIterations = 25000;
1275 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
1277 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
1279 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
1284 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
1287 assert(!pwalletdbEncryption);
1288 pwalletdbEncryption = new CWalletDB(strWalletFile);
1289 if (!pwalletdbEncryption->TxnBegin()) {
1290 delete pwalletdbEncryption;
1291 pwalletdbEncryption = NULL;
1294 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
1297 if (!EncryptKeys(vMasterKey))
1300 pwalletdbEncryption->TxnAbort();
1301 delete pwalletdbEncryption;
1303 // We now probably have half of our keys encrypted in memory, and half not...
1304 // die and let the user reload the unencrypted wallet.
1308 // Encryption was introduced in version 0.4.0
1309 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
1313 if (!pwalletdbEncryption->TxnCommit()) {
1314 delete pwalletdbEncryption;
1315 // We now have keys encrypted in memory, but not on disk...
1316 // die to avoid confusion and let the user reload the unencrypted wallet.
1320 delete pwalletdbEncryption;
1321 pwalletdbEncryption = NULL;
1325 Unlock(strWalletPassphrase);
1329 // Need to completely rewrite the wallet file; if we don't, bdb might keep
1330 // bits of the unencrypted private key in slack space in the database file.
1331 CDB::Rewrite(strWalletFile);
1334 NotifyStatusChanged(this);
1339 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
1341 AssertLockHeld(cs_wallet); // nOrderPosNext
1342 int64_t nRet = nOrderPosNext++;
1344 pwalletdb->WriteOrderPosNext(nOrderPosNext);
1346 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
1351 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
1353 AssertLockHeld(cs_wallet); // mapWallet
1354 CWalletDB walletdb(strWalletFile);
1356 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
1359 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
1360 // would make this much faster for applications that do this a lot.
1361 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1363 CWalletTx* wtx = &((*it).second);
1364 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
1367 walletdb.ListAccountCreditDebit(strAccount, acentries);
1368 BOOST_FOREACH(CAccountingEntry& entry, acentries)
1370 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
1376 void CWallet::MarkDirty()
1380 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1381 item.second.MarkDirty();
1386 * Ensure that every note in the wallet (for which we possess a spending key)
1387 * has a cached nullifier.
1389 bool CWallet::UpdateNullifierNoteMap()
1397 ZCNoteDecryption dec;
1398 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1399 for (mapSproutNoteData_t::value_type& item : wtxItem.second.mapSproutNoteData) {
1400 if (!item.second.nullifier) {
1401 if (GetNoteDecryptor(item.second.address, dec)) {
1402 auto i = item.first.js;
1403 auto hSig = wtxItem.second.vjoinsplit[i].h_sig(
1404 *pzcashParams, wtxItem.second.joinSplitPubKey);
1405 item.second.nullifier = GetSproutNoteNullifier(
1406 wtxItem.second.vjoinsplit[i],
1407 item.second.address,
1415 // TODO: Sapling. This method is only called from RPC walletpassphrase, which is currently unsupported
1416 // as RPC encryptwallet is hidden behind two flags: -developerencryptwallet -experimentalfeatures
1418 UpdateNullifierNoteMapWithTx(wtxItem.second);
1425 * Update mapSproutNullifiersToNotes and mapSaplingNullifiersToNotes
1426 * with the cached nullifiers in this tx.
1428 void CWallet::UpdateNullifierNoteMapWithTx(const CWalletTx& wtx)
1432 for (const mapSproutNoteData_t::value_type& item : wtx.mapSproutNoteData) {
1433 if (item.second.nullifier) {
1434 mapSproutNullifiersToNotes[*item.second.nullifier] = item.first;
1438 for (const mapSaplingNoteData_t::value_type& item : wtx.mapSaplingNoteData) {
1439 if (item.second.nullifier) {
1440 mapSaplingNullifiersToNotes[*item.second.nullifier] = item.first;
1447 * Update mapSaplingNullifiersToNotes, computing the nullifier from a cached witness if necessary.
1449 void CWallet::UpdateSaplingNullifierNoteMapWithTx(CWalletTx& wtx) {
1452 for (mapSaplingNoteData_t::value_type &item : wtx.mapSaplingNoteData) {
1453 SaplingOutPoint op = item.first;
1454 SaplingNoteData nd = item.second;
1456 if (nd.witnesses.empty()) {
1457 // If there are no witnesses, erase the nullifier and associated mapping.
1458 if (item.second.nullifier) {
1459 mapSaplingNullifiersToNotes.erase(item.second.nullifier.get());
1461 item.second.nullifier = boost::none;
1464 uint64_t position = nd.witnesses.front().position();
1465 SaplingFullViewingKey fvk = mapSaplingFullViewingKeys.at(nd.ivk);
1466 OutputDescription output = wtx.vShieldedOutput[op.n];
1467 auto optPlaintext = SaplingNotePlaintext::decrypt(output.encCiphertext, nd.ivk, output.ephemeralKey, output.cm);
1468 if (!optPlaintext) {
1469 // An item in mapSaplingNoteData must have already been successfully decrypted,
1470 // otherwise the item would not exist in the first place.
1473 auto optNote = optPlaintext.get().note(nd.ivk);
1477 auto optNullifier = optNote.get().nullifier(fvk, position);
1478 if (!optNullifier) {
1479 // This should not happen. If it does, maybe the position has been corrupted or miscalculated?
1482 uint256 nullifier = optNullifier.get();
1483 mapSaplingNullifiersToNotes[nullifier] = op;
1484 item.second.nullifier = nullifier;
1490 * Iterate over transactions in a block and update the cached Sapling nullifiers
1491 * for transactions which belong to the wallet.
1493 void CWallet::UpdateSaplingNullifierNoteMapForBlock(const CBlock *pblock) {
1496 for (const CTransaction& tx : pblock->vtx) {
1497 auto hash = tx.GetHash();
1498 bool txIsOurs = mapWallet.count(hash);
1500 UpdateSaplingNullifierNoteMapWithTx(mapWallet[hash]);
1505 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb)
1507 uint256 hash = wtxIn.GetHash();
1509 if (fFromLoadWallet)
1511 mapWallet[hash] = wtxIn;
1512 mapWallet[hash].BindWallet(this);
1513 UpdateNullifierNoteMapWithTx(mapWallet[hash]);
1519 // Inserts only if not already there, returns tx inserted or tx found
1520 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
1521 CWalletTx& wtx = (*ret.first).second;
1522 wtx.BindWallet(this);
1523 UpdateNullifierNoteMapWithTx(wtx);
1524 bool fInsertedNew = ret.second;
1527 wtx.nTimeReceived = GetAdjustedTime();
1528 wtx.nOrderPos = IncOrderPosNext(pwalletdb);
1530 wtx.nTimeSmart = wtx.nTimeReceived;
1531 if (!wtxIn.hashBlock.IsNull())
1533 if (mapBlockIndex.count(wtxIn.hashBlock))
1535 int64_t latestNow = wtx.nTimeReceived;
1536 int64_t latestEntry = 0;
1538 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
1539 int64_t latestTolerated = latestNow + 300;
1540 std::list<CAccountingEntry> acentries;
1541 TxItems txOrdered = OrderedTxItems(acentries);
1542 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
1544 CWalletTx *const pwtx = (*it).second.first;
1547 CAccountingEntry *const pacentry = (*it).second.second;
1551 nSmartTime = pwtx->nTimeSmart;
1553 nSmartTime = pwtx->nTimeReceived;
1556 nSmartTime = pacentry->nTime;
1557 if (nSmartTime <= latestTolerated)
1559 latestEntry = nSmartTime;
1560 if (nSmartTime > latestNow)
1561 latestNow = nSmartTime;
1567 int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
1568 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
1571 LogPrintf("AddToWallet(): found %s in block %s not in index\n",
1572 wtxIn.GetHash().ToString(),
1573 wtxIn.hashBlock.ToString());
1578 bool fUpdated = false;
1582 if (!wtxIn.hashBlock.IsNull() && wtxIn.hashBlock != wtx.hashBlock)
1584 wtx.hashBlock = wtxIn.hashBlock;
1587 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
1589 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
1590 wtx.nIndex = wtxIn.nIndex;
1593 if (UpdatedNoteData(wtxIn, wtx)) {
1596 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
1598 wtx.fFromMe = wtxIn.fFromMe;
1604 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
1607 if (fInsertedNew || fUpdated)
1608 if (!wtx.WriteToDisk(pwalletdb))
1611 // Break debit/credit balance caches:
1614 // Notify UI of new or updated transaction
1615 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
1617 // notify an external script when a wallet transaction comes in or is updated
1618 std::string strCmd = GetArg("-walletnotify", "");
1620 if ( !strCmd.empty())
1622 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
1623 boost::thread t(runCommand, strCmd); // thread runs free
1630 bool CWallet::UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx)
1632 bool unchangedSproutFlag = (wtxIn.mapSproutNoteData.empty() || wtxIn.mapSproutNoteData == wtx.mapSproutNoteData);
1633 if (!unchangedSproutFlag) {
1634 auto tmp = wtxIn.mapSproutNoteData;
1635 // Ensure we keep any cached witnesses we may already have
1636 for (const std::pair <JSOutPoint, SproutNoteData> nd : wtx.mapSproutNoteData) {
1637 if (tmp.count(nd.first) && nd.second.witnesses.size() > 0) {
1638 tmp.at(nd.first).witnesses.assign(
1639 nd.second.witnesses.cbegin(), nd.second.witnesses.cend());
1641 tmp.at(nd.first).witnessHeight = nd.second.witnessHeight;
1643 // Now copy over the updated note data
1644 wtx.mapSproutNoteData = tmp;
1647 bool unchangedSaplingFlag = (wtxIn.mapSaplingNoteData.empty() || wtxIn.mapSaplingNoteData == wtx.mapSaplingNoteData);
1648 if (!unchangedSaplingFlag) {
1649 auto tmp = wtxIn.mapSaplingNoteData;
1650 // Ensure we keep any cached witnesses we may already have
1652 for (const std::pair <SaplingOutPoint, SaplingNoteData> nd : wtx.mapSaplingNoteData) {
1653 if (tmp.count(nd.first) && nd.second.witnesses.size() > 0) {
1654 tmp.at(nd.first).witnesses.assign(
1655 nd.second.witnesses.cbegin(), nd.second.witnesses.cend());
1657 tmp.at(nd.first).witnessHeight = nd.second.witnessHeight;
1660 // Now copy over the updated note data
1661 wtx.mapSaplingNoteData = tmp;
1664 return !unchangedSproutFlag || !unchangedSaplingFlag;
1668 * Add a transaction to the wallet, or update it.
1669 * pblock is optional, but should be provided if the transaction is known to be in a block.
1670 * If fUpdate is true, existing transactions will be updated.
1672 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
1675 AssertLockHeld(cs_wallet);
1676 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1677 if (fExisted && !fUpdate) return false;
1678 auto sproutNoteData = FindMySproutNotes(tx);
1679 auto saplingNoteDataAndAddressesToAdd = FindMySaplingNotes(tx);
1680 auto saplingNoteData = saplingNoteDataAndAddressesToAdd.first;
1681 auto addressesToAdd = saplingNoteDataAndAddressesToAdd.second;
1682 for (const auto &addressToAdd : addressesToAdd) {
1683 if (!AddSaplingIncomingViewingKey(addressToAdd.second, addressToAdd.first)) {
1687 if (fExisted || IsMine(tx) || IsFromMe(tx) || sproutNoteData.size() > 0 || saplingNoteData.size() > 0)
1689 CWalletTx wtx(this,tx);
1691 if (sproutNoteData.size() > 0) {
1692 wtx.SetSproutNoteData(sproutNoteData);
1695 if (saplingNoteData.size() > 0) {
1696 wtx.SetSaplingNoteData(saplingNoteData);
1699 // Get merkle branch if transaction was found in a block
1701 wtx.SetMerkleBranch(*pblock);
1703 // Do not flush the wallet here for performance reasons
1704 // this is safe, as in case of a crash, we rescan the necessary blocks on startup through our SetBestChain-mechanism
1705 CWalletDB walletdb(strWalletFile, "r+", false);
1707 return AddToWallet(wtx, false, &walletdb);
1713 void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
1715 LOCK2(cs_main, cs_wallet);
1716 if (!AddToWalletIfInvolvingMe(tx, pblock, true))
1717 return; // Not one of ours
1719 MarkAffectedTransactionsDirty(tx);
1722 void CWallet::MarkAffectedTransactionsDirty(const CTransaction& tx)
1724 // If a transaction changes 'conflicted' state, that changes the balance
1725 // available of the outputs it spends. So force those to be
1726 // recomputed, also:
1727 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1729 if (mapWallet.count(txin.prevout.hash))
1730 mapWallet[txin.prevout.hash].MarkDirty();
1732 for (const JSDescription& jsdesc : tx.vjoinsplit) {
1733 for (const uint256& nullifier : jsdesc.nullifiers) {
1734 if (mapSproutNullifiersToNotes.count(nullifier) &&
1735 mapWallet.count(mapSproutNullifiersToNotes[nullifier].hash)) {
1736 mapWallet[mapSproutNullifiersToNotes[nullifier].hash].MarkDirty();
1741 for (const SpendDescription &spend : tx.vShieldedSpend) {
1742 uint256 nullifier = spend.nullifier;
1743 if (mapSaplingNullifiersToNotes.count(nullifier) &&
1744 mapWallet.count(mapSaplingNullifiersToNotes[nullifier].hash)) {
1745 mapWallet[mapSaplingNullifiersToNotes[nullifier].hash].MarkDirty();
1750 void CWallet::EraseFromWallet(const uint256 &hash)
1756 if (mapWallet.erase(hash))
1757 CWalletDB(strWalletFile).EraseTx(hash);
1764 * Returns a nullifier if the SpendingKey is available
1765 * Throws std::runtime_error if the decryptor doesn't match this note
1767 boost::optional<uint256> CWallet::GetSproutNoteNullifier(const JSDescription &jsdesc,
1768 const libzcash::SproutPaymentAddress &address,
1769 const ZCNoteDecryption &dec,
1770 const uint256 &hSig,
1773 boost::optional<uint256> ret;
1774 auto note_pt = libzcash::SproutNotePlaintext::decrypt(
1776 jsdesc.ciphertexts[n],
1777 jsdesc.ephemeralKey,
1780 auto note = note_pt.note(address);
1782 // Check note plaintext against note commitment
1783 if (note.cm() != jsdesc.commitments[n]) {
1784 throw libzcash::note_decryption_failed();
1787 // SpendingKeys are only available if:
1788 // - We have them (this isn't a viewing key)
1789 // - The wallet is unlocked
1790 libzcash::SproutSpendingKey key;
1791 if (GetSproutSpendingKey(address, key)) {
1792 ret = note.nullifier(key);
1798 * Finds all output notes in the given transaction that have been sent to
1799 * PaymentAddresses in this wallet.
1801 * It should never be necessary to call this method with a CWalletTx, because
1802 * the result of FindMySproutNotes (for the addresses available at the time) will
1803 * already have been cached in CWalletTx.mapSproutNoteData.
1805 mapSproutNoteData_t CWallet::FindMySproutNotes(const CTransaction &tx) const
1807 LOCK(cs_SpendingKeyStore);
1808 uint256 hash = tx.GetHash();
1810 mapSproutNoteData_t noteData;
1811 for (size_t i = 0; i < tx.vjoinsplit.size(); i++) {
1812 auto hSig = tx.vjoinsplit[i].h_sig(*pzcashParams, tx.joinSplitPubKey);
1813 for (uint8_t j = 0; j < tx.vjoinsplit[i].ciphertexts.size(); j++) {
1814 for (const NoteDecryptorMap::value_type& item : mapNoteDecryptors) {
1816 auto address = item.first;
1817 JSOutPoint jsoutpt {hash, i, j};
1818 auto nullifier = GetSproutNoteNullifier(
1824 SproutNoteData nd {address, *nullifier};
1825 noteData.insert(std::make_pair(jsoutpt, nd));
1827 SproutNoteData nd {address};
1828 noteData.insert(std::make_pair(jsoutpt, nd));
1831 } catch (const note_decryption_failed &err) {
1832 // Couldn't decrypt with this decryptor
1833 } catch (const std::exception &exc) {
1834 // Unexpected failure
1835 LogPrintf("FindMySproutNotes(): Unexpected error while testing decrypt:\n");
1836 LogPrintf("%s\n", exc.what());
1846 * Finds all output notes in the given transaction that have been sent to
1847 * SaplingPaymentAddresses in this wallet.
1849 * It should never be necessary to call this method with a CWalletTx, because
1850 * the result of FindMySaplingNotes (for the addresses available at the time) will
1851 * already have been cached in CWalletTx.mapSaplingNoteData.
1853 std::pair<mapSaplingNoteData_t, SaplingIncomingViewingKeyMap> CWallet::FindMySaplingNotes(const CTransaction &tx) const
1855 LOCK(cs_SpendingKeyStore);
1856 uint256 hash = tx.GetHash();
1858 mapSaplingNoteData_t noteData;
1859 SaplingIncomingViewingKeyMap viewingKeysToAdd;
1861 // Protocol Spec: 4.19 Block Chain Scanning (Sapling)
1862 for (uint32_t i = 0; i < tx.vShieldedOutput.size(); ++i) {
1863 const OutputDescription output = tx.vShieldedOutput[i];
1864 for (auto it = mapSaplingFullViewingKeys.begin(); it != mapSaplingFullViewingKeys.end(); ++it) {
1865 SaplingIncomingViewingKey ivk = it->first;
1866 auto result = SaplingNotePlaintext::decrypt(output.encCiphertext, ivk, output.ephemeralKey, output.cm);
1870 auto address = ivk.address(result.get().d);
1871 if (address && mapSaplingIncomingViewingKeys.count(address.get()) == 0) {
1872 viewingKeysToAdd[address.get()] = ivk;
1874 // We don't cache the nullifier here as computing it requires knowledge of the note position
1875 // in the commitment tree, which can only be determined when the transaction has been mined.
1876 SaplingOutPoint op {hash, i};
1879 noteData.insert(std::make_pair(op, nd));
1884 return std::make_pair(noteData, viewingKeysToAdd);
1887 bool CWallet::IsSproutNullifierFromMe(const uint256& nullifier) const
1891 if (mapSproutNullifiersToNotes.count(nullifier) &&
1892 mapWallet.count(mapSproutNullifiersToNotes.at(nullifier).hash)) {
1899 bool CWallet::IsSaplingNullifierFromMe(const uint256& nullifier) const
1903 if (mapSaplingNullifiersToNotes.count(nullifier) &&
1904 mapWallet.count(mapSaplingNullifiersToNotes.at(nullifier).hash)) {
1911 void CWallet::GetSproutNoteWitnesses(std::vector<JSOutPoint> notes,
1912 std::vector<boost::optional<SproutWitness>>& witnesses,
1913 uint256 &final_anchor)
1916 witnesses.resize(notes.size());
1917 boost::optional<uint256> rt;
1919 for (JSOutPoint note : notes) {
1920 if (mapWallet.count(note.hash) &&
1921 mapWallet[note.hash].mapSproutNoteData.count(note) &&
1922 mapWallet[note.hash].mapSproutNoteData[note].witnesses.size() > 0) {
1923 witnesses[i] = mapWallet[note.hash].mapSproutNoteData[note].witnesses.front();
1925 rt = witnesses[i]->root();
1927 assert(*rt == witnesses[i]->root());
1932 // All returned witnesses have the same anchor
1938 void CWallet::GetSaplingNoteWitnesses(std::vector<SaplingOutPoint> notes,
1939 std::vector<boost::optional<SaplingWitness>>& witnesses,
1940 uint256 &final_anchor)
1943 witnesses.resize(notes.size());
1944 boost::optional<uint256> rt;
1946 for (SaplingOutPoint note : notes) {
1947 if (mapWallet.count(note.hash) &&
1948 mapWallet[note.hash].mapSaplingNoteData.count(note) &&
1949 mapWallet[note.hash].mapSaplingNoteData[note].witnesses.size() > 0) {
1950 witnesses[i] = mapWallet[note.hash].mapSaplingNoteData[note].witnesses.front();
1952 rt = witnesses[i]->root();
1954 assert(*rt == witnesses[i]->root());
1959 // All returned witnesses have the same anchor
1965 isminetype CWallet::IsMine(const CTxIn &txin) const
1969 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1970 if (mi != mapWallet.end())
1972 const CWalletTx& prev = (*mi).second;
1973 if (txin.prevout.n < prev.vout.size())
1974 return IsMine(prev.vout[txin.prevout.n]);
1980 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1984 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1985 if (mi != mapWallet.end())
1987 const CWalletTx& prev = (*mi).second;
1988 if (txin.prevout.n < prev.vout.size())
1989 if (IsMine(prev.vout[txin.prevout.n]) & filter)
1990 return prev.vout[txin.prevout.n].nValue;
1996 isminetype CWallet::IsMine(const CTxOut& txout) const
1998 return ::IsMine(*this, txout.scriptPubKey);
2001 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
2003 if (!MoneyRange(txout.nValue))
2004 throw std::runtime_error("CWallet::GetCredit(): value out of range");
2005 return ((IsMine(txout) & filter) ? txout.nValue : 0);
2008 bool CWallet::IsChange(const CTxOut& txout) const
2010 // TODO: fix handling of 'change' outputs. The assumption is that any
2011 // payment to a script that is ours, but is not in the address book
2012 // is change. That assumption is likely to break when we implement multisignature
2013 // wallets that return change back into a multi-signature-protected address;
2014 // a better way of identifying which outputs are 'the send' and which are
2015 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
2016 // which output, if any, was change).
2017 if (::IsMine(*this, txout.scriptPubKey))
2019 CTxDestination address;
2020 if (!ExtractDestination(txout.scriptPubKey, address))
2024 if (!mapAddressBook.count(address))
2030 CAmount CWallet::GetChange(const CTxOut& txout) const
2032 if (!MoneyRange(txout.nValue))
2033 throw std::runtime_error("CWallet::GetChange(): value out of range");
2034 return (IsChange(txout) ? txout.nValue : 0);
2037 bool CWallet::IsMine(const CTransaction& tx) const
2039 BOOST_FOREACH(const CTxOut& txout, tx.vout)
2045 bool CWallet::IsFromMe(const CTransaction& tx) const
2047 if (GetDebit(tx, ISMINE_ALL) > 0) {
2050 for (const JSDescription& jsdesc : tx.vjoinsplit) {
2051 for (const uint256& nullifier : jsdesc.nullifiers) {
2052 if (IsSproutNullifierFromMe(nullifier)) {
2057 for (const SpendDescription &spend : tx.vShieldedSpend) {
2058 if (IsSaplingNullifierFromMe(spend.nullifier)) {
2065 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
2068 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2070 nDebit += GetDebit(txin, filter);
2071 if (!MoneyRange(nDebit))
2072 throw std::runtime_error("CWallet::GetDebit(): value out of range");
2077 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
2079 CAmount nCredit = 0;
2080 BOOST_FOREACH(const CTxOut& txout, tx.vout)
2082 nCredit += GetCredit(txout, filter);
2083 if (!MoneyRange(nCredit))
2084 throw std::runtime_error("CWallet::GetCredit(): value out of range");
2089 CAmount CWallet::GetChange(const CTransaction& tx) const
2091 CAmount nChange = 0;
2092 BOOST_FOREACH(const CTxOut& txout, tx.vout)
2094 nChange += GetChange(txout);
2095 if (!MoneyRange(nChange))
2096 throw std::runtime_error("CWallet::GetChange(): value out of range");
2101 bool CWallet::IsHDFullyEnabled() const
2103 // Only Sapling addresses are HD for now
2107 void CWallet::GenerateNewSeed()
2111 auto seed = HDSeed::Random(HD_WALLET_SEED_LENGTH);
2113 int64_t nCreationTime = GetTime();
2115 // If the wallet is encrypted and locked, this will fail.
2116 if (!SetHDSeed(seed))
2117 throw std::runtime_error(std::string(__func__) + ": SetHDSeed failed");
2119 // store the key creation time together with
2120 // the child index counter in the database
2121 // as a hdchain object
2122 CHDChain newHdChain;
2123 newHdChain.nVersion = CHDChain::VERSION_HD_BASE;
2124 newHdChain.seedFp = seed.Fingerprint();
2125 newHdChain.nCreateTime = nCreationTime;
2126 SetHDChain(newHdChain, false);
2129 bool CWallet::SetHDSeed(const HDSeed& seed)
2131 if (!CCryptoKeyStore::SetHDSeed(seed)) {
2142 return CWalletDB(strWalletFile).WriteHDSeed(seed);
2148 bool CWallet::SetCryptedHDSeed(const uint256& seedFp, const std::vector<unsigned char> &vchCryptedSecret)
2150 if (!CCryptoKeyStore::SetCryptedHDSeed(seedFp, vchCryptedSecret)) {
2160 if (pwalletdbEncryption)
2161 return pwalletdbEncryption->WriteCryptedHDSeed(seedFp, vchCryptedSecret);
2163 return CWalletDB(strWalletFile).WriteCryptedHDSeed(seedFp, vchCryptedSecret);
2168 HDSeed CWallet::GetHDSeedForRPC() const {
2170 if (!pwalletMain->GetHDSeed(seed)) {
2171 throw JSONRPCError(RPC_WALLET_ERROR, "HD seed not found");
2176 void CWallet::SetHDChain(const CHDChain& chain, bool memonly)
2179 if (!memonly && fFileBacked && !CWalletDB(strWalletFile).WriteHDChain(chain))
2180 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
2185 bool CWallet::LoadHDSeed(const HDSeed& seed)
2187 return CBasicKeyStore::SetHDSeed(seed);
2190 bool CWallet::LoadCryptedHDSeed(const uint256& seedFp, const std::vector<unsigned char>& seed)
2192 return CCryptoKeyStore::SetCryptedHDSeed(seedFp, seed);
2195 void CWalletTx::SetSproutNoteData(mapSproutNoteData_t ¬eData)
2197 mapSproutNoteData.clear();
2198 for (const std::pair<JSOutPoint, SproutNoteData> nd : noteData) {
2199 if (nd.first.js < vjoinsplit.size() &&
2200 nd.first.n < vjoinsplit[nd.first.js].ciphertexts.size()) {
2201 // Store the address and nullifier for the Note
2202 mapSproutNoteData[nd.first] = nd.second;
2204 // If FindMySproutNotes() was used to obtain noteData,
2205 // this should never happen
2206 throw std::logic_error("CWalletTx::SetSproutNoteData(): Invalid note");
2211 void CWalletTx::SetSaplingNoteData(mapSaplingNoteData_t ¬eData)
2213 mapSaplingNoteData.clear();
2214 for (const std::pair<SaplingOutPoint, SaplingNoteData> nd : noteData) {
2215 if (nd.first.n < vShieldedOutput.size()) {
2216 mapSaplingNoteData[nd.first] = nd.second;
2218 throw std::logic_error("CWalletTx::SetSaplingNoteData(): Invalid note");
2223 int64_t CWalletTx::GetTxTime() const
2225 int64_t n = nTimeSmart;
2226 return n ? n : nTimeReceived;
2229 int CWalletTx::GetRequestCount() const
2231 // Returns -1 if it wasn't being tracked
2234 LOCK(pwallet->cs_wallet);
2238 if (!hashBlock.IsNull())
2240 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
2241 if (mi != pwallet->mapRequestCount.end())
2242 nRequests = (*mi).second;
2247 // Did anyone request this transaction?
2248 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
2249 if (mi != pwallet->mapRequestCount.end())
2251 nRequests = (*mi).second;
2253 // How about the block it's in?
2254 if (nRequests == 0 && !hashBlock.IsNull())
2256 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
2257 if (mi != pwallet->mapRequestCount.end())
2258 nRequests = (*mi).second;
2260 nRequests = 1; // If it's in someone else's block it must have got out
2268 // GetAmounts will determine the transparent debits and credits for a given wallet tx.
2269 void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
2270 list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
2273 listReceived.clear();
2275 strSentAccount = strFromAccount;
2277 // Is this tx sent/signed by me?
2278 CAmount nDebit = GetDebit(filter);
2279 bool isFromMyTaddr = nDebit > 0; // debit>0 means we signed/sent this transaction
2281 // Compute fee if we sent this transaction.
2282 if (isFromMyTaddr) {
2283 CAmount nValueOut = GetValueOut(); // transparent outputs plus all Sprout vpub_old and negative Sapling valueBalance
2284 CAmount nValueIn = GetShieldedValueIn();
2285 nFee = nDebit - nValueOut + nValueIn;
2288 // Create output entry for vpub_old/new, if we sent utxos from this transaction
2289 if (isFromMyTaddr) {
2290 CAmount myVpubOld = 0;
2291 CAmount myVpubNew = 0;
2292 for (const JSDescription& js : vjoinsplit) {
2293 bool fMyJSDesc = false;
2296 for (const uint256& nullifier : js.nullifiers) {
2297 if (pwallet->IsSproutNullifierFromMe(nullifier)) {
2303 // Check output side
2305 for (const std::pair<JSOutPoint, SproutNoteData> nd : this->mapSproutNoteData) {
2306 if (nd.first.js < vjoinsplit.size() && nd.first.n < vjoinsplit[nd.first.js].ciphertexts.size()) {
2314 myVpubOld += js.vpub_old;
2315 myVpubNew += js.vpub_new;
2318 if (!MoneyRange(js.vpub_old) || !MoneyRange(js.vpub_new) || !MoneyRange(myVpubOld) || !MoneyRange(myVpubNew)) {
2319 throw std::runtime_error("CWalletTx::GetAmounts: value out of range");
2323 // Create an output for the value taken from or added to the transparent value pool by JoinSplits
2324 if (myVpubOld > myVpubNew) {
2325 COutputEntry output = {CNoDestination(), myVpubOld - myVpubNew, (int)vout.size()};
2326 listSent.push_back(output);
2327 } else if (myVpubNew > myVpubOld) {
2328 COutputEntry output = {CNoDestination(), myVpubNew - myVpubOld, (int)vout.size()};
2329 listReceived.push_back(output);
2333 // If we sent utxos from this transaction, create output for value taken from (negative valueBalance)
2334 // or added (positive valueBalance) to the transparent value pool by Sapling shielding and unshielding.
2335 if (isFromMyTaddr) {
2336 if (valueBalance < 0) {
2337 COutputEntry output = {CNoDestination(), -valueBalance, (int) vout.size()};
2338 listSent.push_back(output);
2339 } else if (valueBalance > 0) {
2340 COutputEntry output = {CNoDestination(), valueBalance, (int) vout.size()};
2341 listReceived.push_back(output);
2346 for (unsigned int i = 0; i < vout.size(); ++i)
2348 const CTxOut& txout = vout[i];
2349 isminetype fIsMine = pwallet->IsMine(txout);
2350 // Only need to handle txouts if AT LEAST one of these is true:
2351 // 1) they debit from us (sent)
2352 // 2) the output is to us (received)
2355 // Don't report 'change' txouts
2356 if (pwallet->IsChange(txout))
2359 else if (!(fIsMine & filter))
2362 // In either case, we need to get the destination address
2363 CTxDestination address;
2364 if (!ExtractDestination(txout.scriptPubKey, address))
2366 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
2367 this->GetHash().ToString());
2368 address = CNoDestination();
2371 COutputEntry output = {address, txout.nValue, (int)i};
2373 // If we are debited by the transaction, add the output as a "sent" entry
2375 listSent.push_back(output);
2377 // If we are receiving the output, add it as a "received" entry
2378 if (fIsMine & filter)
2379 listReceived.push_back(output);
2384 void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
2385 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
2387 nReceived = nSent = nFee = 0;
2390 string strSentAccount;
2391 list<COutputEntry> listReceived;
2392 list<COutputEntry> listSent;
2393 GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
2395 if (strAccount == strSentAccount)
2397 BOOST_FOREACH(const COutputEntry& s, listSent)
2402 LOCK(pwallet->cs_wallet);
2403 BOOST_FOREACH(const COutputEntry& r, listReceived)
2405 if (pwallet->mapAddressBook.count(r.destination))
2407 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
2408 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
2409 nReceived += r.amount;
2411 else if (strAccount.empty())
2413 nReceived += r.amount;
2420 bool CWalletTx::WriteToDisk(CWalletDB *pwalletdb)
2422 return pwalletdb->WriteTx(GetHash(), *this);
2425 void CWallet::WitnessNoteCommitment(std::vector<uint256> commitments,
2426 std::vector<boost::optional<SproutWitness>>& witnesses,
2427 uint256 &final_anchor)
2429 witnesses.resize(commitments.size());
2430 CBlockIndex* pindex = chainActive.Genesis();
2431 SproutMerkleTree tree;
2435 ReadBlockFromDisk(block, pindex, Params().GetConsensus());
2437 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2439 BOOST_FOREACH(const JSDescription& jsdesc, tx.vjoinsplit)
2441 BOOST_FOREACH(const uint256 ¬e_commitment, jsdesc.commitments)
2443 tree.append(note_commitment);
2445 BOOST_FOREACH(boost::optional<SproutWitness>& wit, witnesses) {
2447 wit->append(note_commitment);
2452 BOOST_FOREACH(uint256& commitment, commitments) {
2453 if (note_commitment == commitment) {
2454 witnesses.at(i) = tree.witness();
2462 uint256 current_anchor = tree.root();
2464 // Consistency check: we should be able to find the current tree
2465 // in our CCoins view.
2466 SproutMerkleTree dummy_tree;
2467 assert(pcoinsTip->GetSproutAnchorAt(current_anchor, dummy_tree));
2469 pindex = chainActive.Next(pindex);
2472 // TODO: #93; Select a root via some heuristic.
2473 final_anchor = tree.root();
2475 BOOST_FOREACH(boost::optional<SproutWitness>& wit, witnesses) {
2477 assert(final_anchor == wit->root());
2483 * Scan the block chain (starting in pindexStart) for transactions
2484 * from or to us. If fUpdate is true, found transactions that already
2485 * exist in the wallet will be updated.
2487 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
2490 int64_t nNow = GetTime();
2491 const CChainParams& chainParams = Params();
2493 CBlockIndex* pindex = pindexStart;
2495 std::vector<uint256> myTxHashes;
2498 LOCK2(cs_main, cs_wallet);
2500 // no need to read and scan block, if block was created before
2501 // our wallet birthday (as adjusted for block time variability)
2502 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
2503 pindex = chainActive.Next(pindex);
2505 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
2506 double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
2507 double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip(), false);
2510 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
2511 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
2514 ReadBlockFromDisk(block, pindex, Params().GetConsensus());
2515 BOOST_FOREACH(CTransaction& tx, block.vtx)
2517 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) {
2518 myTxHashes.push_back(tx.GetHash());
2523 SproutMerkleTree sproutTree;
2524 SaplingMerkleTree saplingTree;
2525 // This should never fail: we should always be able to get the tree
2526 // state on the path to the tip of our chain
2527 assert(pcoinsTip->GetSproutAnchorAt(pindex->hashSproutAnchor, sproutTree));
2528 if (pindex->pprev) {
2529 if (NetworkUpgradeActive(pindex->pprev->nHeight, Params().GetConsensus(), Consensus::UPGRADE_SAPLING)) {
2530 assert(pcoinsTip->GetSaplingAnchorAt(pindex->pprev->hashFinalSaplingRoot, saplingTree));
2533 // Increment note witness caches
2534 ChainTipAdded(pindex, &block, sproutTree, saplingTree);
2536 pindex = chainActive.Next(pindex);
2537 if (GetTime() >= nNow + 60) {
2539 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex));
2543 // After rescanning, persist Sapling note data that might have changed, e.g. nullifiers.
2544 // Do not flush the wallet here for performance reasons.
2545 CWalletDB walletdb(strWalletFile, "r+", false);
2546 for (auto hash : myTxHashes) {
2547 CWalletTx wtx = mapWallet[hash];
2548 if (!wtx.mapSaplingNoteData.empty()) {
2549 if (!wtx.WriteToDisk(&walletdb)) {
2550 LogPrintf("Rescanning... WriteToDisk failed to update Sapling note data for: %s\n", hash.ToString());
2555 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
2560 void CWallet::ReacceptWalletTransactions()
2562 // If transactions aren't being broadcasted, don't let them into local mempool either
2563 if (!fBroadcastTransactions)
2565 LOCK2(cs_main, cs_wallet);
2566 std::map<int64_t, CWalletTx*> mapSorted;
2568 // Sort pending wallet transactions based on their initial wallet insertion order
2569 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
2571 const uint256& wtxid = item.first;
2572 CWalletTx& wtx = item.second;
2573 assert(wtx.GetHash() == wtxid);
2575 int nDepth = wtx.GetDepthInMainChain();
2577 if (!wtx.IsCoinBase() && nDepth < 0) {
2578 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
2582 // Try to add wallet transactions to memory pool
2583 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
2585 CWalletTx& wtx = *(item.second);
2588 wtx.AcceptToMemoryPool(false);
2592 bool CWalletTx::RelayWalletTransaction()
2594 assert(pwallet->GetBroadcastTransactions());
2597 if (GetDepthInMainChain() == 0) {
2598 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
2599 RelayTransaction((CTransaction)*this);
2606 set<uint256> CWalletTx::GetConflicts() const
2608 set<uint256> result;
2609 if (pwallet != NULL)
2611 uint256 myHash = GetHash();
2612 result = pwallet->GetConflicts(myHash);
2613 result.erase(myHash);
2618 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
2624 if(filter & ISMINE_SPENDABLE)
2627 debit += nDebitCached;
2630 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
2631 fDebitCached = true;
2632 debit += nDebitCached;
2635 if(filter & ISMINE_WATCH_ONLY)
2637 if(fWatchDebitCached)
2638 debit += nWatchDebitCached;
2641 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
2642 fWatchDebitCached = true;
2643 debit += nWatchDebitCached;
2649 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
2651 // Must wait until coinbase is safely deep enough in the chain before valuing it
2652 if (IsCoinBase() && GetBlocksToMaturity() > 0)
2656 if (filter & ISMINE_SPENDABLE)
2658 // GetBalance can assume transactions in mapWallet won't change
2660 credit += nCreditCached;
2663 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
2664 fCreditCached = true;
2665 credit += nCreditCached;
2668 if (filter & ISMINE_WATCH_ONLY)
2670 if (fWatchCreditCached)
2671 credit += nWatchCreditCached;
2674 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
2675 fWatchCreditCached = true;
2676 credit += nWatchCreditCached;
2682 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
2684 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
2686 if (fUseCache && fImmatureCreditCached)
2687 return nImmatureCreditCached;
2688 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
2689 fImmatureCreditCached = true;
2690 return nImmatureCreditCached;
2696 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
2701 // Must wait until coinbase is safely deep enough in the chain before valuing it
2702 if (IsCoinBase() && GetBlocksToMaturity() > 0)
2705 if (fUseCache && fAvailableCreditCached)
2706 return nAvailableCreditCached;
2708 CAmount nCredit = 0;
2709 uint256 hashTx = GetHash();
2710 for (unsigned int i = 0; i < vout.size(); i++)
2712 if (!pwallet->IsSpent(hashTx, i))
2714 const CTxOut &txout = vout[i];
2715 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
2716 if (!MoneyRange(nCredit))
2717 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
2721 nAvailableCreditCached = nCredit;
2722 fAvailableCreditCached = true;
2726 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
2728 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
2730 if (fUseCache && fImmatureWatchCreditCached)
2731 return nImmatureWatchCreditCached;
2732 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
2733 fImmatureWatchCreditCached = true;
2734 return nImmatureWatchCreditCached;
2740 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
2745 // Must wait until coinbase is safely deep enough in the chain before valuing it
2746 if (IsCoinBase() && GetBlocksToMaturity() > 0)
2749 if (fUseCache && fAvailableWatchCreditCached)
2750 return nAvailableWatchCreditCached;
2752 CAmount nCredit = 0;
2753 for (unsigned int i = 0; i < vout.size(); i++)
2755 if (!pwallet->IsSpent(GetHash(), i))
2757 const CTxOut &txout = vout[i];
2758 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
2759 if (!MoneyRange(nCredit))
2760 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
2764 nAvailableWatchCreditCached = nCredit;
2765 fAvailableWatchCreditCached = true;
2769 CAmount CWalletTx::GetChange() const
2772 return nChangeCached;
2773 nChangeCached = pwallet->GetChange(*this);
2774 fChangeCached = true;
2775 return nChangeCached;
2778 bool CWalletTx::IsTrusted() const
2780 // Quick answer in most cases
2781 if (!CheckFinalTx(*this))
2783 int nDepth = GetDepthInMainChain();
2788 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
2791 // Trusted if all inputs are from us and are in the mempool:
2792 BOOST_FOREACH(const CTxIn& txin, vin)
2794 // Transactions not sent by us: not trusted
2795 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
2798 const CTxOut& parentOut = parent->vout[txin.prevout.n];
2799 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
2805 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
2807 std::vector<uint256> result;
2810 // Sort them in chronological order
2811 multimap<unsigned int, CWalletTx*> mapSorted;
2812 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
2814 CWalletTx& wtx = item.second;
2815 // Don't rebroadcast if newer than nTime:
2816 if (wtx.nTimeReceived > nTime)
2818 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
2820 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
2822 CWalletTx& wtx = *item.second;
2823 if (wtx.RelayWalletTransaction())
2824 result.push_back(wtx.GetHash());
2829 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
2831 // Do this infrequently and randomly to avoid giving away
2832 // that these are our transactions.
2833 if (GetTime() < nNextResend || !fBroadcastTransactions)
2835 bool fFirst = (nNextResend == 0);
2836 nNextResend = GetTime() + GetRand(30 * 60);
2840 // Only do it if there's been a new block since last time
2841 if (nBestBlockTime < nLastResend)
2843 nLastResend = GetTime();
2845 // Rebroadcast unconfirmed txes older than 5 minutes before the last
2847 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60);
2848 if (!relayed.empty())
2849 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
2852 /** @} */ // end of mapWallet
2857 /** @defgroup Actions
2863 CAmount CWallet::GetBalance() const
2867 LOCK2(cs_main, cs_wallet);
2868 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2870 const CWalletTx* pcoin = &(*it).second;
2871 if (pcoin->IsTrusted())
2872 nTotal += pcoin->GetAvailableCredit();
2879 CAmount CWallet::GetUnconfirmedBalance() const
2883 LOCK2(cs_main, cs_wallet);
2884 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2886 const CWalletTx* pcoin = &(*it).second;
2887 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
2888 nTotal += pcoin->GetAvailableCredit();
2894 CAmount CWallet::GetImmatureBalance() const
2898 LOCK2(cs_main, cs_wallet);
2899 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2901 const CWalletTx* pcoin = &(*it).second;
2902 nTotal += pcoin->GetImmatureCredit();
2908 CAmount CWallet::GetWatchOnlyBalance() const
2912 LOCK2(cs_main, cs_wallet);
2913 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2915 const CWalletTx* pcoin = &(*it).second;
2916 if (pcoin->IsTrusted())
2917 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2924 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2928 LOCK2(cs_main, cs_wallet);
2929 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2931 const CWalletTx* pcoin = &(*it).second;
2932 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
2933 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2939 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2943 LOCK2(cs_main, cs_wallet);
2944 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2946 const CWalletTx* pcoin = &(*it).second;
2947 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2954 * populate vCoins with vector of available COutputs.
2956 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue, bool fIncludeCoinBase) const
2961 LOCK2(cs_main, cs_wallet);
2962 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2964 const uint256& wtxid = it->first;
2965 const CWalletTx* pcoin = &(*it).second;
2967 if (!CheckFinalTx(*pcoin))
2970 if (fOnlyConfirmed && !pcoin->IsTrusted())
2973 if (pcoin->IsCoinBase() && !fIncludeCoinBase)
2976 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2979 int nDepth = pcoin->GetDepthInMainChain();
2983 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
2984 isminetype mine = IsMine(pcoin->vout[i]);
2985 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
2986 !IsLockedCoin((*it).first, i) && (pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
2987 (!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected((*it).first, i)))
2988 vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO));
2994 static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2995 vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2997 vector<char> vfIncluded;
2999 vfBest.assign(vValue.size(), true);
3000 nBest = nTotalLower;
3002 seed_insecure_rand();
3004 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
3006 vfIncluded.assign(vValue.size(), false);
3008 bool fReachedTarget = false;
3009 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3011 for (unsigned int i = 0; i < vValue.size(); i++)
3013 //The solver here uses a randomized algorithm,
3014 //the randomness serves no real security purpose but is just
3015 //needed to prevent degenerate behavior and it is important
3016 //that the rng is fast. We do not use a constant random sequence,
3017 //because there may be some privacy improvement by making
3018 //the selection random.
3019 if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
3021 nTotal += vValue[i].first;
3022 vfIncluded[i] = true;
3023 if (nTotal >= nTargetValue)
3025 fReachedTarget = true;
3029 vfBest = vfIncluded;
3031 nTotal -= vValue[i].first;
3032 vfIncluded[i] = false;
3040 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
3041 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
3043 setCoinsRet.clear();
3046 // List of values less than target
3047 pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
3048 coinLowestLarger.first = std::numeric_limits<CAmount>::max();
3049 coinLowestLarger.second.first = NULL;
3050 vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
3051 CAmount nTotalLower = 0;
3053 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3055 BOOST_FOREACH(const COutput &output, vCoins)
3057 if (!output.fSpendable)
3060 const CWalletTx *pcoin = output.tx;
3062 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
3066 CAmount n = pcoin->vout[i].nValue;
3068 pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
3070 if (n == nTargetValue)
3072 setCoinsRet.insert(coin.second);
3073 nValueRet += coin.first;
3076 else if (n < nTargetValue + CENT)
3078 vValue.push_back(coin);
3081 else if (n < coinLowestLarger.first)
3083 coinLowestLarger = coin;
3087 if (nTotalLower == nTargetValue)
3089 for (unsigned int i = 0; i < vValue.size(); ++i)
3091 setCoinsRet.insert(vValue[i].second);
3092 nValueRet += vValue[i].first;
3097 if (nTotalLower < nTargetValue)
3099 if (coinLowestLarger.second.first == NULL)
3101 setCoinsRet.insert(coinLowestLarger.second);
3102 nValueRet += coinLowestLarger.first;
3106 // Solve subset sum by stochastic approximation
3107 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
3108 vector<char> vfBest;
3111 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
3112 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
3113 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
3115 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
3116 // or the next bigger coin is closer), return the bigger coin
3117 if (coinLowestLarger.second.first &&
3118 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
3120 setCoinsRet.insert(coinLowestLarger.second);
3121 nValueRet += coinLowestLarger.first;
3124 for (unsigned int i = 0; i < vValue.size(); i++)
3127 setCoinsRet.insert(vValue[i].second);
3128 nValueRet += vValue[i].first;
3131 LogPrint("selectcoins", "SelectCoins() best subset: ");
3132 for (unsigned int i = 0; i < vValue.size(); i++)
3134 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
3135 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
3141 bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, bool& fOnlyCoinbaseCoinsRet, bool& fNeedCoinbaseCoinsRet, const CCoinControl* coinControl) const
3143 // Output parameter fOnlyCoinbaseCoinsRet is set to true when the only available coins are coinbase utxos.
3144 vector<COutput> vCoinsNoCoinbase, vCoinsWithCoinbase;
3145 AvailableCoins(vCoinsNoCoinbase, true, coinControl, false, false);
3146 AvailableCoins(vCoinsWithCoinbase, true, coinControl, false, true);
3147 fOnlyCoinbaseCoinsRet = vCoinsNoCoinbase.size() == 0 && vCoinsWithCoinbase.size() > 0;
3149 // If coinbase utxos can only be sent to zaddrs, exclude any coinbase utxos from coin selection.
3150 bool fProtectCoinbase = Params().GetConsensus().fCoinbaseMustBeProtected;
3151 vector<COutput> vCoins = (fProtectCoinbase) ? vCoinsNoCoinbase : vCoinsWithCoinbase;
3153 // Output parameter fNeedCoinbaseCoinsRet is set to true if coinbase utxos need to be spent to meet target amount
3154 if (fProtectCoinbase && vCoinsWithCoinbase.size() > vCoinsNoCoinbase.size()) {
3156 for (const COutput& out : vCoinsNoCoinbase) {
3157 if (!out.fSpendable) {
3160 value += out.tx->vout[out.i].nValue;
3162 if (value <= nTargetValue) {
3163 CAmount valueWithCoinbase = 0;
3164 for (const COutput& out : vCoinsWithCoinbase) {
3165 if (!out.fSpendable) {
3168 valueWithCoinbase += out.tx->vout[out.i].nValue;
3170 fNeedCoinbaseCoinsRet = (valueWithCoinbase >= nTargetValue);
3174 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
3175 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
3177 BOOST_FOREACH(const COutput& out, vCoins)
3179 if (!out.fSpendable)
3181 nValueRet += out.tx->vout[out.i].nValue;
3182 setCoinsRet.insert(make_pair(out.tx, out.i));
3184 return (nValueRet >= nTargetValue);
3187 // calculate value from preset inputs and store them
3188 set<pair<const CWalletTx*, uint32_t> > setPresetCoins;
3189 CAmount nValueFromPresetInputs = 0;
3191 std::vector<COutPoint> vPresetInputs;
3193 coinControl->ListSelected(vPresetInputs);
3194 BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
3196 map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
3197 if (it != mapWallet.end())
3199 const CWalletTx* pcoin = &it->second;
3200 // Clearly invalid input, fail
3201 if (pcoin->vout.size() <= outpoint.n)
3203 nValueFromPresetInputs += pcoin->vout[outpoint.n].nValue;
3204 setPresetCoins.insert(make_pair(pcoin, outpoint.n));
3206 return false; // TODO: Allow non-wallet inputs
3209 // remove preset inputs from vCoins
3210 for (vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
3212 if (setPresetCoins.count(make_pair(it->tx, it->i)))
3213 it = vCoins.erase(it);
3218 bool res = nTargetValue <= nValueFromPresetInputs ||
3219 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, vCoins, setCoinsRet, nValueRet) ||
3220 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, vCoins, setCoinsRet, nValueRet) ||
3221 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, vCoins, setCoinsRet, nValueRet));
3223 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
3224 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
3226 // add preset inputs to the total value selected
3227 nValueRet += nValueFromPresetInputs;
3232 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount &nFeeRet, int& nChangePosRet, std::string& strFailReason)
3234 vector<CRecipient> vecSend;
3236 // Turn the txout set into a CRecipient vector
3237 BOOST_FOREACH(const CTxOut& txOut, tx.vout)
3239 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, false};
3240 vecSend.push_back(recipient);
3243 CCoinControl coinControl;
3244 coinControl.fAllowOtherInputs = true;
3245 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3246 coinControl.Select(txin.prevout);
3248 CReserveKey reservekey(this);
3251 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosRet, strFailReason, &coinControl, false))
3254 if (nChangePosRet != -1)
3255 tx.vout.insert(tx.vout.begin() + nChangePosRet, wtx.vout[nChangePosRet]);
3257 // Add new txins (keeping original txin scriptSig/order)
3258 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
3261 BOOST_FOREACH(const CTxIn& origTxIn, tx.vin)
3263 if (txin.prevout.hash == origTxIn.prevout.hash && txin.prevout.n == origTxIn.prevout.n)
3270 tx.vin.push_back(txin);
3276 bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
3277 int& nChangePosRet, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
3280 unsigned int nSubtractFeeFromAmount = 0;
3281 BOOST_FOREACH (const CRecipient& recipient, vecSend)
3283 if (nValue < 0 || recipient.nAmount < 0)
3285 strFailReason = _("Transaction amounts must be positive");
3288 nValue += recipient.nAmount;
3290 if (recipient.fSubtractFeeFromAmount)
3291 nSubtractFeeFromAmount++;
3293 if (vecSend.empty() || nValue < 0)
3295 strFailReason = _("Transaction amounts must be positive");
3299 wtxNew.fTimeReceivedIsTxTime = true;
3300 wtxNew.BindWallet(this);
3301 int nextBlockHeight = chainActive.Height() + 1;
3302 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(
3303 Params().GetConsensus(), nextBlockHeight);
3305 // Activates after Overwinter network upgrade
3306 if (NetworkUpgradeActive(nextBlockHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER)) {
3307 if (txNew.nExpiryHeight >= TX_EXPIRY_HEIGHT_THRESHOLD){
3308 strFailReason = _("nExpiryHeight must be less than TX_EXPIRY_HEIGHT_THRESHOLD.");
3313 unsigned int max_tx_size = MAX_TX_SIZE_AFTER_SAPLING;
3314 if (!NetworkUpgradeActive(nextBlockHeight, Params().GetConsensus(), Consensus::UPGRADE_SAPLING)) {
3315 max_tx_size = MAX_TX_SIZE_BEFORE_SAPLING;
3318 // Discourage fee sniping.
3320 // However because of a off-by-one-error in previous versions we need to
3321 // neuter it by setting nLockTime to at least one less than nBestHeight.
3322 // Secondly currently propagation of transactions created for block heights
3323 // corresponding to blocks that were just mined may be iffy - transactions
3324 // aren't re-accepted into the mempool - we additionally neuter the code by
3325 // going ten blocks back. Doesn't yet do anything for sniping, but does act
3326 // to shake out wallet bugs like not showing nLockTime'd transactions at
3328 txNew.nLockTime = std::max(0, chainActive.Height() - 10);
3330 // Secondly occasionally randomly pick a nLockTime even further back, so
3331 // that transactions that are delayed after signing for whatever reason,
3332 // e.g. high-latency mix networks and some CoinJoin implementations, have
3334 if (GetRandInt(10) == 0)
3335 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
3337 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
3338 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
3341 LOCK2(cs_main, cs_wallet);
3348 wtxNew.fFromMe = true;
3352 CAmount nTotalValue = nValue;
3353 if (nSubtractFeeFromAmount == 0)
3354 nTotalValue += nFeeRet;
3355 double dPriority = 0;
3356 // vouts to the payees
3357 BOOST_FOREACH (const CRecipient& recipient, vecSend)
3359 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
3361 if (recipient.fSubtractFeeFromAmount)
3363 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
3365 if (fFirst) // first receiver pays the remainder not divisible by output count
3368 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
3372 if (txout.IsDust(::minRelayTxFee))
3374 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
3376 if (txout.nValue < 0)
3377 strFailReason = _("The transaction amount is too small to pay the fee");
3379 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
3382 strFailReason = _("Transaction amount too small");
3385 txNew.vout.push_back(txout);
3388 // Choose coins to use
3389 set<pair<const CWalletTx*,unsigned int> > setCoins;
3390 CAmount nValueIn = 0;
3391 bool fOnlyCoinbaseCoins = false;
3392 bool fNeedCoinbaseCoins = false;
3393 if (!SelectCoins(nTotalValue, setCoins, nValueIn, fOnlyCoinbaseCoins, fNeedCoinbaseCoins, coinControl))
3395 if (fOnlyCoinbaseCoins && Params().GetConsensus().fCoinbaseMustBeProtected) {
3396 strFailReason = _("Coinbase funds can only be sent to a zaddr");
3397 } else if (fNeedCoinbaseCoins) {
3398 strFailReason = _("Insufficient funds, coinbase funds can only be spent after they have been sent to a zaddr");
3400 strFailReason = _("Insufficient funds");
3404 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
3406 CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
3407 //The coin age after the next block (depth+1) is used instead of the current,
3408 //reflecting an assumption the user would accept a bit more delay for
3409 //a chance at a free transaction.
3410 //But mempool inputs might still be in the mempool, so their age stays 0
3411 int age = pcoin.first->GetDepthInMainChain();
3414 dPriority += (double)nCredit * age;
3417 CAmount nChange = nValueIn - nValue;
3418 if (nSubtractFeeFromAmount == 0)
3423 // Fill a vout to ourself
3424 // TODO: pass in scriptChange instead of reservekey so
3425 // change transaction isn't always pay-to-bitcoin-address
3426 CScript scriptChange;
3428 // coin control: send change to custom address
3429 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
3430 scriptChange = GetScriptForDestination(coinControl->destChange);
3432 // no coin control: send change to newly generated address
3435 // Note: We use a new key here to keep it from being obvious which side is the change.
3436 // The drawback is that by not reusing a previous key, the change may be lost if a
3437 // backup is restored, if the backup doesn't have the new private key for the change.
3438 // If we reused the old key, it would be possible to add code to look for and
3439 // rediscover unknown transactions that were written with keys of ours to recover
3440 // post-backup change.
3442 // Reserve a new key pair from key pool
3445 ret = reservekey.GetReservedKey(vchPubKey);
3446 assert(ret); // should never fail, as we just unlocked
3448 scriptChange = GetScriptForDestination(vchPubKey.GetID());
3451 CTxOut newTxOut(nChange, scriptChange);
3453 // We do not move dust-change to fees, because the sender would end up paying more than requested.
3454 // This would be against the purpose of the all-inclusive feature.
3455 // So instead we raise the change and deduct from the recipient.
3456 if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust(::minRelayTxFee))
3458 CAmount nDust = newTxOut.GetDustThreshold(::minRelayTxFee) - newTxOut.nValue;
3459 newTxOut.nValue += nDust; // raise change until no more dust
3460 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
3462 if (vecSend[i].fSubtractFeeFromAmount)
3464 txNew.vout[i].nValue -= nDust;
3465 if (txNew.vout[i].IsDust(::minRelayTxFee))
3467 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
3475 // Never create dust outputs; if we would, just
3476 // add the dust to the fee.
3477 if (newTxOut.IsDust(::minRelayTxFee))
3480 reservekey.ReturnKey();
3484 // Insert change txn at random position:
3485 nChangePosRet = GetRandInt(txNew.vout.size()+1);
3486 vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosRet;
3487 txNew.vout.insert(position, newTxOut);
3491 reservekey.ReturnKey();
3495 // Note how the sequence number is set to max()-1 so that the
3496 // nLockTime set above actually works.
3497 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
3498 txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
3499 std::numeric_limits<unsigned int>::max()-1));
3501 // Check mempooltxinputlimit to avoid creating a transaction which the local mempool rejects
3502 size_t limit = (size_t)GetArg("-mempooltxinputlimit", 0);
3505 if (NetworkUpgradeActive(chainActive.Height() + 1, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER)) {
3510 size_t n = txNew.vin.size();
3512 strFailReason = _(strprintf("Too many transparent inputs %zu > limit %zu", n, limit).c_str());
3517 // Grab the current consensus branch ID
3518 auto consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus());
3522 CTransaction txNewConst(txNew);
3523 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
3526 const CScript& scriptPubKey = coin.first->vout[coin.second].scriptPubKey;
3527 SignatureData sigdata;
3529 signSuccess = ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.first->vout[coin.second].nValue, SIGHASH_ALL), scriptPubKey, sigdata, consensusBranchId);
3531 signSuccess = ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata, consensusBranchId);
3535 strFailReason = _("Signing transaction failed");
3538 UpdateTransaction(txNew, nIn, sigdata);
3544 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
3546 // Remove scriptSigs if we used dummy signatures for fee calculation
3548 BOOST_FOREACH (CTxIn& vin, txNew.vin)
3549 vin.scriptSig = CScript();
3552 // Embed the constructed transaction data in wtxNew.
3553 *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
3556 if (nBytes >= max_tx_size)
3558 strFailReason = _("Transaction too large");
3562 dPriority = wtxNew.ComputePriority(dPriority, nBytes);
3564 // Can we complete this as a free transaction?
3565 if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
3567 // Not enough fee: enough priority?
3568 double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
3569 // Not enough mempool history to estimate: use hard-coded AllowFree.
3570 if (dPriorityNeeded <= 0 && AllowFree(dPriority))
3573 // Small enough, and priority high enough, to send for free
3574 if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
3578 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
3580 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
3581 // because we must be at the maximum allowed fee.
3582 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
3584 strFailReason = _("Transaction too large for fee policy");
3588 if (nFeeRet >= nFeeNeeded)
3589 break; // Done, enough fee included.
3591 // Include more fee and try again.
3592 nFeeRet = nFeeNeeded;
3602 * Call after CreateTransaction unless you want to abort
3604 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
3607 LOCK2(cs_main, cs_wallet);
3608 LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
3610 // This is only to keep the database open to defeat the auto-flush for the
3611 // duration of this scope. This is the only place where this optimization
3612 // maybe makes sense; please don't do it anywhere else.
3613 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r+") : NULL;
3615 // Take key pair from key pool so it won't be used again
3616 reservekey.KeepKey();
3618 // Add tx to wallet, because if it has change it's also ours,
3619 // otherwise just for transaction history.
3620 AddToWallet(wtxNew, false, pwalletdb);
3622 // Notify that old coins are spent
3623 set<CWalletTx*> setCoins;
3624 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
3626 CWalletTx &coin = mapWallet[txin.prevout.hash];
3627 coin.BindWallet(this);
3628 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
3635 // Track how many getdata requests our transaction gets
3636 mapRequestCount[wtxNew.GetHash()] = 0;
3638 if (fBroadcastTransactions)
3641 if (!wtxNew.AcceptToMemoryPool(false))
3643 // This must not fail. The transaction has already been signed and recorded.
3644 LogPrintf("CommitTransaction(): Error: Transaction not valid\n");
3647 wtxNew.RelayWalletTransaction();
3653 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
3655 // payTxFee is user-set "I want to pay this much"
3656 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
3657 // user selected total at least (default=true)
3658 if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
3659 nFeeNeeded = payTxFee.GetFeePerK();
3660 // User didn't set: use -txconfirmtarget to estimate...
3661 if (nFeeNeeded == 0)
3662 nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
3663 // ... unless we don't have enough mempool data, in which case fall
3664 // back to a hard-coded fee
3665 if (nFeeNeeded == 0)
3666 nFeeNeeded = minTxFee.GetFee(nTxBytes);
3667 // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
3668 if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
3669 nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
3670 // But always obey the maximum
3671 if (nFeeNeeded > maxTxFee)
3672 nFeeNeeded = maxTxFee;
3679 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3683 fFirstRunRet = false;
3684 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
3685 if (nLoadWalletRet == DB_NEED_REWRITE)
3687 if (CDB::Rewrite(strWalletFile, "\x04pool"))
3691 // Note: can't top-up keypool here, because wallet is locked.
3692 // User will be prompted to unlock wallet the next operation
3693 // that requires a new key.
3697 if (nLoadWalletRet != DB_LOAD_OK)
3698 return nLoadWalletRet;
3699 fFirstRunRet = !vchDefaultKey.IsValid();
3701 uiInterface.LoadWallet(this);
3707 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3711 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
3712 if (nZapWalletTxRet == DB_NEED_REWRITE)
3714 if (CDB::Rewrite(strWalletFile, "\x04pool"))
3718 // Note: can't top-up keypool here, because wallet is locked.
3719 // User will be prompted to unlock wallet the next operation
3720 // that requires a new key.
3724 if (nZapWalletTxRet != DB_LOAD_OK)
3725 return nZapWalletTxRet;
3731 bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
3733 bool fUpdated = false;
3735 LOCK(cs_wallet); // mapAddressBook
3736 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3737 fUpdated = mi != mapAddressBook.end();
3738 mapAddressBook[address].name = strName;
3739 if (!strPurpose.empty()) /* update purpose only if requested */
3740 mapAddressBook[address].purpose = strPurpose;
3742 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3743 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3746 if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(EncodeDestination(address), strPurpose))
3748 return CWalletDB(strWalletFile).WriteName(EncodeDestination(address), strName);
3751 bool CWallet::DelAddressBook(const CTxDestination& address)
3754 LOCK(cs_wallet); // mapAddressBook
3758 // Delete destdata tuples associated with address
3759 std::string strAddress = EncodeDestination(address);
3760 BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
3762 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
3765 mapAddressBook.erase(address);
3768 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3772 CWalletDB(strWalletFile).ErasePurpose(EncodeDestination(address));
3773 return CWalletDB(strWalletFile).EraseName(EncodeDestination(address));
3776 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3780 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
3783 vchDefaultKey = vchPubKey;
3788 * Mark old keypool keys as used,
3789 * and generate all new keys
3791 bool CWallet::NewKeyPool()
3795 CWalletDB walletdb(strWalletFile);
3796 BOOST_FOREACH(int64_t nIndex, setKeyPool)
3797 walletdb.ErasePool(nIndex);
3803 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
3804 for (int i = 0; i < nKeys; i++)
3806 int64_t nIndex = i+1;
3807 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
3808 setKeyPool.insert(nIndex);
3810 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
3815 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3823 CWalletDB walletdb(strWalletFile);
3826 unsigned int nTargetSize;
3828 nTargetSize = kpSize;
3830 nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0);
3832 while (setKeyPool.size() < (nTargetSize + 1))
3835 if (!setKeyPool.empty())
3836 nEnd = *(--setKeyPool.end()) + 1;
3837 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
3838 throw runtime_error("TopUpKeyPool(): writing generated key failed");
3839 setKeyPool.insert(nEnd);
3840 LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
3846 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
3849 keypool.vchPubKey = CPubKey();
3856 // Get the oldest key
3857 if(setKeyPool.empty())
3860 CWalletDB walletdb(strWalletFile);
3862 nIndex = *(setKeyPool.begin());
3863 setKeyPool.erase(setKeyPool.begin());
3864 if (!walletdb.ReadPool(nIndex, keypool))
3865 throw runtime_error("ReserveKeyFromKeyPool(): read failed");
3866 if (!HaveKey(keypool.vchPubKey.GetID()))
3867 throw runtime_error("ReserveKeyFromKeyPool(): unknown key in key pool");
3868 assert(keypool.vchPubKey.IsValid());
3869 LogPrintf("keypool reserve %d\n", nIndex);
3873 void CWallet::KeepKey(int64_t nIndex)
3875 // Remove from key pool
3878 CWalletDB walletdb(strWalletFile);
3879 walletdb.ErasePool(nIndex);
3881 LogPrintf("keypool keep %d\n", nIndex);
3884 void CWallet::ReturnKey(int64_t nIndex)
3886 // Return to key pool
3889 setKeyPool.insert(nIndex);
3891 LogPrintf("keypool return %d\n", nIndex);
3894 bool CWallet::GetKeyFromPool(CPubKey& result)
3900 ReserveKeyFromKeyPool(nIndex, keypool);
3903 if (IsLocked()) return false;
3904 result = GenerateNewKey();
3908 result = keypool.vchPubKey;
3913 int64_t CWallet::GetOldestKeyPoolTime()
3917 ReserveKeyFromKeyPool(nIndex, keypool);
3921 return keypool.nTime;
3924 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3926 map<CTxDestination, CAmount> balances;
3930 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3932 CWalletTx *pcoin = &walletEntry.second;
3934 if (!CheckFinalTx(*pcoin) || !pcoin->IsTrusted())
3937 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3940 int nDepth = pcoin->GetDepthInMainChain();
3941 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3944 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
3946 CTxDestination addr;
3947 if (!IsMine(pcoin->vout[i]))
3949 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
3952 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
3954 if (!balances.count(addr))
3956 balances[addr] += n;
3964 set< set<CTxDestination> > CWallet::GetAddressGroupings()
3966 AssertLockHeld(cs_wallet); // mapWallet
3967 set< set<CTxDestination> > groupings;
3968 set<CTxDestination> grouping;
3970 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3972 CWalletTx *pcoin = &walletEntry.second;
3974 if (pcoin->vin.size() > 0)
3976 bool any_mine = false;
3977 // group all input addresses with each other
3978 BOOST_FOREACH(CTxIn txin, pcoin->vin)
3980 CTxDestination address;
3981 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3983 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
3985 grouping.insert(address);
3989 // group change with input addresses
3992 BOOST_FOREACH(CTxOut txout, pcoin->vout)
3993 if (IsChange(txout))
3995 CTxDestination txoutAddr;
3996 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3998 grouping.insert(txoutAddr);
4001 if (grouping.size() > 0)
4003 groupings.insert(grouping);
4008 // group lone addrs by themselves
4009 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
4010 if (IsMine(pcoin->vout[i]))
4012 CTxDestination address;
4013 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
4015 grouping.insert(address);
4016 groupings.insert(grouping);
4021 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
4022 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
4023 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
4025 // make a set of all the groups hit by this new group
4026 set< set<CTxDestination>* > hits;
4027 map< CTxDestination, set<CTxDestination>* >::iterator it;
4028 BOOST_FOREACH(CTxDestination address, grouping)
4029 if ((it = setmap.find(address)) != setmap.end())
4030 hits.insert((*it).second);
4032 // merge all hit groups into a new single group and delete old groups
4033 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
4034 BOOST_FOREACH(set<CTxDestination>* hit, hits)
4036 merged->insert(hit->begin(), hit->end());
4037 uniqueGroupings.erase(hit);
4040 uniqueGroupings.insert(merged);
4043 BOOST_FOREACH(CTxDestination element, *merged)
4044 setmap[element] = merged;
4047 set< set<CTxDestination> > ret;
4048 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
4050 ret.insert(*uniqueGrouping);
4051 delete uniqueGrouping;
4057 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
4060 set<CTxDestination> result;
4061 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
4063 const CTxDestination& address = item.first;
4064 const string& strName = item.second.name;
4065 if (strName == strAccount)
4066 result.insert(address);
4071 bool CReserveKey::GetReservedKey(CPubKey& pubkey)
4076 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
4078 vchPubKey = keypool.vchPubKey;
4083 assert(vchPubKey.IsValid());
4088 void CReserveKey::KeepKey()
4091 pwallet->KeepKey(nIndex);
4093 vchPubKey = CPubKey();
4096 void CReserveKey::ReturnKey()
4099 pwallet->ReturnKey(nIndex);
4101 vchPubKey = CPubKey();
4104 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
4108 CWalletDB walletdb(strWalletFile);
4110 LOCK2(cs_main, cs_wallet);
4111 BOOST_FOREACH(const int64_t& id, setKeyPool)
4114 if (!walletdb.ReadPool(id, keypool))
4115 throw runtime_error("GetAllReserveKeyHashes(): read failed");
4116 assert(keypool.vchPubKey.IsValid());
4117 CKeyID keyID = keypool.vchPubKey.GetID();
4118 if (!HaveKey(keyID))
4119 throw runtime_error("GetAllReserveKeyHashes(): unknown key in key pool");
4120 setAddress.insert(keyID);
4124 void CWallet::UpdatedTransaction(const uint256 &hashTx)
4128 // Only notify UI if this transaction is in this wallet
4129 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
4130 if (mi != mapWallet.end())
4131 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
4135 void CWallet::GetScriptForMining(boost::shared_ptr<CReserveScript> &script)
4137 if (!GetArg("-mineraddress", "").empty()) {
4141 boost::shared_ptr<CReserveKey> rKey(new CReserveKey(this));
4143 if (!rKey->GetReservedKey(pubkey))
4147 script->reserveScript = CScript() << OP_DUP << OP_HASH160 << ToByteVector(pubkey.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG;
4150 void CWallet::LockCoin(COutPoint& output)
4152 AssertLockHeld(cs_wallet); // setLockedCoins
4153 setLockedCoins.insert(output);
4156 void CWallet::UnlockCoin(COutPoint& output)
4158 AssertLockHeld(cs_wallet); // setLockedCoins
4159 setLockedCoins.erase(output);
4162 void CWallet::UnlockAllCoins()
4164 AssertLockHeld(cs_wallet); // setLockedCoins
4165 setLockedCoins.clear();
4168 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
4170 AssertLockHeld(cs_wallet); // setLockedCoins
4171 COutPoint outpt(hash, n);
4173 return (setLockedCoins.count(outpt) > 0);
4176 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
4178 AssertLockHeld(cs_wallet); // setLockedCoins
4179 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
4180 it != setLockedCoins.end(); it++) {
4181 COutPoint outpt = (*it);
4182 vOutpts.push_back(outpt);
4187 // Note Locking Operations
4189 void CWallet::LockNote(const JSOutPoint& output)
4191 AssertLockHeld(cs_wallet); // setLockedSproutNotes
4192 setLockedSproutNotes.insert(output);
4195 void CWallet::UnlockNote(const JSOutPoint& output)
4197 AssertLockHeld(cs_wallet); // setLockedSproutNotes
4198 setLockedSproutNotes.erase(output);
4201 void CWallet::UnlockAllSproutNotes()
4203 AssertLockHeld(cs_wallet); // setLockedSproutNotes
4204 setLockedSproutNotes.clear();
4207 bool CWallet::IsLockedNote(const JSOutPoint& outpt) const
4209 AssertLockHeld(cs_wallet); // setLockedSproutNotes
4211 return (setLockedSproutNotes.count(outpt) > 0);
4214 std::vector<JSOutPoint> CWallet::ListLockedSproutNotes()
4216 AssertLockHeld(cs_wallet); // setLockedSproutNotes
4217 std::vector<JSOutPoint> vOutpts(setLockedSproutNotes.begin(), setLockedSproutNotes.end());
4221 void CWallet::LockNote(const SaplingOutPoint& output)
4223 AssertLockHeld(cs_wallet);
4224 setLockedSaplingNotes.insert(output);
4227 void CWallet::UnlockNote(const SaplingOutPoint& output)
4229 AssertLockHeld(cs_wallet);
4230 setLockedSaplingNotes.erase(output);
4233 void CWallet::UnlockAllSaplingNotes()
4235 AssertLockHeld(cs_wallet);
4236 setLockedSaplingNotes.clear();
4239 bool CWallet::IsLockedNote(const SaplingOutPoint& output) const
4241 AssertLockHeld(cs_wallet);
4242 return (setLockedSaplingNotes.count(output) > 0);
4245 std::vector<SaplingOutPoint> CWallet::ListLockedSaplingNotes()
4247 AssertLockHeld(cs_wallet);
4248 std::vector<SaplingOutPoint> vOutputs(setLockedSaplingNotes.begin(), setLockedSaplingNotes.end());
4252 /** @} */ // end of Actions
4254 class CAffectedKeysVisitor : public boost::static_visitor<void> {
4256 const CKeyStore &keystore;
4257 std::vector<CKeyID> &vKeys;
4260 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
4262 void Process(const CScript &script) {
4264 std::vector<CTxDestination> vDest;
4266 if (ExtractDestinations(script, type, vDest, nRequired)) {
4267 BOOST_FOREACH(const CTxDestination &dest, vDest)
4268 boost::apply_visitor(*this, dest);
4272 void operator()(const CKeyID &keyId) {
4273 if (keystore.HaveKey(keyId))
4274 vKeys.push_back(keyId);
4277 void operator()(const CScriptID &scriptId) {
4279 if (keystore.GetCScript(scriptId, script))
4283 void operator()(const CNoDestination &none) {}
4286 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
4287 AssertLockHeld(cs_wallet); // mapKeyMetadata
4288 mapKeyBirth.clear();
4290 // get birth times for keys with metadata
4291 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
4292 if (it->second.nCreateTime)
4293 mapKeyBirth[it->first] = it->second.nCreateTime;
4295 // map in which we'll infer heights of other keys
4296 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
4297 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
4298 std::set<CKeyID> setKeys;
4300 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
4301 if (mapKeyBirth.count(keyid) == 0)
4302 mapKeyFirstBlock[keyid] = pindexMax;
4306 // if there are no such keys, we're done
4307 if (mapKeyFirstBlock.empty())
4310 // find first block that affects those keys, if there are any left
4311 std::vector<CKeyID> vAffected;
4312 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
4313 // iterate over all wallet transactions...
4314 const CWalletTx &wtx = (*it).second;
4315 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
4316 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
4317 // ... which are already in a block
4318 int nHeight = blit->second->nHeight;
4319 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
4320 // iterate over all their outputs
4321 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
4322 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
4323 // ... and all their affected keys
4324 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
4325 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
4326 rit->second = blit->second;
4333 // Extract block timestamps for those keys
4334 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
4335 mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
4338 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
4340 if (boost::get<CNoDestination>(&dest))
4343 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
4346 return CWalletDB(strWalletFile).WriteDestData(EncodeDestination(dest), key, value);
4349 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
4351 if (!mapAddressBook[dest].destdata.erase(key))
4355 return CWalletDB(strWalletFile).EraseDestData(EncodeDestination(dest), key);
4358 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
4360 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
4364 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
4366 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
4367 if(i != mapAddressBook.end())
4369 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
4370 if(j != i->second.destdata.end())
4380 CKeyPool::CKeyPool()
4385 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
4388 vchPubKey = vchPubKeyIn;
4391 CWalletKey::CWalletKey(int64_t nExpires)
4393 nTimeCreated = (nExpires ? GetTime() : 0);
4394 nTimeExpires = nExpires;
4397 int CMerkleTx::SetMerkleBranch(const CBlock& block)
4399 AssertLockHeld(cs_main);
4402 // Update the tx's hashBlock
4403 hashBlock = block.GetHash();
4405 // Locate the transaction
4406 for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
4407 if (block.vtx[nIndex] == *(CTransaction*)this)
4409 if (nIndex == (int)block.vtx.size())
4411 vMerkleBranch.clear();
4413 LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
4417 // Fill in merkle branch
4418 vMerkleBranch = block.GetMerkleBranch(nIndex);
4420 // Is the tx in a block that's in the main chain
4421 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4422 if (mi == mapBlockIndex.end())
4424 const CBlockIndex* pindex = (*mi).second;
4425 if (!pindex || !chainActive.Contains(pindex))
4428 return chainActive.Height() - pindex->nHeight + 1;
4431 int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const
4433 if (hashBlock.IsNull() || nIndex == -1)
4435 AssertLockHeld(cs_main);
4437 // Find the block it claims to be in
4438 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4439 if (mi == mapBlockIndex.end())
4441 CBlockIndex* pindex = (*mi).second;
4442 if (!pindex || !chainActive.Contains(pindex))
4445 // Make sure the merkle branch connects to this block
4446 if (!fMerkleVerified)
4448 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
4450 fMerkleVerified = true;
4454 return chainActive.Height() - pindex->nHeight + 1;
4457 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4459 AssertLockHeld(cs_main);
4460 int nResult = GetDepthInMainChainINTERNAL(pindexRet);
4461 if (nResult == 0 && !mempool.exists(GetHash()))
4462 return -1; // Not in chain, not in mempool
4467 int CMerkleTx::GetBlocksToMaturity() const
4471 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4475 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectAbsurdFee)
4477 CValidationState state;
4478 return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectAbsurdFee);
4482 * Find notes in the wallet filtered by payment address, min depth and ability to spend.
4483 * These notes are decrypted and added to the output parameter vector, outEntries.
4485 void CWallet::GetFilteredNotes(
4486 std::vector<CSproutNotePlaintextEntry>& sproutEntries,
4487 std::vector<SaplingNoteEntry>& saplingEntries,
4488 std::string address,
4491 bool requireSpendingKey)
4493 std::set<PaymentAddress> filterAddresses;
4495 if (address.length() > 0) {
4496 filterAddresses.insert(DecodePaymentAddress(address));
4499 GetFilteredNotes(sproutEntries, saplingEntries, filterAddresses, minDepth, INT_MAX, ignoreSpent, requireSpendingKey);
4503 * Find notes in the wallet filtered by payment addresses, min depth, max depth,
4504 * if the note is spent, if a spending key is required, and if the notes are locked.
4505 * These notes are decrypted and added to the output parameter vector, outEntries.
4507 void CWallet::GetFilteredNotes(
4508 std::vector<CSproutNotePlaintextEntry>& sproutEntries,
4509 std::vector<SaplingNoteEntry>& saplingEntries,
4510 std::set<PaymentAddress>& filterAddresses,
4514 bool requireSpendingKey,
4517 LOCK2(cs_main, cs_wallet);
4519 for (auto & p : mapWallet) {
4520 CWalletTx wtx = p.second;
4522 // Filter the transactions before checking for notes
4523 if (!CheckFinalTx(wtx) ||
4524 wtx.GetBlocksToMaturity() > 0 ||
4525 wtx.GetDepthInMainChain() < minDepth ||
4526 wtx.GetDepthInMainChain() > maxDepth) {
4530 for (auto & pair : wtx.mapSproutNoteData) {
4531 JSOutPoint jsop = pair.first;
4532 SproutNoteData nd = pair.second;
4533 SproutPaymentAddress pa = nd.address;
4535 // skip notes which belong to a different payment address in the wallet
4536 if (!(filterAddresses.empty() || filterAddresses.count(pa))) {
4540 // skip note which has been spent
4541 if (ignoreSpent && nd.nullifier && IsSproutSpent(*nd.nullifier)) {
4545 // skip notes which cannot be spent
4546 if (requireSpendingKey && !HaveSproutSpendingKey(pa)) {
4550 // skip locked notes
4551 if (ignoreLocked && IsLockedNote(jsop)) {
4555 int i = jsop.js; // Index into CTransaction.vjoinsplit
4556 int j = jsop.n; // Index into JSDescription.ciphertexts
4558 // Get cached decryptor
4559 ZCNoteDecryption decryptor;
4560 if (!GetNoteDecryptor(pa, decryptor)) {
4561 // Note decryptors are created when the wallet is loaded, so it should always exist
4562 throw std::runtime_error(strprintf("Could not find note decryptor for payment address %s", EncodePaymentAddress(pa)));
4565 // determine amount of funds in the note
4566 auto hSig = wtx.vjoinsplit[i].h_sig(*pzcashParams, wtx.joinSplitPubKey);
4568 SproutNotePlaintext plaintext = SproutNotePlaintext::decrypt(
4570 wtx.vjoinsplit[i].ciphertexts[j],
4571 wtx.vjoinsplit[i].ephemeralKey,
4575 sproutEntries.push_back(CSproutNotePlaintextEntry{jsop, pa, plaintext, wtx.GetDepthInMainChain()});
4577 } catch (const note_decryption_failed &err) {
4578 // Couldn't decrypt with this spending key
4579 throw std::runtime_error(strprintf("Could not decrypt note for payment address %s", EncodePaymentAddress(pa)));
4580 } catch (const std::exception &exc) {
4581 // Unexpected failure
4582 throw std::runtime_error(strprintf("Error while decrypting note for payment address %s: %s", EncodePaymentAddress(pa), exc.what()));
4586 for (auto & pair : wtx.mapSaplingNoteData) {
4587 SaplingOutPoint op = pair.first;
4588 SaplingNoteData nd = pair.second;
4590 auto maybe_pt = SaplingNotePlaintext::decrypt(
4591 wtx.vShieldedOutput[op.n].encCiphertext,
4593 wtx.vShieldedOutput[op.n].ephemeralKey,
4594 wtx.vShieldedOutput[op.n].cm);
4595 assert(static_cast<bool>(maybe_pt));
4596 auto notePt = maybe_pt.get();
4598 auto maybe_pa = nd.ivk.address(notePt.d);
4599 assert(static_cast<bool>(maybe_pa));
4600 auto pa = maybe_pa.get();
4602 // skip notes which belong to a different payment address in the wallet
4603 if (!(filterAddresses.empty() || filterAddresses.count(pa))) {
4607 if (ignoreSpent && nd.nullifier && IsSaplingSpent(*nd.nullifier)) {
4611 // skip notes which cannot be spent
4612 if (requireSpendingKey) {
4613 libzcash::SaplingIncomingViewingKey ivk;
4614 libzcash::SaplingFullViewingKey fvk;
4615 if (!(GetSaplingIncomingViewingKey(pa, ivk) &&
4616 GetSaplingFullViewingKey(ivk, fvk) &&
4617 HaveSaplingSpendingKey(fvk))) {
4622 // skip locked notes
4623 if (ignoreLocked && IsLockedNote(op)) {
4627 auto note = notePt.note(nd.ivk).get();
4628 saplingEntries.push_back(SaplingNoteEntry {
4629 op, pa, note, notePt.memo(), wtx.GetDepthInMainChain() });
4636 // Shielded key and address generalizations
4639 bool PaymentAddressBelongsToWallet::operator()(const libzcash::SproutPaymentAddress &zaddr) const
4641 return m_wallet->HaveSproutSpendingKey(zaddr) || m_wallet->HaveSproutViewingKey(zaddr);
4644 bool PaymentAddressBelongsToWallet::operator()(const libzcash::SaplingPaymentAddress &zaddr) const
4646 libzcash::SaplingIncomingViewingKey ivk;
4648 // If we have a SaplingExtendedSpendingKey in the wallet, then we will
4649 // also have the corresponding SaplingFullViewingKey.
4650 return m_wallet->GetSaplingIncomingViewingKey(zaddr, ivk) &&
4651 m_wallet->HaveSaplingFullViewingKey(ivk);
4654 bool PaymentAddressBelongsToWallet::operator()(const libzcash::InvalidEncoding& no) const
4659 bool HaveSpendingKeyForPaymentAddress::operator()(const libzcash::SproutPaymentAddress &zaddr) const
4661 return m_wallet->HaveSproutSpendingKey(zaddr);
4664 bool HaveSpendingKeyForPaymentAddress::operator()(const libzcash::SaplingPaymentAddress &zaddr) const
4666 libzcash::SaplingIncomingViewingKey ivk;
4667 libzcash::SaplingFullViewingKey fvk;
4669 return m_wallet->GetSaplingIncomingViewingKey(zaddr, ivk) &&
4670 m_wallet->GetSaplingFullViewingKey(ivk, fvk) &&
4671 m_wallet->HaveSaplingSpendingKey(fvk);
4674 bool HaveSpendingKeyForPaymentAddress::operator()(const libzcash::InvalidEncoding& no) const
4679 boost::optional<libzcash::SpendingKey> GetSpendingKeyForPaymentAddress::operator()(
4680 const libzcash::SproutPaymentAddress &zaddr) const
4682 libzcash::SproutSpendingKey k;
4683 if (m_wallet->GetSproutSpendingKey(zaddr, k)) {
4684 return libzcash::SpendingKey(k);
4690 boost::optional<libzcash::SpendingKey> GetSpendingKeyForPaymentAddress::operator()(
4691 const libzcash::SaplingPaymentAddress &zaddr) const
4693 libzcash::SaplingExtendedSpendingKey extsk;
4694 if (m_wallet->GetSaplingExtendedSpendingKey(zaddr, extsk)) {
4695 return libzcash::SpendingKey(extsk);
4701 boost::optional<libzcash::SpendingKey> GetSpendingKeyForPaymentAddress::operator()(
4702 const libzcash::InvalidEncoding& no) const
4704 // Defaults to InvalidEncoding
4705 return libzcash::SpendingKey();
4708 SpendingKeyAddResult AddSpendingKeyToWallet::operator()(const libzcash::SproutSpendingKey &sk) const {
4709 auto addr = sk.address();
4711 LogPrint("zrpc", "Importing zaddr %s...\n", EncodePaymentAddress(addr));
4713 if (m_wallet->HaveSproutSpendingKey(addr)) {
4714 return KeyAlreadyExists;
4715 } else if (m_wallet-> AddSproutZKey(sk)) {
4716 m_wallet->mapSproutZKeyMetadata[addr].nCreateTime = nTime;
4723 SpendingKeyAddResult AddSpendingKeyToWallet::operator()(const libzcash::SaplingExtendedSpendingKey &sk) const {
4724 auto fvk = sk.expsk.full_viewing_key();
4725 auto ivk = fvk.in_viewing_key();
4726 auto addr = sk.DefaultAddress();
4729 LogPrint("zrpc", "Importing zaddr %s...\n", EncodePaymentAddress(addr));
4731 // Don't throw error in case a key is already there
4732 if (m_wallet->HaveSaplingSpendingKey(fvk)) {
4733 return KeyAlreadyExists;
4735 if (!m_wallet-> AddSaplingZKey(sk, addr)) {
4739 // Sapling addresses can't have been used in transactions prior to activation.
4740 if (params.vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight == Consensus::NetworkUpgrade::ALWAYS_ACTIVE) {
4741 m_wallet->mapSaplingZKeyMetadata[ivk].nCreateTime = nTime;
4743 // 154051200 seconds from epoch is Friday, 26 October 2018 00:00:00 GMT - definitely before Sapling activates
4744 m_wallet->mapSaplingZKeyMetadata[ivk].nCreateTime = std::max((int64_t) 154051200, nTime);
4747 m_wallet->mapSaplingZKeyMetadata[ivk].hdKeypath = hdKeypath.get();
4751 seedFp.SetHex(seedFpStr.get());
4752 m_wallet->mapSaplingZKeyMetadata[ivk].seedFp = seedFp;
4759 SpendingKeyAddResult AddSpendingKeyToWallet::operator()(const libzcash::InvalidEncoding& no) const {
4760 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid spending key");