]> Git Repo - VerusCoin.git/blame - src/wallet/wallet.cpp
Auto merge of #3422 - bitcartel:3061_track_notes_based_on_3062, r=str4d
[VerusCoin.git] / src / wallet / wallet.cpp
CommitLineData
b2120e22 1// Copyright (c) 2009-2010 Satoshi Nakamoto
f914f1a7 2// Copyright (c) 2009-2014 The Bitcoin Core developers
5b40d886 3// Distributed under the MIT software license, see the accompanying
3a25a2b9 4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
e8ef3da7 5
50c72f23 6#include "wallet/wallet.h"
51ed9ec9 7
3e1cf9b6 8#include "checkpoints.h"
6a86c24d 9#include "coincontrol.h"
be126699 10#include "consensus/upgrades.h"
da29ecbc 11#include "consensus/validation.h"
9bb37bf0 12#include "consensus/consensus.h"
02e67455 13#include "init.h"
3d31e09c 14#include "key_io.h"
8a893c94 15#include "main.h"
0689f46c 16#include "net.h"
e088d65a 17#include "script/script.h"
18#include "script/sign.h"
14f888ca 19#include "timedata.h"
ad49c256 20#include "utilmoneystr.h"
02e67455 21#include "zcash/Note.hpp"
73699cea 22#include "crypter.h"
51ed9ec9 23
d0c4197e
PK
24#include <assert.h>
25
cae686d3 26#include <boost/algorithm/string/replace.hpp>
2bb1c877 27#include <boost/filesystem.hpp>
ad49c256 28#include <boost/thread.hpp>
e8ef3da7
WL
29
30using namespace std;
c1c45943 31using namespace libzcash;
e8ef3da7 32
5b40d886
MF
33/**
34 * Settings
35 */
c6cb21d1 36CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
aa279d61 37CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
77ed59df 38unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
1bbca249 39bool bSpendZeroConfChange = true;
c1c9d5b4 40bool fSendFreeTransactions = false;
ed3e5e46 41bool fPayAtLeastCustomFee = true;
e8ef3da7 42
7e6d23b1
CD
43/**
44 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
5b40d886
MF
45 * Override with -mintxfee
46 */
9b1627d1 47CFeeRate CWallet::minTxFee = CFeeRate(1000);
13fc83c7 48
5b40d886
MF
49/** @defgroup mapWallet
50 *
51 * @{
52 */
e8ef3da7 53
d650f96d
CM
54struct CompareValueOnly
55{
a372168e
MF
56 bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
57 const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
d650f96d
CM
58 {
59 return t1.first < t2.first;
60 }
61};
62
02e67455
JG
63std::string JSOutPoint::ToString() const
64{
65 return strprintf("JSOutPoint(%s, %d, %d)", hash.ToString().substr(0,10), js, n);
66}
67
ad49c256
WL
68std::string COutput::ToString() const
69{
805344dc 70 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
ad49c256
WL
71}
72
93a18a36
GA
73const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
74{
75 LOCK(cs_wallet);
76 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
77 if (it == mapWallet.end())
78 return NULL;
79 return &(it->second);
80}
81
c1c45943 82// Generate a new spending key and return its public payment address
80ed13d5 83libzcash::PaymentAddress CWallet::GenerateNewZKey()
c1c45943
S
84{
85 AssertLockHeld(cs_wallet); // mapZKeyMetadata
e5eab182
JG
86 // TODO: Add Sapling support
87 auto k = SproutSpendingKey::random();
c1c45943
S
88 auto addr = k.address();
89
90 // Check for collision, even though it is unlikely to ever occur
25d5e80c 91 if (CCryptoKeyStore::HaveSproutSpendingKey(addr))
0feffd14 92 throw std::runtime_error("CWallet::GenerateNewZKey(): Collision detected");
c1c45943
S
93
94 // Create new metadata
95 int64_t nCreationTime = GetTime();
96 mapZKeyMetadata[addr] = CKeyMetadata(nCreationTime);
97
c1c45943 98 if (!AddZKey(k))
0feffd14 99 throw std::runtime_error("CWallet::GenerateNewZKey(): AddZKey failed");
80ed13d5 100 return addr;
c1c45943
S
101}
102
efb7662d
JG
103// Generate a new Sapling spending key and return its public payment address
104SaplingPaymentAddress CWallet::GenerateNewSaplingZKey()
105{
8e91ebf7 106 AssertLockHeld(cs_wallet); // mapSaplingZKeyMetadata
f82a864d 107
8e91ebf7 108 auto sk = SaplingSpendingKey::random();
efb7662d 109 auto fvk = sk.full_viewing_key();
8e91ebf7 110 auto addr = sk.default_address();
f82a864d
JG
111
112 // Check for collision, even though it is unlikely to ever occur
8e91ebf7
JG
113 if (CCryptoKeyStore::HaveSaplingSpendingKey(fvk)) {
114 throw std::runtime_error("CWallet::GenerateNewSaplingZKey(): Collision detected");
115 }
f82a864d
JG
116
117 // Create new metadata
118 int64_t nCreationTime = GetTime();
119 mapSaplingZKeyMetadata[addr] = CKeyMetadata(nCreationTime);
120
5175a7f0 121 if (!AddSaplingZKey(sk, addr)) {
f82a864d 122 throw std::runtime_error("CWallet::GenerateNewSaplingZKey(): AddSaplingZKey failed");
efb7662d 123 }
f82a864d
JG
124 // return default sapling payment address.
125 return addr;
efb7662d
JG
126}
127
128// Add spending key to keystore
5175a7f0
JG
129bool CWallet::AddSaplingZKey(
130 const libzcash::SaplingSpendingKey &sk,
131 const boost::optional<libzcash::SaplingPaymentAddress> &defaultAddr)
efb7662d
JG
132{
133 AssertLockHeld(cs_wallet); // mapSaplingZKeyMetadata
efb7662d 134
5175a7f0 135 if (!CCryptoKeyStore::AddSaplingSpendingKey(sk, defaultAddr)) {
efb7662d
JG
136 return false;
137 }
f4207d0c
JG
138
139 if (!fFileBacked) {
140 return true;
141 }
efb7662d 142
f4207d0c 143 // TODO: Persist to disk
f82a864d 144
efb7662d
JG
145 return true;
146}
147
148
c1c45943 149// Add spending key to keystore and persist to disk
e5eab182 150bool CWallet::AddZKey(const libzcash::SproutSpendingKey &key)
c1c45943
S
151{
152 AssertLockHeld(cs_wallet); // mapZKeyMetadata
153 auto addr = key.address();
154
25d5e80c 155 if (!CCryptoKeyStore::AddSproutSpendingKey(key))
c1c45943
S
156 return false;
157
167cd333 158 // check if we need to remove from viewing keys
4c775177
JG
159 if (HaveSproutViewingKey(addr))
160 RemoveSproutViewingKey(key.viewing_key());
167cd333 161
c1c45943
S
162 if (!fFileBacked)
163 return true;
164
165 if (!IsCrypted()) {
166 return CWalletDB(strWalletFile).WriteZKey(addr,
167 key,
168 mapZKeyMetadata[addr]);
169 }
170 return true;
171}
172
fd61d6f5 173CPubKey CWallet::GenerateNewKey()
9976cf07 174{
95691680 175 AssertLockHeld(cs_wallet); // mapKeyMetadata
439e1497 176 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
38067c18 177
dfa23b94
PW
178 CKey secret;
179 secret.MakeNewKey(fCompressed);
38067c18
PW
180
181 // Compressed public keys were introduced in version 0.6.0
182 if (fCompressed)
439e1497 183 SetMinVersion(FEATURE_COMPRPUBKEY);
38067c18 184
dfa23b94 185 CPubKey pubkey = secret.GetPubKey();
d0c41a73 186 assert(secret.VerifyPubKey(pubkey));
4addb2c0
PW
187
188 // Create new metadata
51ed9ec9 189 int64_t nCreationTime = GetTime();
4addb2c0
PW
190 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
191 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
192 nTimeFirstKey = nCreationTime;
193
dfa23b94 194 if (!AddKeyPubKey(secret, pubkey))
5262fde0 195 throw std::runtime_error("CWallet::GenerateNewKey(): AddKey failed");
dfa23b94 196 return pubkey;
9976cf07 197}
e8ef3da7 198
4addb2c0 199bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
e8ef3da7 200{
95691680 201 AssertLockHeld(cs_wallet); // mapKeyMetadata
dfa23b94 202 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
acd65016 203 return false;
ccca27a7
CL
204
205 // check if we need to remove from watch-only
206 CScript script;
207 script = GetScriptForDestination(pubkey.GetID());
208 if (HaveWatchOnly(script))
209 RemoveWatchOnly(script);
210
e8ef3da7
WL
211 if (!fFileBacked)
212 return true;
dfa23b94 213 if (!IsCrypted()) {
3869fb89
JG
214 return CWalletDB(strWalletFile).WriteKey(pubkey,
215 secret.GetPrivKey(),
4addb2c0 216 mapKeyMetadata[pubkey.GetID()]);
dfa23b94 217 }
84c3c2eb 218 return true;
4e87d341
MC
219}
220
3869fb89 221bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
4addb2c0 222 const vector<unsigned char> &vchCryptedSecret)
4e87d341 223{
efb7662d 224
4e87d341
MC
225 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
226 return false;
227 if (!fFileBacked)
228 return true;
96f34cd5 229 {
f8dcd5ca 230 LOCK(cs_wallet);
96f34cd5 231 if (pwalletdbEncryption)
3869fb89
JG
232 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
233 vchCryptedSecret,
4addb2c0 234 mapKeyMetadata[vchPubKey.GetID()]);
96f34cd5 235 else
3869fb89
JG
236 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
237 vchCryptedSecret,
4addb2c0 238 mapKeyMetadata[vchPubKey.GetID()]);
96f34cd5 239 }
0767e691 240 return false;
4e87d341
MC
241}
242
73699cea 243
25d5e80c
JG
244bool CWallet::AddCryptedSproutSpendingKey(
245 const libzcash::SproutPaymentAddress &address,
246 const libzcash::ReceivingKey &rk,
247 const std::vector<unsigned char> &vchCryptedSecret)
73699cea 248{
25d5e80c 249 if (!CCryptoKeyStore::AddCryptedSproutSpendingKey(address, rk, vchCryptedSecret))
73699cea
S
250 return false;
251 if (!fFileBacked)
252 return true;
253 {
254 LOCK(cs_wallet);
82bd9ee8 255 if (pwalletdbEncryption) {
73699cea 256 return pwalletdbEncryption->WriteCryptedZKey(address,
642a1caf 257 rk,
73699cea
S
258 vchCryptedSecret,
259 mapZKeyMetadata[address]);
82bd9ee8 260 } else {
73699cea 261 return CWalletDB(strWalletFile).WriteCryptedZKey(address,
642a1caf 262 rk,
73699cea
S
263 vchCryptedSecret,
264 mapZKeyMetadata[address]);
82bd9ee8 265 }
73699cea
S
266 }
267 return false;
268}
269
bc6344b3 270bool CWallet::AddCryptedSaplingSpendingKey(const libzcash::SaplingFullViewingKey &fvk,
5175a7f0
JG
271 const std::vector<unsigned char> &vchCryptedSecret,
272 const boost::optional<libzcash::SaplingPaymentAddress> &defaultAddr)
bc6344b3 273{
5175a7f0 274 if (!CCryptoKeyStore::AddCryptedSaplingSpendingKey(fvk, vchCryptedSecret, defaultAddr))
bc6344b3
JG
275 return false;
276 if (!fFileBacked)
277 return true;
278 {
279 // TODO: Sapling - Write to disk
280 }
281 return false;
282}
283
4addb2c0
PW
284bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
285{
95691680 286 AssertLockHeld(cs_wallet); // mapKeyMetadata
4addb2c0
PW
287 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
288 nTimeFirstKey = meta.nCreateTime;
289
290 mapKeyMetadata[pubkey.GetID()] = meta;
291 return true;
292}
293
e5eab182 294bool CWallet::LoadZKeyMetadata(const SproutPaymentAddress &addr, const CKeyMetadata &meta)
c1c45943
S
295{
296 AssertLockHeld(cs_wallet); // mapZKeyMetadata
297 mapZKeyMetadata[addr] = meta;
298 return true;
299}
300
2f15e86a
GA
301bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
302{
303 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
304}
305
e5eab182 306bool CWallet::LoadCryptedZKey(const libzcash::SproutPaymentAddress &addr, const libzcash::ReceivingKey &rk, const std::vector<unsigned char> &vchCryptedSecret)
73699cea 307{
25d5e80c 308 return CCryptoKeyStore::AddCryptedSproutSpendingKey(addr, rk, vchCryptedSecret);
73699cea
S
309}
310
e5eab182 311bool CWallet::LoadZKey(const libzcash::SproutSpendingKey &key)
c1c45943 312{
25d5e80c 313 return CCryptoKeyStore::AddSproutSpendingKey(key);
c1c45943
S
314}
315
4c775177 316bool CWallet::AddSproutViewingKey(const libzcash::SproutViewingKey &vk)
167cd333 317{
4c775177 318 if (!CCryptoKeyStore::AddSproutViewingKey(vk)) {
167cd333 319 return false;
bec22351 320 }
167cd333 321 nTimeFirstKey = 1; // No birthday information for viewing keys.
bec22351 322 if (!fFileBacked) {
167cd333 323 return true;
bec22351 324 }
4c775177 325 return CWalletDB(strWalletFile).WriteSproutViewingKey(vk);
167cd333
JG
326}
327
4c775177 328bool CWallet::RemoveSproutViewingKey(const libzcash::SproutViewingKey &vk)
167cd333
JG
329{
330 AssertLockHeld(cs_wallet);
4c775177 331 if (!CCryptoKeyStore::RemoveSproutViewingKey(vk)) {
167cd333 332 return false;
bec22351
JG
333 }
334 if (fFileBacked) {
4c775177 335 if (!CWalletDB(strWalletFile).EraseSproutViewingKey(vk)) {
167cd333 336 return false;
bec22351
JG
337 }
338 }
167cd333
JG
339
340 return true;
341}
342
4c775177 343bool CWallet::LoadSproutViewingKey(const libzcash::SproutViewingKey &vk)
167cd333 344{
4c775177 345 return CCryptoKeyStore::AddSproutViewingKey(vk);
167cd333
JG
346}
347
922e8e29 348bool CWallet::AddCScript(const CScript& redeemScript)
e679ec96 349{
922e8e29 350 if (!CCryptoKeyStore::AddCScript(redeemScript))
e679ec96
GA
351 return false;
352 if (!fFileBacked)
353 return true;
922e8e29 354 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
e679ec96
GA
355}
356
18116b06
WL
357bool CWallet::LoadCScript(const CScript& redeemScript)
358{
359 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
360 * that never can be redeemed. However, old wallets may still contain
361 * these. Do not add them to the wallet and warn. */
362 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
363 {
07444da1 364 std::string strAddr = EncodeDestination(CScriptID(redeemScript));
18116b06
WL
365 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",
366 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
367 return true;
368 }
369
370 return CCryptoKeyStore::AddCScript(redeemScript);
371}
372
d5087d1b 373bool CWallet::AddWatchOnly(const CScript &dest)
c8988460
PW
374{
375 if (!CCryptoKeyStore::AddWatchOnly(dest))
376 return false;
377 nTimeFirstKey = 1; // No birthday information for watch-only keys.
939ed973 378 NotifyWatchonlyChanged(true);
c8988460
PW
379 if (!fFileBacked)
380 return true;
381 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
382}
383
ccca27a7
CL
384bool CWallet::RemoveWatchOnly(const CScript &dest)
385{
386 AssertLockHeld(cs_wallet);
387 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
388 return false;
389 if (!HaveWatchOnly())
390 NotifyWatchonlyChanged(false);
391 if (fFileBacked)
392 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
393 return false;
394
395 return true;
396}
397
d5087d1b 398bool CWallet::LoadWatchOnly(const CScript &dest)
c8988460 399{
c8988460
PW
400 return CCryptoKeyStore::AddWatchOnly(dest);
401}
402
94f778bd 403bool CWallet::Unlock(const SecureString& strWalletPassphrase)
4e87d341 404{
6cc4a62c
GA
405 CCrypter crypter;
406 CKeyingMaterial vMasterKey;
4e87d341 407
f8dcd5ca
PW
408 {
409 LOCK(cs_wallet);
4e87d341
MC
410 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
411 {
412 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
413 return false;
414 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
92f2c1fe 415 continue; // try another master key
4e87d341
MC
416 if (CCryptoKeyStore::Unlock(vMasterKey))
417 return true;
418 }
f8dcd5ca 419 }
4e87d341
MC
420 return false;
421}
422
94f778bd 423bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
4e87d341 424{
6cc4a62c 425 bool fWasLocked = IsLocked();
4e87d341 426
6cc4a62c 427 {
f8dcd5ca 428 LOCK(cs_wallet);
4e87d341
MC
429 Lock();
430
431 CCrypter crypter;
432 CKeyingMaterial vMasterKey;
433 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
434 {
435 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
436 return false;
6cc4a62c 437 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
4e87d341
MC
438 return false;
439 if (CCryptoKeyStore::Unlock(vMasterKey))
440 {
51ed9ec9 441 int64_t nStartTime = GetTimeMillis();
ddebdd9a
MC
442 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
443 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
444
445 nStartTime = GetTimeMillis();
446 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
447 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
448
449 if (pMasterKey.second.nDeriveIterations < 25000)
450 pMasterKey.second.nDeriveIterations = 25000;
451
881a85a2 452 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
ddebdd9a 453
4e87d341
MC
454 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
455 return false;
456 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
457 return false;
458 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
459 if (fWasLocked)
460 Lock();
461 return true;
462 }
463 }
464 }
6cc4a62c 465
4e87d341
MC
466 return false;
467}
468
f86ee1c2
EOW
469void CWallet::ChainTip(const CBlockIndex *pindex,
470 const CBlock *pblock,
4fc309f0
EOW
471 SproutMerkleTree sproutTree,
472 SaplingMerkleTree saplingTree,
f86ee1c2 473 bool added)
769e031c
JG
474{
475 if (added) {
f86ee1c2 476 IncrementNoteWitnesses(pindex, pblock, sproutTree, saplingTree);
769e031c 477 } else {
40ef121e 478 DecrementNoteWitnesses(pindex);
769e031c 479 }
c343e2db 480 UpdateSaplingNullifierNoteMapForBlock(pblock);
769e031c
JG
481}
482
ed6d0b5f
PW
483void CWallet::SetBestChain(const CBlockLocator& loc)
484{
485 CWalletDB walletdb(strWalletFile);
03f83b9b 486 SetBestChainINTERNAL(walletdb, loc);
ed6d0b5f 487}
7414733b 488
0646f749
EOW
489std::set<std::pair<libzcash::PaymentAddress, uint256>> CWallet::GetNullifiersForAddresses(const std::set<libzcash::PaymentAddress> & addresses)
490{
491 std::set<std::pair<libzcash::PaymentAddress, uint256>> nullifierSet;
492 for (const auto & txPair : mapWallet) {
2f0b2a25 493 for (const auto & noteDataPair : txPair.second.mapSproutNoteData) {
0646f749
EOW
494 if (noteDataPair.second.nullifier && addresses.count(noteDataPair.second.address)) {
495 nullifierSet.insert(std::make_pair(noteDataPair.second.address, noteDataPair.second.nullifier.get()));
496 }
497 }
498 }
499 return nullifierSet;
500}
501
502bool CWallet::IsNoteChange(const std::set<std::pair<libzcash::PaymentAddress, uint256>> & nullifierSet, const PaymentAddress & address, const JSOutPoint & jsop)
503{
504 // A Note is marked as "change" if the address that received it
505 // also spent Notes in the same transaction. This will catch,
506 // for instance:
507 // - Change created by spending fractions of Notes (because
508 // z_sendmany sends change to the originating z-address).
509 // - "Chaining Notes" used to connect JoinSplits together.
510 // - Notes created by consolidation transactions (e.g. using
511 // z_mergetoaddress).
512 // - Notes sent from one address to itself.
513 for (const JSDescription & jsd : mapWallet[jsop.hash].vjoinsplit) {
514 for (const uint256 & nullifier : jsd.nullifiers) {
515 if (nullifierSet.count(std::make_pair(address, nullifier))) {
516 return true;
517 }
518 }
519 }
520 return false;
521}
522
439e1497 523bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
0b807a41 524{
ca4cf5cf 525 LOCK(cs_wallet); // nWalletVersion
0b807a41
PW
526 if (nWalletVersion >= nVersion)
527 return true;
528
439e1497
PW
529 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
530 if (fExplicit && nVersion > nWalletMaxVersion)
531 nVersion = FEATURE_LATEST;
532
0b807a41
PW
533 nWalletVersion = nVersion;
534
439e1497
PW
535 if (nVersion > nWalletMaxVersion)
536 nWalletMaxVersion = nVersion;
537
0b807a41
PW
538 if (fFileBacked)
539 {
540 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
0b807a41
PW
541 if (nWalletVersion > 40000)
542 pwalletdb->WriteMinVersion(nWalletVersion);
543 if (!pwalletdbIn)
544 delete pwalletdb;
545 }
546
547 return true;
548}
549
439e1497
PW
550bool CWallet::SetMaxVersion(int nVersion)
551{
ca4cf5cf 552 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
439e1497
PW
553 // cannot downgrade below current version
554 if (nWalletVersion > nVersion)
555 return false;
556
557 nWalletMaxVersion = nVersion;
558
559 return true;
560}
561
3015e0bc 562set<uint256> CWallet::GetConflicts(const uint256& txid) const
731b89b8
GA
563{
564 set<uint256> result;
565 AssertLockHeld(cs_wallet);
566
567 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
568 if (it == mapWallet.end())
569 return result;
570 const CWalletTx& wtx = it->second;
571
93a18a36 572 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
731b89b8
GA
573
574 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
575 {
93a18a36
GA
576 if (mapTxSpends.count(txin.prevout) <= 1)
577 continue; // No conflict if zero or one spends
578 range = mapTxSpends.equal_range(txin.prevout);
579 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
3015e0bc 580 result.insert(it->second);
731b89b8 581 }
0f106047
JG
582
583 std::pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range_n;
584
585 for (const JSDescription& jsdesc : wtx.vjoinsplit) {
586 for (const uint256& nullifier : jsdesc.nullifiers) {
3438e26c 587 if (mapTxSproutNullifiers.count(nullifier) <= 1) {
0f106047
JG
588 continue; // No conflict if zero or one spends
589 }
3438e26c 590 range_n = mapTxSproutNullifiers.equal_range(nullifier);
0f106047
JG
591 for (TxNullifiers::const_iterator it = range_n.first; it != range_n.second; ++it) {
592 result.insert(it->second);
593 }
594 }
3afc6ce2
S
595 }
596
597 std::pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range_o;
598
599 for (const SpendDescription &spend : wtx.vShieldedSpend) {
600 uint256 nullifier = spend.nullifier;
601 if (mapTxSaplingNullifiers.count(nullifier) <= 1) {
602 continue; // No conflict if zero or one spends
603 }
604 range_o = mapTxSaplingNullifiers.equal_range(nullifier);
605 for (TxNullifiers::const_iterator it = range_o.first; it != range_o.second; ++it) {
606 result.insert(it->second);
607 }
0f106047 608 }
731b89b8
GA
609 return result;
610}
611
2bb1c877
JS
612void CWallet::Flush(bool shutdown)
613{
614 bitdb.Flush(shutdown);
615}
616
341e2385 617bool CWallet::Verify(const string& walletFile, string& warningString, string& errorString)
2bb1c877
JS
618{
619 if (!bitdb.Open(GetDataDir()))
620 {
621 // try moving the database env out of the way
622 boost::filesystem::path pathDatabase = GetDataDir() / "database";
623 boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
624 try {
625 boost::filesystem::rename(pathDatabase, pathDatabaseBak);
626 LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
627 } catch (const boost::filesystem::filesystem_error&) {
628 // failure is ok (well, not really, but it's not worse than what we started with)
629 }
efb7662d 630
2bb1c877
JS
631 // try again
632 if (!bitdb.Open(GetDataDir())) {
633 // if it still fails, it probably means we can't even create the database env
634 string msg = strprintf(_("Error initializing wallet database environment %s!"), GetDataDir());
635 errorString += msg;
636 return true;
637 }
638 }
efb7662d 639
2bb1c877
JS
640 if (GetBoolArg("-salvagewallet", false))
641 {
642 // Recover readable keypairs:
643 if (!CWalletDB::Recover(bitdb, walletFile, true))
644 return false;
645 }
efb7662d 646
2bb1c877
JS
647 if (boost::filesystem::exists(GetDataDir() / walletFile))
648 {
649 CDBEnv::VerifyResult r = bitdb.Verify(walletFile, CWalletDB::Recover);
650 if (r == CDBEnv::RECOVER_OK)
651 {
652 warningString += strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
653 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
654 " your balance or transactions are incorrect you should"
655 " restore from a backup."), GetDataDir());
656 }
657 if (r == CDBEnv::RECOVER_FAIL)
658 errorString += _("wallet.dat corrupt, salvage failed");
659 }
efb7662d 660
2bb1c877
JS
661 return true;
662}
663
0f106047
JG
664template <class T>
665void CWallet::SyncMetaData(pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator> range)
731b89b8
GA
666{
667 // We want all the wallet transactions in range to have the same metadata as
668 // the oldest (smallest nOrderPos).
669 // So: find smallest nOrderPos:
670
671 int nMinOrderPos = std::numeric_limits<int>::max();
672 const CWalletTx* copyFrom = NULL;
0f106047 673 for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
731b89b8
GA
674 {
675 const uint256& hash = it->second;
676 int n = mapWallet[hash].nOrderPos;
677 if (n < nMinOrderPos)
678 {
679 nMinOrderPos = n;
680 copyFrom = &mapWallet[hash];
681 }
682 }
683 // Now copy data from copyFrom to rest:
0f106047 684 for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
731b89b8
GA
685 {
686 const uint256& hash = it->second;
687 CWalletTx* copyTo = &mapWallet[hash];
688 if (copyFrom == copyTo) continue;
689 copyTo->mapValue = copyFrom->mapValue;
303f80fb 690 // mapSproutNoteData and mapSaplingNoteData not copied on purpose
c3a7307a 691 // (it is always set correctly for each CWalletTx)
731b89b8
GA
692 copyTo->vOrderForm = copyFrom->vOrderForm;
693 // fTimeReceivedIsTxTime not copied on purpose
694 // nTimeReceived not copied on purpose
695 copyTo->nTimeSmart = copyFrom->nTimeSmart;
696 copyTo->fFromMe = copyFrom->fFromMe;
697 copyTo->strFromAccount = copyFrom->strFromAccount;
731b89b8
GA
698 // nOrderPos not copied on purpose
699 // cached members not copied on purpose
700 }
701}
702
5b40d886
MF
703/**
704 * Outpoint is spent if any non-conflicted transaction
705 * spends it:
706 */
93a18a36 707bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
731b89b8 708{
93a18a36
GA
709 const COutPoint outpoint(hash, n);
710 pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
711 range = mapTxSpends.equal_range(outpoint);
731b89b8 712
93a18a36 713 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
731b89b8 714 {
93a18a36
GA
715 const uint256& wtxid = it->second;
716 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
717 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
718 return true; // Spent
731b89b8 719 }
93a18a36
GA
720 return false;
721}
722
0f106047
JG
723/**
724 * Note is spent if any non-conflicted transaction
725 * spends it:
726 */
3b6dd486 727bool CWallet::IsSproutSpent(const uint256& nullifier) const {
0f106047 728 pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range;
3438e26c 729 range = mapTxSproutNullifiers.equal_range(nullifier);
0f106047
JG
730
731 for (TxNullifiers::const_iterator it = range.first; it != range.second; ++it) {
732 const uint256& wtxid = it->second;
edfc6a78
S
733 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
734 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) {
735 return true; // Spent
736 }
737 }
3b6dd486
S
738 return false;
739}
edfc6a78 740
3b6dd486
S
741bool CWallet::IsSaplingSpent(const uint256& nullifier) const {
742 pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range;
edfc6a78
S
743 range = mapTxSaplingNullifiers.equal_range(nullifier);
744
745 for (TxNullifiers::const_iterator it = range.first; it != range.second; ++it) {
746 const uint256& wtxid = it->second;
0f106047
JG
747 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
748 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) {
749 return true; // Spent
750 }
751 }
752 return false;
753}
754
d5e490d9 755void CWallet::AddToTransparentSpends(const COutPoint& outpoint, const uint256& wtxid)
93a18a36
GA
756{
757 mapTxSpends.insert(make_pair(outpoint, wtxid));
758
759 pair<TxSpends::iterator, TxSpends::iterator> range;
760 range = mapTxSpends.equal_range(outpoint);
0f106047 761 SyncMetaData<COutPoint>(range);
93a18a36
GA
762}
763
d5e490d9 764void CWallet::AddToSproutSpends(const uint256& nullifier, const uint256& wtxid)
0f106047 765{
3438e26c 766 mapTxSproutNullifiers.insert(make_pair(nullifier, wtxid));
0f106047
JG
767
768 pair<TxNullifiers::iterator, TxNullifiers::iterator> range;
3438e26c 769 range = mapTxSproutNullifiers.equal_range(nullifier);
0f106047
JG
770 SyncMetaData<uint256>(range);
771}
93a18a36 772
c343e2db
S
773void CWallet::AddToSaplingSpends(const uint256& nullifier, const uint256& wtxid)
774{
775 mapTxSaplingNullifiers.insert(make_pair(nullifier, wtxid));
776
777 pair<TxNullifiers::iterator, TxNullifiers::iterator> range;
778 range = mapTxSaplingNullifiers.equal_range(nullifier);
779 SyncMetaData<uint256>(range);
780}
781
93a18a36
GA
782void CWallet::AddToSpends(const uint256& wtxid)
783{
784 assert(mapWallet.count(wtxid));
785 CWalletTx& thisTx = mapWallet[wtxid];
786 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
787 return;
788
0f106047 789 for (const CTxIn& txin : thisTx.vin) {
d5e490d9 790 AddToTransparentSpends(txin.prevout, wtxid);
0f106047
JG
791 }
792 for (const JSDescription& jsdesc : thisTx.vjoinsplit) {
793 for (const uint256& nullifier : jsdesc.nullifiers) {
d5e490d9 794 AddToSproutSpends(nullifier, wtxid);
0f106047
JG
795 }
796 }
52332fb4
S
797 for (const SpendDescription &spend : thisTx.vShieldedSpend) {
798 AddToSaplingSpends(spend.nullifier, wtxid);
799 }
800}
801
76b22658
JG
802void CWallet::ClearNoteWitnessCache()
803{
804 LOCK(cs_wallet);
805 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
005f3ad1 806 for (mapSproutNoteData_t::value_type& item : wtxItem.second.mapSproutNoteData) {
40600f50 807 item.second.witnesses.clear();
a4ef3aa9 808 item.second.witnessHeight = -1;
76b22658 809 }
403b9b4e
EOW
810 for (mapSaplingNoteData_t::value_type& item : wtxItem.second.mapSaplingNoteData) {
811 item.second.witnesses.clear();
812 item.second.witnessHeight = -1;
813 }
76b22658 814 }
a4ef3aa9 815 nWitnessCacheSize = 0;
76b22658
JG
816}
817
b5380248
EOW
818template<typename NoteDataMap>
819void CopyPreviousWitnesses(NoteDataMap& noteDataMap, int indexHeight, int64_t nWitnessCacheSize)
820{
821 for (auto& item : noteDataMap) {
822 auto* nd = &(item.second);
823 // Only increment witnesses that are behind the current height
824 if (nd->witnessHeight < indexHeight) {
825 // Check the validity of the cache
826 // The only time a note witnessed above the current height
827 // would be invalid here is during a reindex when blocks
828 // have been decremented, and we are incrementing the blocks
829 // immediately after.
830 assert(nWitnessCacheSize >= nd->witnesses.size());
831 // Witnesses being incremented should always be either -1
832 // (never incremented or decremented) or one below indexHeight
833 assert((nd->witnessHeight == -1) || (nd->witnessHeight == indexHeight - 1));
834 // Copy the witness for the previous block if we have one
835 if (nd->witnesses.size() > 0) {
836 nd->witnesses.push_front(nd->witnesses.front());
837 }
838 if (nd->witnesses.size() > WITNESS_CACHE_SIZE) {
839 nd->witnesses.pop_back();
840 }
841 }
842 }
843}
844
f6d0d5ec
EOW
845template<typename NoteDataMap>
846void AppendNoteCommitment(NoteDataMap& noteDataMap, int indexHeight, int64_t nWitnessCacheSize, const uint256& note_commitment)
847{
848 for (auto& item : noteDataMap) {
849 auto* nd = &(item.second);
850 if (nd->witnessHeight < indexHeight && nd->witnesses.size() > 0) {
851 // Check the validity of the cache
852 // See comment in CopyPreviousWitnesses about validity.
853 assert(nWitnessCacheSize >= nd->witnesses.size());
854 nd->witnesses.front().append(note_commitment);
855 }
856 }
857}
858
859template<typename OutPoint, typename NoteData, typename Witness>
860void WitnessNoteIfMine(std::map<OutPoint, NoteData>& noteDataMap, int indexHeight, int64_t nWitnessCacheSize, const OutPoint& key, const Witness& witness)
861{
862 if (noteDataMap.count(key) && noteDataMap[key].witnessHeight < indexHeight) {
863 auto* nd = &(noteDataMap[key]);
864 if (nd->witnesses.size() > 0) {
865 // We think this can happen because we write out the
866 // witness cache state after every block increment or
867 // decrement, but the block index itself is written in
868 // batches. So if the node crashes in between these two
869 // operations, it is possible for IncrementNoteWitnesses
870 // to be called again on previously-cached blocks. This
871 // doesn't affect existing cached notes because of the
872 // NoteData::witnessHeight checks. See #1378 for details.
873 LogPrintf("Inconsistent witness cache state found for %s\n- Cache size: %d\n- Top (height %d): %s\n- New (height %d): %s\n",
874 key.ToString(), nd->witnesses.size(),
875 nd->witnessHeight,
876 nd->witnesses.front().root().GetHex(),
877 indexHeight,
878 witness.root().GetHex());
879 nd->witnesses.clear();
880 }
881 nd->witnesses.push_front(witness);
882 // Set height to one less than pindex so it gets incremented
883 nd->witnessHeight = indexHeight - 1;
884 // Check the validity of the cache
885 assert(nWitnessCacheSize >= nd->witnesses.size());
886 }
887}
888
4a0bc604
EOW
889
890template<typename NoteDataMap>
891void UpdateWitnessHeights(NoteDataMap& noteDataMap, int indexHeight, int64_t nWitnessCacheSize)
892{
893 for (auto& item : noteDataMap) {
894 auto* nd = &(item.second);
895 if (nd->witnessHeight < indexHeight) {
896 nd->witnessHeight = indexHeight;
897 // Check the validity of the cache
898 // See comment in CopyPreviousWitnesses about validity.
899 assert(nWitnessCacheSize >= nd->witnesses.size());
900 }
901 }
902}
903
be74c80d
JG
904void CWallet::IncrementNoteWitnesses(const CBlockIndex* pindex,
905 const CBlock* pblockIn,
4fc309f0
EOW
906 SproutMerkleTree& sproutTree,
907 SaplingMerkleTree& saplingTree)
be74c80d 908{
49695a97
EOW
909 LOCK(cs_wallet);
910 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
b5380248 911 ::CopyPreviousWitnesses(wtxItem.second.mapSproutNoteData, pindex->nHeight, nWitnessCacheSize);
45de2eda 912 ::CopyPreviousWitnesses(wtxItem.second.mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize);
49695a97 913 }
b5380248 914
49695a97
EOW
915 if (nWitnessCacheSize < WITNESS_CACHE_SIZE) {
916 nWitnessCacheSize += 1;
917 }
be74c80d 918
49695a97
EOW
919 const CBlock* pblock {pblockIn};
920 CBlock block;
921 if (!pblock) {
922 ReadBlockFromDisk(block, pindex);
923 pblock = &block;
924 }
be74c80d 925
49695a97
EOW
926 for (const CTransaction& tx : pblock->vtx) {
927 auto hash = tx.GetHash();
928 bool txIsOurs = mapWallet.count(hash);
45de2eda 929 // Sprout
49695a97
EOW
930 for (size_t i = 0; i < tx.vjoinsplit.size(); i++) {
931 const JSDescription& jsdesc = tx.vjoinsplit[i];
932 for (uint8_t j = 0; j < jsdesc.commitments.size(); j++) {
933 const uint256& note_commitment = jsdesc.commitments[j];
f86ee1c2 934 sproutTree.append(note_commitment);
be74c80d 935
49695a97
EOW
936 // Increment existing witnesses
937 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
f6d0d5ec 938 ::AppendNoteCommitment(wtxItem.second.mapSproutNoteData, pindex->nHeight, nWitnessCacheSize, note_commitment);
be74c80d 939 }
b6961fc1 940
49695a97
EOW
941 // If this is our note, witness it
942 if (txIsOurs) {
943 JSOutPoint jsoutpt {hash, i, j};
f86ee1c2 944 ::WitnessNoteIfMine(mapWallet[hash].mapSproutNoteData, pindex->nHeight, nWitnessCacheSize, jsoutpt, sproutTree.witness());
b6961fc1 945 }
83d7b5b6
JG
946 }
947 }
45de2eda
EOW
948 // Sapling
949 for (uint32_t i = 0; i < tx.vShieldedOutput.size(); i++) {
950 const uint256& note_commitment = tx.vShieldedOutput[i].cm;
951 saplingTree.append(note_commitment);
952
953 // Increment existing witnesses
954 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
955 ::AppendNoteCommitment(wtxItem.second.mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize, note_commitment);
956 }
957
958 // If this is our note, witness it
959 if (txIsOurs) {
960 SaplingOutPoint outPoint {hash, i};
961 ::WitnessNoteIfMine(mapWallet[hash].mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize, outPoint, saplingTree.witness());
962 }
963 }
49695a97 964 }
b6961fc1 965
49695a97
EOW
966 // Update witness heights
967 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
4a0bc604 968 ::UpdateWitnessHeights(wtxItem.second.mapSproutNoteData, pindex->nHeight, nWitnessCacheSize);
45de2eda 969 ::UpdateWitnessHeights(wtxItem.second.mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize);
be74c80d 970 }
49695a97
EOW
971
972 // For performance reasons, we write out the witness cache in
973 // CWallet::SetBestChain() (which also ensures that overall consistency
974 // of the wallet.dat is maintained).
be74c80d
JG
975}
976
9d804cc6
EOW
977template<typename NoteDataMap>
978void DecrementNoteWitnesses(NoteDataMap& noteDataMap, int indexHeight, int64_t nWitnessCacheSize)
be74c80d 979{
9d804cc6
EOW
980 for (auto& item : noteDataMap) {
981 auto* nd = &(item.second);
982 // Only decrement witnesses that are not above the current height
983 if (nd->witnessHeight <= indexHeight) {
49695a97 984 // Check the validity of the cache
9d804cc6
EOW
985 // See comment below (this would be invalid if there were a
986 // prior decrement).
987 assert(nWitnessCacheSize >= nd->witnesses.size());
988 // Witnesses being decremented should always be either -1
989 // (never incremented or decremented) or equal to the height
990 // of the block being removed (indexHeight)
991 assert((nd->witnessHeight == -1) || (nd->witnessHeight == indexHeight));
992 if (nd->witnesses.size() > 0) {
993 nd->witnesses.pop_front();
83d7b5b6 994 }
9d804cc6
EOW
995 // indexHeight is the height of the block being removed, so
996 // the new witness cache height is one below it.
997 nd->witnessHeight = indexHeight - 1;
998 }
999 // Check the validity of the cache
1000 // Technically if there are notes witnessed above the current
1001 // height, their cache will now be invalid (relative to the new
1002 // value of nWitnessCacheSize). However, this would only occur
1003 // during a reindex, and by the time the reindex reaches the tip
1004 // of the chain again, the existing witness caches will be valid
1005 // again.
1006 // We don't set nWitnessCacheSize to zero at the start of the
1007 // reindex because the on-disk blocks had already resulted in a
1008 // chain that didn't trigger the assertion below.
1009 if (nd->witnessHeight < indexHeight) {
1010 // Subtract 1 to compare to what nWitnessCacheSize will be after
1011 // decrementing.
1012 assert((nWitnessCacheSize - 1) >= nd->witnesses.size());
83d7b5b6 1013 }
be74c80d 1014 }
9d804cc6
EOW
1015}
1016
1017void CWallet::DecrementNoteWitnesses(const CBlockIndex* pindex)
1018{
1019 LOCK(cs_wallet);
1020 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
1021 ::DecrementNoteWitnesses(wtxItem.second.mapSproutNoteData, pindex->nHeight, nWitnessCacheSize);
1022 ::DecrementNoteWitnesses(wtxItem.second.mapSaplingNoteData, pindex->nHeight, nWitnessCacheSize);
1023 }
3c868d2b 1024 nWitnessCacheSize -= 1;
49695a97
EOW
1025 // TODO: If nWitnessCache is zero, we need to regenerate the caches (#1302)
1026 assert(nWitnessCacheSize > 0);
1027
1028 // For performance reasons, we write out the witness cache in
1029 // CWallet::SetBestChain() (which also ensures that overall consistency
1030 // of the wallet.dat is maintained).
be74c80d
JG
1031}
1032
94f778bd 1033bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
4e87d341 1034{
6cc4a62c
GA
1035 if (IsCrypted())
1036 return false;
4e87d341 1037
6cc4a62c 1038 CKeyingMaterial vMasterKey;
4e87d341 1039
6cc4a62c 1040 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
65e3a1e7 1041 GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
4e87d341 1042
6cc4a62c 1043 CMasterKey kMasterKey;
001a53d7 1044
6cc4a62c 1045 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
65e3a1e7 1046 GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
4e87d341 1047
6cc4a62c 1048 CCrypter crypter;
51ed9ec9 1049 int64_t nStartTime = GetTimeMillis();
6cc4a62c
GA
1050 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
1051 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
ddebdd9a 1052
6cc4a62c
GA
1053 nStartTime = GetTimeMillis();
1054 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
1055 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
ddebdd9a 1056
6cc4a62c
GA
1057 if (kMasterKey.nDeriveIterations < 25000)
1058 kMasterKey.nDeriveIterations = 25000;
ddebdd9a 1059
881a85a2 1060 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
ddebdd9a 1061
6cc4a62c
GA
1062 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
1063 return false;
1064 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
1065 return false;
4e87d341 1066
6cc4a62c 1067 {
f8dcd5ca 1068 LOCK(cs_wallet);
4e87d341
MC
1069 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
1070 if (fFileBacked)
1071 {
870da77d 1072 assert(!pwalletdbEncryption);
96f34cd5 1073 pwalletdbEncryption = new CWalletDB(strWalletFile);
870da77d
PK
1074 if (!pwalletdbEncryption->TxnBegin()) {
1075 delete pwalletdbEncryption;
1076 pwalletdbEncryption = NULL;
0fb78eae 1077 return false;
870da77d 1078 }
96f34cd5 1079 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
4e87d341
MC
1080 }
1081
1082 if (!EncryptKeys(vMasterKey))
96f34cd5 1083 {
870da77d 1084 if (fFileBacked) {
96f34cd5 1085 pwalletdbEncryption->TxnAbort();
870da77d
PK
1086 delete pwalletdbEncryption;
1087 }
1088 // We now probably have half of our keys encrypted in memory, and half not...
7e6d23b1 1089 // die and let the user reload the unencrypted wallet.
d0c4197e 1090 assert(false);
96f34cd5
MC
1091 }
1092
0b807a41 1093 // Encryption was introduced in version 0.4.0
439e1497 1094 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
0b807a41 1095
96f34cd5
MC
1096 if (fFileBacked)
1097 {
870da77d
PK
1098 if (!pwalletdbEncryption->TxnCommit()) {
1099 delete pwalletdbEncryption;
5b40d886 1100 // We now have keys encrypted in memory, but not on disk...
7e6d23b1 1101 // die to avoid confusion and let the user reload the unencrypted wallet.
d0c4197e 1102 assert(false);
870da77d 1103 }
96f34cd5 1104
fcfd7ff8 1105 delete pwalletdbEncryption;
96f34cd5
MC
1106 pwalletdbEncryption = NULL;
1107 }
4e87d341 1108
37971fcc
GA
1109 Lock();
1110 Unlock(strWalletPassphrase);
1111 NewKeyPool();
4e87d341 1112 Lock();
6cc4a62c 1113
d764d916
GA
1114 // Need to completely rewrite the wallet file; if we don't, bdb might keep
1115 // bits of the unencrypted private key in slack space in the database file.
b2d3b2d6 1116 CDB::Rewrite(strWalletFile);
fe4a6550 1117
d764d916 1118 }
ab1b288f 1119 NotifyStatusChanged(this);
9e9869d0 1120
4e87d341 1121 return true;
e8ef3da7
WL
1122}
1123
51ed9ec9 1124int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
da7b8c12 1125{
95691680 1126 AssertLockHeld(cs_wallet); // nOrderPosNext
51ed9ec9 1127 int64_t nRet = nOrderPosNext++;
4291e8fe
PW
1128 if (pwalletdb) {
1129 pwalletdb->WriteOrderPosNext(nOrderPosNext);
1130 } else {
1131 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
1132 }
da7b8c12
LD
1133 return nRet;
1134}
1135
ddb709e9 1136CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
c3f95ef1 1137{
95691680 1138 AssertLockHeld(cs_wallet); // mapWallet
c3f95ef1
LD
1139 CWalletDB walletdb(strWalletFile);
1140
1141 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
1142 TxItems txOrdered;
1143
1144 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
1145 // would make this much faster for applications that do this a lot.
1146 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1147 {
1148 CWalletTx* wtx = &((*it).second);
1149 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
1150 }
ddb709e9 1151 acentries.clear();
c3f95ef1
LD
1152 walletdb.ListAccountCreditDebit(strAccount, acentries);
1153 BOOST_FOREACH(CAccountingEntry& entry, acentries)
1154 {
1155 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
1156 }
1157
1158 return txOrdered;
1159}
1160
95d888a6
PW
1161void CWallet::MarkDirty()
1162{
95d888a6 1163 {
f8dcd5ca 1164 LOCK(cs_wallet);
95d888a6
PW
1165 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1166 item.second.MarkDirty();
1167 }
1168}
1169
1a62587e 1170/**
9a2b8ae5
JG
1171 * Ensure that every note in the wallet (for which we possess a spending key)
1172 * has a cached nullifier.
1a62587e
JG
1173 */
1174bool CWallet::UpdateNullifierNoteMap()
1175{
1176 {
1177 LOCK(cs_wallet);
1178
1179 if (IsLocked())
1180 return false;
1181
1182 ZCNoteDecryption dec;
1183 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
005f3ad1 1184 for (mapSproutNoteData_t::value_type& item : wtxItem.second.mapSproutNoteData) {
1a62587e 1185 if (!item.second.nullifier) {
9a2b8ae5
JG
1186 if (GetNoteDecryptor(item.second.address, dec)) {
1187 auto i = item.first.js;
1188 auto hSig = wtxItem.second.vjoinsplit[i].h_sig(
1189 *pzcashParams, wtxItem.second.joinSplitPubKey);
618206c7 1190 item.second.nullifier = GetSproutNoteNullifier(
9a2b8ae5
JG
1191 wtxItem.second.vjoinsplit[i],
1192 item.second.address,
1193 dec,
1194 hSig,
1195 item.first.n);
1196 }
1a62587e
JG
1197 }
1198 }
ad1e90dd
S
1199
1200 // TODO: Sapling. This method is only called from RPC walletpassphrase, which is currently unsupported
1201 // as RPC encryptwallet is hidden behind two flags: -developerencryptwallet -experimentalfeatures
1202
6e263a5f 1203 UpdateNullifierNoteMapWithTx(wtxItem.second);
1a62587e
JG
1204 }
1205 }
1206 return true;
1207}
1208
6e263a5f 1209/**
ad1e90dd
S
1210 * Update mapSproutNullifiersToNotes and mapSaplingNullifiersToNotes
1211 * with the cached nullifiers in this tx.
6e263a5f
JG
1212 */
1213void CWallet::UpdateNullifierNoteMapWithTx(const CWalletTx& wtx)
8db7e25c
JG
1214{
1215 {
1216 LOCK(cs_wallet);
005f3ad1 1217 for (const mapSproutNoteData_t::value_type& item : wtx.mapSproutNoteData) {
1a62587e 1218 if (item.second.nullifier) {
f41bf503 1219 mapSproutNullifiersToNotes[*item.second.nullifier] = item.first;
1a62587e 1220 }
8db7e25c 1221 }
ad1e90dd
S
1222
1223 for (const mapSaplingNoteData_t::value_type& item : wtx.mapSaplingNoteData) {
1224 if (item.second.nullifier) {
1225 mapSaplingNullifiersToNotes[*item.second.nullifier] = item.first;
1226 }
1227 }
1228 }
1229}
1230
1231/**
1232 * Update mapSaplingNullifiersToNotes, computing the nullifier from a cached witness if necessary.
1233 */
1234void CWallet::UpdateSaplingNullifierNoteMapWithTx(CWalletTx& wtx) {
1235 LOCK(cs_wallet);
1236
1237 for (mapSaplingNoteData_t::value_type &item : wtx.mapSaplingNoteData) {
1238 SaplingOutPoint op = item.first;
1239 SaplingNoteData nd = item.second;
1240
c343e2db 1241 if (nd.witnesses.empty()) {
ad1e90dd
S
1242 // If there are no witnesses, erase the nullifier and associated mapping.
1243 if (item.second.nullifier) {
1244 mapSaplingNullifiersToNotes.erase(item.second.nullifier.get());
1245 }
1246 item.second.nullifier = boost::none;
1247 }
c343e2db 1248 else {
ad1e90dd
S
1249 uint64_t position = nd.witnesses.front().position();
1250 SaplingFullViewingKey fvk = mapSaplingFullViewingKeys.at(nd.ivk);
1251 OutputDescription output = wtx.vShieldedOutput[op.n];
1252 auto optPlaintext = SaplingNotePlaintext::decrypt(output.encCiphertext, nd.ivk, output.ephemeralKey, output.cm);
1253 if (!optPlaintext) {
1254 // An item in mapSaplingNoteData must have already been successfully decrypted,
1255 // otherwise the item would not exist in the first place.
1256 assert(false);
1257 }
1258 auto optNote = optPlaintext.get().note(nd.ivk);
1259 if (!optNote) {
1260 assert(false);
1261 }
1262 auto optNullifier = optNote.get().nullifier(fvk, position);
1263 if (!optNullifier) {
1264 // This should not happen. If it does, maybe the position has been corrupted or miscalculated?
1265 assert(false);
1266 }
1267 uint256 nullifier = optNullifier.get();
1268 mapSaplingNullifiersToNotes[nullifier] = op;
1269 item.second.nullifier = nullifier;
1270 }
1271 }
1272}
1273
1274/**
1275 * Iterate over transactions in a block and update the cached Sapling nullifiers
1276 * for transactions which belong to the wallet.
1277 */
1278void CWallet::UpdateSaplingNullifierNoteMapForBlock(const CBlock *pblock) {
1279 LOCK(cs_wallet);
1280
1281 for (const CTransaction& tx : pblock->vtx) {
1282 auto hash = tx.GetHash();
1283 bool txIsOurs = mapWallet.count(hash);
1284 if (txIsOurs) {
1285 UpdateSaplingNullifierNoteMapWithTx(mapWallet[hash]);
1286 }
8db7e25c
JG
1287 }
1288}
1289
44bc988e 1290bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb)
e8ef3da7 1291{
805344dc 1292 uint256 hash = wtxIn.GetHash();
731b89b8
GA
1293
1294 if (fFromLoadWallet)
1295 {
1296 mapWallet[hash] = wtxIn;
09ec3af1 1297 mapWallet[hash].BindWallet(this);
6e263a5f 1298 UpdateNullifierNoteMapWithTx(mapWallet[hash]);
93a18a36 1299 AddToSpends(hash);
731b89b8
GA
1300 }
1301 else
e8ef3da7 1302 {
f8dcd5ca 1303 LOCK(cs_wallet);
e8ef3da7
WL
1304 // Inserts only if not already there, returns tx inserted or tx found
1305 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
1306 CWalletTx& wtx = (*ret.first).second;
4c6e2295 1307 wtx.BindWallet(this);
6e263a5f 1308 UpdateNullifierNoteMapWithTx(wtx);
e8ef3da7
WL
1309 bool fInsertedNew = ret.second;
1310 if (fInsertedNew)
9c7722b7 1311 {
e8ef3da7 1312 wtx.nTimeReceived = GetAdjustedTime();
44bc988e 1313 wtx.nOrderPos = IncOrderPosNext(pwalletdb);
c3f95ef1
LD
1314
1315 wtx.nTimeSmart = wtx.nTimeReceived;
4f152496 1316 if (!wtxIn.hashBlock.IsNull())
c3f95ef1
LD
1317 {
1318 if (mapBlockIndex.count(wtxIn.hashBlock))
1319 {
209377a7 1320 int64_t latestNow = wtx.nTimeReceived;
1321 int64_t latestEntry = 0;
c3f95ef1
LD
1322 {
1323 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
51ed9ec9 1324 int64_t latestTolerated = latestNow + 300;
ddb709e9
LD
1325 std::list<CAccountingEntry> acentries;
1326 TxItems txOrdered = OrderedTxItems(acentries);
c3f95ef1
LD
1327 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
1328 {
1329 CWalletTx *const pwtx = (*it).second.first;
1330 if (pwtx == &wtx)
1331 continue;
1332 CAccountingEntry *const pacentry = (*it).second.second;
51ed9ec9 1333 int64_t nSmartTime;
c3f95ef1
LD
1334 if (pwtx)
1335 {
1336 nSmartTime = pwtx->nTimeSmart;
1337 if (!nSmartTime)
1338 nSmartTime = pwtx->nTimeReceived;
1339 }
1340 else
1341 nSmartTime = pacentry->nTime;
1342 if (nSmartTime <= latestTolerated)
1343 {
1344 latestEntry = nSmartTime;
1345 if (nSmartTime > latestNow)
1346 latestNow = nSmartTime;
1347 break;
1348 }
1349 }
1350 }
1351
209377a7 1352 int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
c3f95ef1
LD
1353 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
1354 }
1355 else
5262fde0 1356 LogPrintf("AddToWallet(): found %s in block %s not in index\n",
805344dc 1357 wtxIn.GetHash().ToString(),
7d9d134b 1358 wtxIn.hashBlock.ToString());
c3f95ef1 1359 }
93a18a36 1360 AddToSpends(hash);
9c7722b7 1361 }
e8ef3da7
WL
1362
1363 bool fUpdated = false;
1364 if (!fInsertedNew)
1365 {
1366 // Merge
4f152496 1367 if (!wtxIn.hashBlock.IsNull() && wtxIn.hashBlock != wtx.hashBlock)
e8ef3da7
WL
1368 {
1369 wtx.hashBlock = wtxIn.hashBlock;
1370 fUpdated = true;
1371 }
1372 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
1373 {
1374 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
1375 wtx.nIndex = wtxIn.nIndex;
1376 fUpdated = true;
1377 }
ac1c9435 1378 if (UpdatedNoteData(wtxIn, wtx)) {
c3a7307a
JG
1379 fUpdated = true;
1380 }
e8ef3da7
WL
1381 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
1382 {
1383 wtx.fFromMe = wtxIn.fFromMe;
1384 fUpdated = true;
1385 }
e8ef3da7
WL
1386 }
1387
1388 //// debug print
805344dc 1389 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
e8ef3da7
WL
1390
1391 // Write to disk
1392 if (fInsertedNew || fUpdated)
44bc988e 1393 if (!wtx.WriteToDisk(pwalletdb))
e8ef3da7 1394 return false;
ee4b170c 1395
93a18a36
GA
1396 // Break debit/credit balance caches:
1397 wtx.MarkDirty();
e8ef3da7 1398
fe4a6550
WL
1399 // Notify UI of new or updated transaction
1400 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
cae686d3 1401
1402 // notify an external script when a wallet transaction comes in or is updated
1403 std::string strCmd = GetArg("-walletnotify", "");
1404
1405 if ( !strCmd.empty())
1406 {
805344dc 1407 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
cae686d3 1408 boost::thread t(runCommand, strCmd); // thread runs free
1409 }
1410
fe4a6550 1411 }
e8ef3da7
WL
1412 return true;
1413}
1414
ac1c9435
JG
1415bool CWallet::UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx)
1416{
3a83e7c9
S
1417 bool unchangedSproutFlag = (wtxIn.mapSproutNoteData.empty() || wtxIn.mapSproutNoteData == wtx.mapSproutNoteData);
1418 if (!unchangedSproutFlag) {
1419 auto tmp = wtxIn.mapSproutNoteData;
1420 // Ensure we keep any cached witnesses we may already have
1421 for (const std::pair <JSOutPoint, SproutNoteData> nd : wtx.mapSproutNoteData) {
1422 if (tmp.count(nd.first) && nd.second.witnesses.size() > 0) {
1423 tmp.at(nd.first).witnesses.assign(
1424 nd.second.witnesses.cbegin(), nd.second.witnesses.cend());
1425 }
1426 tmp.at(nd.first).witnessHeight = nd.second.witnessHeight;
1427 }
1428 // Now copy over the updated note data
1429 wtx.mapSproutNoteData = tmp;
ac1c9435 1430 }
3a83e7c9
S
1431
1432 bool unchangedSaplingFlag = (wtxIn.mapSaplingNoteData.empty() || wtxIn.mapSaplingNoteData == wtx.mapSaplingNoteData);
1433 if (!unchangedSaplingFlag) {
1434 auto tmp = wtxIn.mapSaplingNoteData;
1435 // Ensure we keep any cached witnesses we may already have
1436
1437 for (const std::pair <SaplingOutPoint, SaplingNoteData> nd : wtx.mapSaplingNoteData) {
1438 if (tmp.count(nd.first) && nd.second.witnesses.size() > 0) {
1439 tmp.at(nd.first).witnesses.assign(
1440 nd.second.witnesses.cbegin(), nd.second.witnesses.cend());
1441 }
1442 tmp.at(nd.first).witnessHeight = nd.second.witnessHeight;
ac1c9435 1443 }
3a83e7c9
S
1444
1445 // Now copy over the updated note data
1446 wtx.mapSaplingNoteData = tmp;
ac1c9435 1447 }
3a83e7c9
S
1448
1449 return !unchangedSproutFlag || !unchangedSaplingFlag;
ac1c9435
JG
1450}
1451
5b40d886
MF
1452/**
1453 * Add a transaction to the wallet, or update it.
1454 * pblock is optional, but should be provided if the transaction is known to be in a block.
1455 * If fUpdate is true, existing transactions will be updated.
1456 */
d38da59b 1457bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
e8ef3da7 1458{
e8ef3da7 1459 {
53d56881 1460 AssertLockHeld(cs_wallet);
805344dc 1461 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
6cc4a62c 1462 if (fExisted && !fUpdate) return false;
78584ef7
S
1463 auto sproutNoteData = FindMySproutNotes(tx);
1464 auto saplingNoteData = FindMySaplingNotes(tx);
1465 if (fExisted || IsMine(tx) || IsFromMe(tx) || sproutNoteData.size() > 0 || saplingNoteData.size() > 0)
6cc4a62c
GA
1466 {
1467 CWalletTx wtx(this,tx);
44bc988e 1468
78584ef7
S
1469 if (sproutNoteData.size() > 0) {
1470 wtx.SetSproutNoteData(sproutNoteData);
1471 }
1472
1473 if (saplingNoteData.size() > 0) {
1474 wtx.SetSaplingNoteData(saplingNoteData);
be74c80d 1475 }
c3a7307a 1476
6cc4a62c
GA
1477 // Get merkle branch if transaction was found in a block
1478 if (pblock)
4b0deb3b 1479 wtx.SetMerkleBranch(*pblock);
44bc988e
CL
1480
1481 // Do not flush the wallet here for performance reasons
1482 // this is safe, as in case of a crash, we rescan the necessary blocks on startup through our SetBestChain-mechanism
1483 CWalletDB walletdb(strWalletFile, "r+", false);
1484
1485 return AddToWallet(wtx, false, &walletdb);
6cc4a62c 1486 }
e8ef3da7 1487 }
e8ef3da7
WL
1488 return false;
1489}
1490
d38da59b 1491void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
93a18a36 1492{
55a1db4f 1493 LOCK2(cs_main, cs_wallet);
d38da59b 1494 if (!AddToWalletIfInvolvingMe(tx, pblock, true))
93a18a36
GA
1495 return; // Not one of ours
1496
ac1c9435
JG
1497 MarkAffectedTransactionsDirty(tx);
1498}
1499
1500void CWallet::MarkAffectedTransactionsDirty(const CTransaction& tx)
1501{
93a18a36
GA
1502 // If a transaction changes 'conflicted' state, that changes the balance
1503 // available of the outputs it spends. So force those to be
1504 // recomputed, also:
1505 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1506 {
1507 if (mapWallet.count(txin.prevout.hash))
1508 mapWallet[txin.prevout.hash].MarkDirty();
1509 }
8db7e25c
JG
1510 for (const JSDescription& jsdesc : tx.vjoinsplit) {
1511 for (const uint256& nullifier : jsdesc.nullifiers) {
f41bf503 1512 if (mapSproutNullifiersToNotes.count(nullifier) &&
dae1c420 1513 mapWallet.count(mapSproutNullifiersToNotes[nullifier].hash)) {
f41bf503 1514 mapWallet[mapSproutNullifiersToNotes[nullifier].hash].MarkDirty();
8db7e25c
JG
1515 }
1516 }
1517 }
dae1c420
S
1518
1519 for (const SpendDescription &spend : tx.vShieldedSpend) {
1520 uint256 nullifier = spend.nullifier;
1521 if (mapSaplingNullifiersToNotes.count(nullifier) &&
1522 mapWallet.count(mapSaplingNullifiersToNotes[nullifier].hash)) {
1523 mapWallet[mapSaplingNullifiersToNotes[nullifier].hash].MarkDirty();
1524 }
1525 }
00588c3f
PW
1526}
1527
1528void CWallet::EraseFromWallet(const uint256 &hash)
e8ef3da7
WL
1529{
1530 if (!fFileBacked)
00588c3f 1531 return;
e8ef3da7 1532 {
f8dcd5ca 1533 LOCK(cs_wallet);
e8ef3da7
WL
1534 if (mapWallet.erase(hash))
1535 CWalletDB(strWalletFile).EraseTx(hash);
1536 }
00588c3f 1537 return;
e8ef3da7
WL
1538}
1539
1540
1a62587e
JG
1541/**
1542 * Returns a nullifier if the SpendingKey is available
1543 * Throws std::runtime_error if the decryptor doesn't match this note
1544 */
618206c7
S
1545boost::optional<uint256> CWallet::GetSproutNoteNullifier(const JSDescription &jsdesc,
1546 const libzcash::SproutPaymentAddress &address,
1547 const ZCNoteDecryption &dec,
1548 const uint256 &hSig,
1549 uint8_t n) const
1a62587e
JG
1550{
1551 boost::optional<uint256> ret;
5020a936 1552 auto note_pt = libzcash::SproutNotePlaintext::decrypt(
1a62587e
JG
1553 dec,
1554 jsdesc.ciphertexts[n],
1555 jsdesc.ephemeralKey,
1556 hSig,
1557 (unsigned char) n);
1558 auto note = note_pt.note(address);
9a2b8ae5
JG
1559 // SpendingKeys are only available if:
1560 // - We have them (this isn't a viewing key)
1561 // - The wallet is unlocked
e5eab182 1562 libzcash::SproutSpendingKey key;
25d5e80c 1563 if (GetSproutSpendingKey(address, key)) {
1a62587e
JG
1564 ret = note.nullifier(key);
1565 }
1566 return ret;
1567}
1568
e492d986
JG
1569/**
1570 * Finds all output notes in the given transaction that have been sent to
1571 * PaymentAddresses in this wallet.
1572 *
1573 * It should never be necessary to call this method with a CWalletTx, because
57faf44e 1574 * the result of FindMySproutNotes (for the addresses available at the time) will
005f3ad1 1575 * already have been cached in CWalletTx.mapSproutNoteData.
e492d986 1576 */
57faf44e 1577mapSproutNoteData_t CWallet::FindMySproutNotes(const CTransaction &tx) const
02e67455 1578{
3fac1020 1579 LOCK(cs_SpendingKeyStore);
fa511e10 1580 uint256 hash = tx.GetHash();
02e67455 1581
005f3ad1 1582 mapSproutNoteData_t noteData;
02e67455
JG
1583 for (size_t i = 0; i < tx.vjoinsplit.size(); i++) {
1584 auto hSig = tx.vjoinsplit[i].h_sig(*pzcashParams, tx.joinSplitPubKey);
1585 for (uint8_t j = 0; j < tx.vjoinsplit[i].ciphertexts.size(); j++) {
3fac1020 1586 for (const NoteDecryptorMap::value_type& item : mapNoteDecryptors) {
02e67455 1587 try {
02e67455 1588 auto address = item.first;
02e67455 1589 JSOutPoint jsoutpt {hash, i, j};
618206c7 1590 auto nullifier = GetSproutNoteNullifier(
1a62587e
JG
1591 tx.vjoinsplit[i],
1592 address,
1593 item.second,
1594 hSig, j);
1595 if (nullifier) {
005f3ad1 1596 SproutNoteData nd {address, *nullifier};
1a62587e
JG
1597 noteData.insert(std::make_pair(jsoutpt, nd));
1598 } else {
005f3ad1 1599 SproutNoteData nd {address};
1a62587e
JG
1600 noteData.insert(std::make_pair(jsoutpt, nd));
1601 }
02e67455 1602 break;
51fde9ea 1603 } catch (const note_decryption_failed &err) {
1a62587e 1604 // Couldn't decrypt with this decryptor
32a103aa
JG
1605 } catch (const std::exception &exc) {
1606 // Unexpected failure
57faf44e 1607 LogPrintf("FindMySproutNotes(): Unexpected error while testing decrypt:\n");
32a103aa 1608 LogPrintf("%s\n", exc.what());
02e67455
JG
1609 }
1610 }
1611 }
1612 }
1613 return noteData;
1614}
1615
78584ef7
S
1616
1617/**
1618 * Finds all output notes in the given transaction that have been sent to
1619 * SaplingPaymentAddresses in this wallet.
1620 *
1621 * It should never be necessary to call this method with a CWalletTx, because
1622 * the result of FindMySaplingNotes (for the addresses available at the time) will
1623 * already have been cached in CWalletTx.mapSaplingNoteData.
1624 */
1625mapSaplingNoteData_t CWallet::FindMySaplingNotes(const CTransaction &tx) const
1626{
1627 LOCK(cs_SpendingKeyStore);
1628 uint256 hash = tx.GetHash();
1629
1630 mapSaplingNoteData_t noteData;
1631
1632 // Protocol Spec: 4.19 Block Chain Scanning (Sapling)
1633 for (uint32_t i = 0; i < tx.vShieldedOutput.size(); ++i) {
1634 const OutputDescription output = tx.vShieldedOutput[i];
ec064abb
S
1635 for (auto it = mapSaplingFullViewingKeys.begin(); it != mapSaplingFullViewingKeys.end(); ++it) {
1636 SaplingIncomingViewingKey ivk = it->first;
78584ef7
S
1637 auto result = SaplingNotePlaintext::decrypt(output.encCiphertext, ivk, output.ephemeralKey, output.cm);
1638 if (!result) {
1639 continue;
1640 }
1641 // We don't cache the nullifier here as computing it requires knowledge of the note position
1642 // in the commitment tree, which can only be determined when the transaction has been mined.
1643 SaplingOutPoint op {hash, i};
1644 SaplingNoteData nd;
1645 nd.ivk = ivk;
1646 noteData.insert(std::make_pair(op, nd));
1647 break;
1648 }
1649 }
1650
1651 return noteData;
1652}
1653
037cacf2 1654bool CWallet::IsSproutNullifierFromMe(const uint256& nullifier) const
1551db87
JG
1655{
1656 {
1657 LOCK(cs_wallet);
f41bf503
S
1658 if (mapSproutNullifiersToNotes.count(nullifier) &&
1659 mapWallet.count(mapSproutNullifiersToNotes.at(nullifier).hash)) {
1551db87
JG
1660 return true;
1661 }
1662 }
1663 return false;
1664}
1665
d7cf640b
S
1666bool CWallet::IsSaplingNullifierFromMe(const uint256& nullifier) const
1667{
1668 {
1669 LOCK(cs_wallet);
1670 if (mapSaplingNullifiersToNotes.count(nullifier) &&
1671 mapWallet.count(mapSaplingNullifiersToNotes.at(nullifier).hash)) {
1672 return true;
1673 }
1674 }
1675 return false;
1676}
1677
8e8279e7 1678void CWallet::GetSproutNoteWitnesses(std::vector<JSOutPoint> notes,
8ea8ef98 1679 std::vector<boost::optional<SproutWitness>>& witnesses,
8e8279e7 1680 uint256 &final_anchor)
be74c80d 1681{
29523dc7
EOW
1682 LOCK(cs_wallet);
1683 witnesses.resize(notes.size());
1684 boost::optional<uint256> rt;
1685 int i = 0;
1686 for (JSOutPoint note : notes) {
1687 if (mapWallet.count(note.hash) &&
1688 mapWallet[note.hash].mapSproutNoteData.count(note) &&
1689 mapWallet[note.hash].mapSproutNoteData[note].witnesses.size() > 0) {
1690 witnesses[i] = mapWallet[note.hash].mapSproutNoteData[note].witnesses.front();
1691 if (!rt) {
1692 rt = witnesses[i]->root();
1693 } else {
1694 assert(*rt == witnesses[i]->root());
be74c80d 1695 }
be74c80d 1696 }
29523dc7
EOW
1697 i++;
1698 }
1699 // All returned witnesses have the same anchor
1700 if (rt) {
1701 final_anchor = *rt;
be74c80d
JG
1702 }
1703}
1704
e6b0a8b9 1705void CWallet::GetSaplingNoteWitnesses(std::vector<SaplingOutPoint> notes,
8ea8ef98 1706 std::vector<boost::optional<SaplingWitness>>& witnesses,
e6b0a8b9
EOW
1707 uint256 &final_anchor)
1708{
1709 LOCK(cs_wallet);
1710 witnesses.resize(notes.size());
1711 boost::optional<uint256> rt;
1712 int i = 0;
1713 for (SaplingOutPoint note : notes) {
1714 if (mapWallet.count(note.hash) &&
1715 mapWallet[note.hash].mapSaplingNoteData.count(note) &&
1716 mapWallet[note.hash].mapSaplingNoteData[note].witnesses.size() > 0) {
1717 witnesses[i] = mapWallet[note.hash].mapSaplingNoteData[note].witnesses.front();
1718 if (!rt) {
1719 rt = witnesses[i]->root();
1720 } else {
1721 assert(*rt == witnesses[i]->root());
1722 }
1723 }
1724 i++;
1725 }
1726 // All returned witnesses have the same anchor
1727 if (rt) {
1728 final_anchor = *rt;
1729 }
1730}
1731
c8988460 1732isminetype CWallet::IsMine(const CTxIn &txin) const
e8ef3da7 1733{
e8ef3da7 1734 {
f8dcd5ca 1735 LOCK(cs_wallet);
e8ef3da7
WL
1736 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1737 if (mi != mapWallet.end())
1738 {
1739 const CWalletTx& prev = (*mi).second;
1740 if (txin.prevout.n < prev.vout.size())
c8988460 1741 return IsMine(prev.vout[txin.prevout.n]);
e8ef3da7
WL
1742 }
1743 }
a3e192a3 1744 return ISMINE_NO;
e8ef3da7
WL
1745}
1746
a372168e 1747CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
e8ef3da7 1748{
e8ef3da7 1749 {
f8dcd5ca 1750 LOCK(cs_wallet);
e8ef3da7
WL
1751 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1752 if (mi != mapWallet.end())
1753 {
1754 const CWalletTx& prev = (*mi).second;
1755 if (txin.prevout.n < prev.vout.size())
d4640d7d 1756 if (IsMine(prev.vout[txin.prevout.n]) & filter)
e8ef3da7
WL
1757 return prev.vout[txin.prevout.n].nValue;
1758 }
1759 }
1760 return 0;
1761}
1762
eca0b1ea
JT
1763isminetype CWallet::IsMine(const CTxOut& txout) const
1764{
1765 return ::IsMine(*this, txout.scriptPubKey);
1766}
1767
1768CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1769{
1770 if (!MoneyRange(txout.nValue))
1771 throw std::runtime_error("CWallet::GetCredit(): value out of range");
1772 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1773}
1774
e679ec96
GA
1775bool CWallet::IsChange(const CTxOut& txout) const
1776{
2a45a494 1777 // TODO: fix handling of 'change' outputs. The assumption is that any
d5087d1b 1778 // payment to a script that is ours, but is not in the address book
2a45a494
GA
1779 // is change. That assumption is likely to break when we implement multisignature
1780 // wallets that return change back into a multi-signature-protected address;
1781 // a better way of identifying which outputs are 'the send' and which are
1782 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1783 // which output, if any, was change).
d5087d1b 1784 if (::IsMine(*this, txout.scriptPubKey))
f8dcd5ca 1785 {
d5087d1b
PW
1786 CTxDestination address;
1787 if (!ExtractDestination(txout.scriptPubKey, address))
1788 return true;
1789
f8dcd5ca
PW
1790 LOCK(cs_wallet);
1791 if (!mapAddressBook.count(address))
1792 return true;
1793 }
e679ec96
GA
1794 return false;
1795}
1796
eca0b1ea
JT
1797CAmount CWallet::GetChange(const CTxOut& txout) const
1798{
1799 if (!MoneyRange(txout.nValue))
1800 throw std::runtime_error("CWallet::GetChange(): value out of range");
1801 return (IsChange(txout) ? txout.nValue : 0);
1802}
1803
1804bool CWallet::IsMine(const CTransaction& tx) const
1805{
1806 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1807 if (IsMine(txout))
1808 return true;
1809 return false;
1810}
1811
1812bool CWallet::IsFromMe(const CTransaction& tx) const
1813{
1551db87
JG
1814 if (GetDebit(tx, ISMINE_ALL) > 0) {
1815 return true;
1816 }
1817 for (const JSDescription& jsdesc : tx.vjoinsplit) {
1818 for (const uint256& nullifier : jsdesc.nullifiers) {
037cacf2 1819 if (IsSproutNullifierFromMe(nullifier)) {
1551db87
JG
1820 return true;
1821 }
1822 }
1823 }
d7cf640b
S
1824 for (const SpendDescription &spend : tx.vShieldedSpend) {
1825 if (IsSaplingNullifierFromMe(spend.nullifier)) {
1826 return true;
1827 }
1828 }
1551db87 1829 return false;
eca0b1ea
JT
1830}
1831
1832CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1833{
1834 CAmount nDebit = 0;
1835 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1836 {
1837 nDebit += GetDebit(txin, filter);
1838 if (!MoneyRange(nDebit))
1839 throw std::runtime_error("CWallet::GetDebit(): value out of range");
1840 }
1841 return nDebit;
1842}
1843
1844CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1845{
1846 CAmount nCredit = 0;
1847 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1848 {
1849 nCredit += GetCredit(txout, filter);
1850 if (!MoneyRange(nCredit))
1851 throw std::runtime_error("CWallet::GetCredit(): value out of range");
1852 }
1853 return nCredit;
1854}
1855
1856CAmount CWallet::GetChange(const CTransaction& tx) const
1857{
1858 CAmount nChange = 0;
1859 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1860 {
1861 nChange += GetChange(txout);
1862 if (!MoneyRange(nChange))
1863 throw std::runtime_error("CWallet::GetChange(): value out of range");
1864 }
1865 return nChange;
1866}
1867
8e8279e7 1868void CWalletTx::SetSproutNoteData(mapSproutNoteData_t &noteData)
c3a7307a 1869{
005f3ad1
EOW
1870 mapSproutNoteData.clear();
1871 for (const std::pair<JSOutPoint, SproutNoteData> nd : noteData) {
c3a7307a
JG
1872 if (nd.first.js < vjoinsplit.size() &&
1873 nd.first.n < vjoinsplit[nd.first.js].ciphertexts.size()) {
1874 // Store the address and nullifier for the Note
005f3ad1 1875 mapSproutNoteData[nd.first] = nd.second;
c3a7307a 1876 } else {
57faf44e 1877 // If FindMySproutNotes() was used to obtain noteData,
c3a7307a 1878 // this should never happen
8e8279e7 1879 throw std::logic_error("CWalletTx::SetSproutNoteData(): Invalid note");
c3a7307a
JG
1880 }
1881 }
1882}
1883
e6b0a8b9
EOW
1884void CWalletTx::SetSaplingNoteData(mapSaplingNoteData_t &noteData)
1885{
1886 mapSaplingNoteData.clear();
1887 for (const std::pair<SaplingOutPoint, SaplingNoteData> nd : noteData) {
1888 if (nd.first.n < vShieldedOutput.size()) {
1889 mapSaplingNoteData[nd.first] = nd.second;
1890 } else {
1891 throw std::logic_error("CWalletTx::SetSaplingNoteData(): Invalid note");
1892 }
1893 }
1894}
1895
51ed9ec9 1896int64_t CWalletTx::GetTxTime() const
e8ef3da7 1897{
51ed9ec9 1898 int64_t n = nTimeSmart;
c3f95ef1 1899 return n ? n : nTimeReceived;
e8ef3da7
WL
1900}
1901
1902int CWalletTx::GetRequestCount() const
1903{
1904 // Returns -1 if it wasn't being tracked
1905 int nRequests = -1;
e8ef3da7 1906 {
f8dcd5ca 1907 LOCK(pwallet->cs_wallet);
e8ef3da7
WL
1908 if (IsCoinBase())
1909 {
1910 // Generated block
4f152496 1911 if (!hashBlock.IsNull())
e8ef3da7
WL
1912 {
1913 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1914 if (mi != pwallet->mapRequestCount.end())
1915 nRequests = (*mi).second;
1916 }
1917 }
1918 else
1919 {
1920 // Did anyone request this transaction?
805344dc 1921 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
e8ef3da7
WL
1922 if (mi != pwallet->mapRequestCount.end())
1923 {
1924 nRequests = (*mi).second;
1925
1926 // How about the block it's in?
4f152496 1927 if (nRequests == 0 && !hashBlock.IsNull())
e8ef3da7
WL
1928 {
1929 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1930 if (mi != pwallet->mapRequestCount.end())
1931 nRequests = (*mi).second;
1932 else
1933 nRequests = 1; // If it's in someone else's block it must have got out
1934 }
1935 }
1936 }
1937 }
1938 return nRequests;
1939}
1940
86cf60b5 1941// GetAmounts will determine the transparent debits and credits for a given wallet tx.
1b4568cb 1942void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
a372168e 1943 list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
e8ef3da7 1944{
e07c8e91 1945 nFee = 0;
e8ef3da7
WL
1946 listReceived.clear();
1947 listSent.clear();
1948 strSentAccount = strFromAccount;
1949
86cf60b5 1950 // Is this tx sent/signed by me?
a372168e 1951 CAmount nDebit = GetDebit(filter);
86cf60b5
S
1952 bool isFromMyTaddr = nDebit > 0; // debit>0 means we signed/sent this transaction
1953
86cf60b5
S
1954 // Compute fee if we sent this transaction.
1955 if (isFromMyTaddr) {
f6863889
S
1956 CAmount nValueOut = GetValueOut(); // transparent outputs plus all Sprout vpub_old and negative Sapling valueBalance
1957 CAmount nValueIn = GetShieldedValueIn();
86cf60b5
S
1958 nFee = nDebit - nValueOut + nValueIn;
1959 }
1960
1961 // Create output entry for vpub_old/new, if we sent utxos from this transaction
1962 if (isFromMyTaddr) {
1963 CAmount myVpubOld = 0;
1964 CAmount myVpubNew = 0;
1965 for (const JSDescription& js : vjoinsplit) {
1966 bool fMyJSDesc = false;
1967
1968 // Check input side
1969 for (const uint256& nullifier : js.nullifiers) {
037cacf2 1970 if (pwallet->IsSproutNullifierFromMe(nullifier)) {
86cf60b5
S
1971 fMyJSDesc = true;
1972 break;
1973 }
1974 }
1975
1976 // Check output side
1977 if (!fMyJSDesc) {
005f3ad1 1978 for (const std::pair<JSOutPoint, SproutNoteData> nd : this->mapSproutNoteData) {
86cf60b5
S
1979 if (nd.first.js < vjoinsplit.size() && nd.first.n < vjoinsplit[nd.first.js].ciphertexts.size()) {
1980 fMyJSDesc = true;
1981 break;
1982 }
1983 }
1984 }
1985
1986 if (fMyJSDesc) {
1987 myVpubOld += js.vpub_old;
1988 myVpubNew += js.vpub_new;
1989 }
1990
1991 if (!MoneyRange(js.vpub_old) || !MoneyRange(js.vpub_new) || !MoneyRange(myVpubOld) || !MoneyRange(myVpubNew)) {
1992 throw std::runtime_error("CWalletTx::GetAmounts: value out of range");
1993 }
1994 }
1995
1996 // Create an output for the value taken from or added to the transparent value pool by JoinSplits
1997 if (myVpubOld > myVpubNew) {
1998 COutputEntry output = {CNoDestination(), myVpubOld - myVpubNew, (int)vout.size()};
1999 listSent.push_back(output);
2000 } else if (myVpubNew > myVpubOld) {
2001 COutputEntry output = {CNoDestination(), myVpubNew - myVpubOld, (int)vout.size()};
2002 listReceived.push_back(output);
2003 }
e8ef3da7
WL
2004 }
2005
f9816408
S
2006 // If we sent utxos from this transaction, create output for value taken from (negative valueBalance)
2007 // or added (positive valueBalance) to the transparent value pool by Sapling shielding and unshielding.
2008 if (isFromMyTaddr) {
2009 if (valueBalance < 0) {
2010 COutputEntry output = {CNoDestination(), -valueBalance, (int) vout.size()};
2011 listSent.push_back(output);
2012 } else if (valueBalance > 0) {
2013 COutputEntry output = {CNoDestination(), valueBalance, (int) vout.size()};
2014 listReceived.push_back(output);
2015 }
2016 }
2017
e679ec96 2018 // Sent/received.
5bb76550 2019 for (unsigned int i = 0; i < vout.size(); ++i)
e8ef3da7 2020 {
1b4568cb 2021 const CTxOut& txout = vout[i];
a5c6c5d6 2022 isminetype fIsMine = pwallet->IsMine(txout);
96ed6821
LD
2023 // Only need to handle txouts if AT LEAST one of these is true:
2024 // 1) they debit from us (sent)
2025 // 2) the output is to us (received)
2026 if (nDebit > 0)
2027 {
2028 // Don't report 'change' txouts
2029 if (pwallet->IsChange(txout))
2030 continue;
96ed6821 2031 }
a5c6c5d6 2032 else if (!(fIsMine & filter))
96ed6821
LD
2033 continue;
2034
2035 // In either case, we need to get the destination address
10254401 2036 CTxDestination address;
10254401 2037 if (!ExtractDestination(txout.scriptPubKey, address))
e8ef3da7 2038 {
881a85a2 2039 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
805344dc 2040 this->GetHash().ToString());
96ed6821 2041 address = CNoDestination();
e8ef3da7
WL
2042 }
2043
5bb76550 2044 COutputEntry output = {address, txout.nValue, (int)i};
1b4568cb 2045
96ed6821 2046 // If we are debited by the transaction, add the output as a "sent" entry
e8ef3da7 2047 if (nDebit > 0)
1b4568cb 2048 listSent.push_back(output);
e8ef3da7 2049
96ed6821 2050 // If we are receiving the output, add it as a "received" entry
d512534c 2051 if (fIsMine & filter)
1b4568cb 2052 listReceived.push_back(output);
e8ef3da7
WL
2053 }
2054
2055}
2056
a372168e
MF
2057void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
2058 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
e8ef3da7 2059{
e07c8e91 2060 nReceived = nSent = nFee = 0;
e8ef3da7 2061
a372168e 2062 CAmount allFee;
e8ef3da7 2063 string strSentAccount;
1b4568cb
CL
2064 list<COutputEntry> listReceived;
2065 list<COutputEntry> listSent;
d4640d7d 2066 GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
e8ef3da7 2067
e8ef3da7
WL
2068 if (strAccount == strSentAccount)
2069 {
1b4568cb
CL
2070 BOOST_FOREACH(const COutputEntry& s, listSent)
2071 nSent += s.amount;
e8ef3da7
WL
2072 nFee = allFee;
2073 }
e8ef3da7 2074 {
f8dcd5ca 2075 LOCK(pwallet->cs_wallet);
1b4568cb 2076 BOOST_FOREACH(const COutputEntry& r, listReceived)
e8ef3da7 2077 {
1b4568cb 2078 if (pwallet->mapAddressBook.count(r.destination))
e8ef3da7 2079 {
1b4568cb 2080 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
61885513 2081 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
1b4568cb 2082 nReceived += r.amount;
e8ef3da7
WL
2083 }
2084 else if (strAccount.empty())
2085 {
1b4568cb 2086 nReceived += r.amount;
e8ef3da7
WL
2087 }
2088 }
2089 }
2090}
2091
722fa283 2092
44bc988e 2093bool CWalletTx::WriteToDisk(CWalletDB *pwalletdb)
e8ef3da7 2094{
805344dc 2095 return pwalletdb->WriteTx(GetHash(), *this);
e8ef3da7
WL
2096}
2097
4bc00dc1 2098void CWallet::WitnessNoteCommitment(std::vector<uint256> commitments,
8ea8ef98 2099 std::vector<boost::optional<SproutWitness>>& witnesses,
4bc00dc1 2100 uint256 &final_anchor)
a8ac403d 2101{
2dc35992 2102 witnesses.resize(commitments.size());
a8ac403d 2103 CBlockIndex* pindex = chainActive.Genesis();
4fc309f0 2104 SproutMerkleTree tree;
a8ac403d
SB
2105
2106 while (pindex) {
2107 CBlock block;
2108 ReadBlockFromDisk(block, pindex);
2109
2110 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2111 {
22de1602 2112 BOOST_FOREACH(const JSDescription& jsdesc, tx.vjoinsplit)
a8ac403d 2113 {
22de1602 2114 BOOST_FOREACH(const uint256 &note_commitment, jsdesc.commitments)
a8ac403d 2115 {
4bc00dc1 2116 tree.append(note_commitment);
1760b3cd 2117
8ea8ef98 2118 BOOST_FOREACH(boost::optional<SproutWitness>& wit, witnesses) {
2dc35992 2119 if (wit) {
4bc00dc1 2120 wit->append(note_commitment);
2dc35992
SB
2121 }
2122 }
2123
2124 size_t i = 0;
2125 BOOST_FOREACH(uint256& commitment, commitments) {
4bc00dc1 2126 if (note_commitment == commitment) {
2dc35992 2127 witnesses.at(i) = tree.witness();
1760b3cd 2128 }
2dc35992 2129 i++;
a8ac403d
SB
2130 }
2131 }
2132 }
2133 }
2134
ccb439c5 2135 uint256 current_anchor = tree.root();
a8ac403d
SB
2136
2137 // Consistency check: we should be able to find the current tree
2138 // in our CCoins view.
4fc309f0 2139 SproutMerkleTree dummy_tree;
008f4ee8 2140 assert(pcoinsTip->GetSproutAnchorAt(current_anchor, dummy_tree));
a8ac403d
SB
2141
2142 pindex = chainActive.Next(pindex);
2143 }
2144
ccb439c5
SB
2145 // TODO: #93; Select a root via some heuristic.
2146 final_anchor = tree.root();
a8ac403d 2147
8ea8ef98 2148 BOOST_FOREACH(boost::optional<SproutWitness>& wit, witnesses) {
2dc35992
SB
2149 if (wit) {
2150 assert(final_anchor == wit->root());
2151 }
1760b3cd 2152 }
a8ac403d
SB
2153}
2154
5b40d886
MF
2155/**
2156 * Scan the block chain (starting in pindexStart) for transactions
2157 * from or to us. If fUpdate is true, found transactions that already
2158 * exist in the wallet will be updated.
2159 */
e8ef3da7
WL
2160int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
2161{
2162 int ret = 0;
75b8953a 2163 int64_t nNow = GetTime();
11982d36 2164 const CChainParams& chainParams = Params();
e8ef3da7
WL
2165
2166 CBlockIndex* pindex = pindexStart;
e8ef3da7 2167 {
55a1db4f 2168 LOCK2(cs_main, cs_wallet);
39278369
CL
2169
2170 // no need to read and scan block, if block was created before
2171 // our wallet birthday (as adjusted for block time variability)
209377a7 2172 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
39278369
CL
2173 pindex = chainActive.Next(pindex);
2174
2175 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
11982d36
CF
2176 double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
2177 double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip(), false);
e8ef3da7
WL
2178 while (pindex)
2179 {
39278369 2180 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
11982d36 2181 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
8da9dd07 2182
e8ef3da7 2183 CBlock block;
7db120d5 2184 ReadBlockFromDisk(block, pindex);
e8ef3da7
WL
2185 BOOST_FOREACH(CTransaction& tx, block.vtx)
2186 {
d38da59b 2187 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
e8ef3da7
WL
2188 ret++;
2189 }
b6961fc1 2190
4fc309f0
EOW
2191 SproutMerkleTree sproutTree;
2192 SaplingMerkleTree saplingTree;
b6961fc1
JG
2193 // This should never fail: we should always be able to get the tree
2194 // state on the path to the tip of our chain
f86ee1c2
EOW
2195 assert(pcoinsTip->GetSproutAnchorAt(pindex->hashSproutAnchor, sproutTree));
2196 if (pindex->pprev) {
d9fe33b8
S
2197 if (NetworkUpgradeActive(pindex->pprev->nHeight, Params().GetConsensus(), Consensus::UPGRADE_SAPLING)) {
2198 assert(pcoinsTip->GetSaplingAnchorAt(pindex->pprev->hashFinalSaplingRoot, saplingTree));
2199 }
f86ee1c2 2200 }
b6961fc1 2201 // Increment note witness caches
f86ee1c2 2202 IncrementNoteWitnesses(pindex, &block, sproutTree, saplingTree);
b6961fc1 2203
4c6d41b8 2204 pindex = chainActive.Next(pindex);
75b8953a
B
2205 if (GetTime() >= nNow + 60) {
2206 nNow = GetTime();
11982d36 2207 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex));
75b8953a 2208 }
e8ef3da7 2209 }
39278369 2210 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
e8ef3da7
WL
2211 }
2212 return ret;
2213}
2214
2215void CWallet::ReacceptWalletTransactions()
2216{
7e6d23b1 2217 // If transactions aren't being broadcasted, don't let them into local mempool either
6f252627
WL
2218 if (!fBroadcastTransactions)
2219 return;
55a1db4f 2220 LOCK2(cs_main, cs_wallet);
e9c3215b 2221 std::map<int64_t, CWalletTx*> mapSorted;
2222
2223 // Sort pending wallet transactions based on their initial wallet insertion order
93a18a36 2224 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
e8ef3da7 2225 {
93a18a36
GA
2226 const uint256& wtxid = item.first;
2227 CWalletTx& wtx = item.second;
805344dc 2228 assert(wtx.GetHash() == wtxid);
e8ef3da7 2229
93a18a36
GA
2230 int nDepth = wtx.GetDepthInMainChain();
2231
e9c3215b 2232 if (!wtx.IsCoinBase() && nDepth < 0) {
2233 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
e8ef3da7
WL
2234 }
2235 }
e9c3215b 2236
2237 // Try to add wallet transactions to memory pool
2238 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
2239 {
2240 CWalletTx& wtx = *(item.second);
2241
2242 LOCK(mempool.cs);
2243 wtx.AcceptToMemoryPool(false);
2244 }
e8ef3da7
WL
2245}
2246
0f5954c4 2247bool CWalletTx::RelayWalletTransaction()
e8ef3da7 2248{
6f252627 2249 assert(pwallet->GetBroadcastTransactions());
e8ef3da7
WL
2250 if (!IsCoinBase())
2251 {
5eaf91a4 2252 if (GetDepthInMainChain() == 0) {
805344dc 2253 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
d38da59b 2254 RelayTransaction((CTransaction)*this);
0f5954c4 2255 return true;
e8ef3da7
WL
2256 }
2257 }
0f5954c4 2258 return false;
e8ef3da7
WL
2259}
2260
3015e0bc 2261set<uint256> CWalletTx::GetConflicts() const
731b89b8
GA
2262{
2263 set<uint256> result;
2264 if (pwallet != NULL)
2265 {
805344dc 2266 uint256 myHash = GetHash();
3015e0bc 2267 result = pwallet->GetConflicts(myHash);
731b89b8
GA
2268 result.erase(myHash);
2269 }
2270 return result;
2271}
2272
bbacd882
CF
2273CAmount CWalletTx::GetDebit(const isminefilter& filter) const
2274{
2275 if (vin.empty())
2276 return 0;
2277
2278 CAmount debit = 0;
2279 if(filter & ISMINE_SPENDABLE)
2280 {
2281 if (fDebitCached)
2282 debit += nDebitCached;
2283 else
2284 {
2285 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
2286 fDebitCached = true;
2287 debit += nDebitCached;
2288 }
2289 }
2290 if(filter & ISMINE_WATCH_ONLY)
2291 {
2292 if(fWatchDebitCached)
2293 debit += nWatchDebitCached;
2294 else
2295 {
2296 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
2297 fWatchDebitCached = true;
2298 debit += nWatchDebitCached;
2299 }
2300 }
2301 return debit;
2302}
2303
2304CAmount CWalletTx::GetCredit(const isminefilter& filter) const
2305{
2306 // Must wait until coinbase is safely deep enough in the chain before valuing it
2307 if (IsCoinBase() && GetBlocksToMaturity() > 0)
2308 return 0;
2309
2310 int64_t credit = 0;
2311 if (filter & ISMINE_SPENDABLE)
2312 {
2313 // GetBalance can assume transactions in mapWallet won't change
2314 if (fCreditCached)
2315 credit += nCreditCached;
2316 else
2317 {
2318 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
2319 fCreditCached = true;
2320 credit += nCreditCached;
2321 }
2322 }
2323 if (filter & ISMINE_WATCH_ONLY)
2324 {
2325 if (fWatchCreditCached)
2326 credit += nWatchCreditCached;
2327 else
2328 {
2329 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
2330 fWatchCreditCached = true;
2331 credit += nWatchCreditCached;
2332 }
2333 }
2334 return credit;
2335}
2336
2337CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
2338{
2339 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
2340 {
2341 if (fUseCache && fImmatureCreditCached)
2342 return nImmatureCreditCached;
2343 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
2344 fImmatureCreditCached = true;
2345 return nImmatureCreditCached;
2346 }
2347
2348 return 0;
2349}
2350
2351CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
2352{
2353 if (pwallet == 0)
2354 return 0;
2355
2356 // Must wait until coinbase is safely deep enough in the chain before valuing it
2357 if (IsCoinBase() && GetBlocksToMaturity() > 0)
2358 return 0;
2359
2360 if (fUseCache && fAvailableCreditCached)
2361 return nAvailableCreditCached;
2362
2363 CAmount nCredit = 0;
805344dc 2364 uint256 hashTx = GetHash();
bbacd882
CF
2365 for (unsigned int i = 0; i < vout.size(); i++)
2366 {
2367 if (!pwallet->IsSpent(hashTx, i))
2368 {
2369 const CTxOut &txout = vout[i];
2370 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
2371 if (!MoneyRange(nCredit))
2372 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
2373 }
2374 }
2375
2376 nAvailableCreditCached = nCredit;
2377 fAvailableCreditCached = true;
2378 return nCredit;
2379}
2380
2381CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
2382{
2383 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
2384 {
2385 if (fUseCache && fImmatureWatchCreditCached)
2386 return nImmatureWatchCreditCached;
2387 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
2388 fImmatureWatchCreditCached = true;
2389 return nImmatureWatchCreditCached;
2390 }
2391
2392 return 0;
2393}
2394
2395CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
2396{
2397 if (pwallet == 0)
2398 return 0;
2399
2400 // Must wait until coinbase is safely deep enough in the chain before valuing it
2401 if (IsCoinBase() && GetBlocksToMaturity() > 0)
2402 return 0;
2403
2404 if (fUseCache && fAvailableWatchCreditCached)
2405 return nAvailableWatchCreditCached;
2406
2407 CAmount nCredit = 0;
2408 for (unsigned int i = 0; i < vout.size(); i++)
2409 {
805344dc 2410 if (!pwallet->IsSpent(GetHash(), i))
bbacd882
CF
2411 {
2412 const CTxOut &txout = vout[i];
2413 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
2414 if (!MoneyRange(nCredit))
2415 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
2416 }
2417 }
2418
2419 nAvailableWatchCreditCached = nCredit;
2420 fAvailableWatchCreditCached = true;
2421 return nCredit;
2422}
2423
2424CAmount CWalletTx::GetChange() const
2425{
2426 if (fChangeCached)
2427 return nChangeCached;
2428 nChangeCached = pwallet->GetChange(*this);
2429 fChangeCached = true;
2430 return nChangeCached;
2431}
2432
2433bool CWalletTx::IsTrusted() const
2434{
2435 // Quick answer in most cases
75a4d512 2436 if (!CheckFinalTx(*this))
bbacd882
CF
2437 return false;
2438 int nDepth = GetDepthInMainChain();
2439 if (nDepth >= 1)
2440 return true;
2441 if (nDepth < 0)
2442 return false;
2443 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
2444 return false;
2445
2446 // Trusted if all inputs are from us and are in the mempool:
2447 BOOST_FOREACH(const CTxIn& txin, vin)
2448 {
2449 // Transactions not sent by us: not trusted
2450 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
2451 if (parent == NULL)
2452 return false;
2453 const CTxOut& parentOut = parent->vout[txin.prevout.n];
2454 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
2455 return false;
2456 }
2457 return true;
2458}
2459
0f5954c4
GA
2460std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
2461{
2462 std::vector<uint256> result;
2463
2464 LOCK(cs_wallet);
2465 // Sort them in chronological order
2466 multimap<unsigned int, CWalletTx*> mapSorted;
2467 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
2468 {
2469 CWalletTx& wtx = item.second;
2470 // Don't rebroadcast if newer than nTime:
2471 if (wtx.nTimeReceived > nTime)
2472 continue;
2473 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
2474 }
2475 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
2476 {
2477 CWalletTx& wtx = *item.second;
2478 if (wtx.RelayWalletTransaction())
805344dc 2479 result.push_back(wtx.GetHash());
0f5954c4
GA
2480 }
2481 return result;
2482}
2483
2484void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
e8ef3da7
WL
2485{
2486 // Do this infrequently and randomly to avoid giving away
2487 // that these are our transactions.
6f252627 2488 if (GetTime() < nNextResend || !fBroadcastTransactions)
e8ef3da7 2489 return;
203d1ae6
LD
2490 bool fFirst = (nNextResend == 0);
2491 nNextResend = GetTime() + GetRand(30 * 60);
e8ef3da7
WL
2492 if (fFirst)
2493 return;
2494
2495 // Only do it if there's been a new block since last time
0f5954c4 2496 if (nBestBlockTime < nLastResend)
e8ef3da7 2497 return;
203d1ae6 2498 nLastResend = GetTime();
e8ef3da7 2499
0f5954c4
GA
2500 // Rebroadcast unconfirmed txes older than 5 minutes before the last
2501 // block was found:
2502 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60);
2503 if (!relayed.empty())
2504 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
e8ef3da7
WL
2505}
2506
5b40d886 2507/** @} */ // end of mapWallet
e8ef3da7
WL
2508
2509
2510
2511
5b40d886
MF
2512/** @defgroup Actions
2513 *
2514 * @{
2515 */
e8ef3da7
WL
2516
2517
a372168e 2518CAmount CWallet::GetBalance() const
e8ef3da7 2519{
a372168e 2520 CAmount nTotal = 0;
e8ef3da7 2521 {
55a1db4f 2522 LOCK2(cs_main, cs_wallet);
e8ef3da7
WL
2523 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2524 {
2525 const CWalletTx* pcoin = &(*it).second;
0542619d 2526 if (pcoin->IsTrusted())
8fdb7e10 2527 nTotal += pcoin->GetAvailableCredit();
e8ef3da7
WL
2528 }
2529 }
2530
e8ef3da7
WL
2531 return nTotal;
2532}
2533
a372168e 2534CAmount CWallet::GetUnconfirmedBalance() const
df5ccbd2 2535{
a372168e 2536 CAmount nTotal = 0;
df5ccbd2 2537 {
55a1db4f 2538 LOCK2(cs_main, cs_wallet);
df5ccbd2
WL
2539 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2540 {
2541 const CWalletTx* pcoin = &(*it).second;
75a4d512 2542 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
8fdb7e10 2543 nTotal += pcoin->GetAvailableCredit();
2544 }
2545 }
2546 return nTotal;
2547}
2548
a372168e 2549CAmount CWallet::GetImmatureBalance() const
8fdb7e10 2550{
a372168e 2551 CAmount nTotal = 0;
8fdb7e10 2552 {
55a1db4f 2553 LOCK2(cs_main, cs_wallet);
8fdb7e10 2554 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2555 {
966a0e8c
PK
2556 const CWalletTx* pcoin = &(*it).second;
2557 nTotal += pcoin->GetImmatureCredit();
df5ccbd2
WL
2558 }
2559 }
2560 return nTotal;
2561}
e8ef3da7 2562
a372168e 2563CAmount CWallet::GetWatchOnlyBalance() const
ffd40da3 2564{
a372168e 2565 CAmount nTotal = 0;
ffd40da3 2566 {
39cc4922 2567 LOCK2(cs_main, cs_wallet);
ffd40da3
J
2568 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2569 {
2570 const CWalletTx* pcoin = &(*it).second;
2571 if (pcoin->IsTrusted())
2572 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2573 }
2574 }
870da77d 2575
ffd40da3
J
2576 return nTotal;
2577}
2578
a372168e 2579CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
ffd40da3 2580{
a372168e 2581 CAmount nTotal = 0;
ffd40da3 2582 {
39cc4922 2583 LOCK2(cs_main, cs_wallet);
ffd40da3
J
2584 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2585 {
2586 const CWalletTx* pcoin = &(*it).second;
75a4d512 2587 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
ffd40da3
J
2588 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2589 }
2590 }
2591 return nTotal;
2592}
2593
a372168e 2594CAmount CWallet::GetImmatureWatchOnlyBalance() const
ffd40da3 2595{
a372168e 2596 CAmount nTotal = 0;
ffd40da3 2597 {
39cc4922 2598 LOCK2(cs_main, cs_wallet);
ffd40da3
J
2599 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2600 {
2601 const CWalletTx* pcoin = &(*it).second;
2602 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2603 }
2604 }
2605 return nTotal;
2606}
2607
5b40d886
MF
2608/**
2609 * populate vCoins with vector of available COutputs.
2610 */
2b1cda3b 2611void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue, bool fIncludeCoinBase) const
9b0369c7
CM
2612{
2613 vCoins.clear();
2614
2615 {
ea3acaf3 2616 LOCK2(cs_main, cs_wallet);
9b0369c7
CM
2617 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2618 {
93a18a36 2619 const uint256& wtxid = it->first;
9b0369c7
CM
2620 const CWalletTx* pcoin = &(*it).second;
2621
75a4d512 2622 if (!CheckFinalTx(*pcoin))
a2709fad
GA
2623 continue;
2624
0542619d 2625 if (fOnlyConfirmed && !pcoin->IsTrusted())
9b0369c7
CM
2626 continue;
2627
2b1cda3b
S
2628 if (pcoin->IsCoinBase() && !fIncludeCoinBase)
2629 continue;
2630
9b0369c7
CM
2631 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2632 continue;
2633
2b72d46f
GA
2634 int nDepth = pcoin->GetDepthInMainChain();
2635 if (nDepth < 0)
2636 continue;
2637
fdbb537d 2638 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
c8988460 2639 isminetype mine = IsMine(pcoin->vout[i]);
a3e192a3 2640 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
219953ce 2641 !IsLockedCoin((*it).first, i) && (pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
aa30f655 2642 (!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected((*it).first, i)))
8d657a65 2643 vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO));
fdbb537d 2644 }
9b0369c7
CM
2645 }
2646 }
2647}
2648
a372168e
MF
2649static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2650 vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
831f59ce
CM
2651{
2652 vector<char> vfIncluded;
2653
2654 vfBest.assign(vValue.size(), true);
2655 nBest = nTotalLower;
2656
907a2aa4
GM
2657 seed_insecure_rand();
2658
831f59ce
CM
2659 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2660 {
2661 vfIncluded.assign(vValue.size(), false);
a372168e 2662 CAmount nTotal = 0;
831f59ce
CM
2663 bool fReachedTarget = false;
2664 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2665 {
2666 for (unsigned int i = 0; i < vValue.size(); i++)
2667 {
907a2aa4
GM
2668 //The solver here uses a randomized algorithm,
2669 //the randomness serves no real security purpose but is just
2670 //needed to prevent degenerate behavior and it is important
5b40d886 2671 //that the rng is fast. We do not use a constant random sequence,
907a2aa4
GM
2672 //because there may be some privacy improvement by making
2673 //the selection random.
2674 if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
831f59ce
CM
2675 {
2676 nTotal += vValue[i].first;
2677 vfIncluded[i] = true;
2678 if (nTotal >= nTargetValue)
2679 {
2680 fReachedTarget = true;
2681 if (nTotal < nBest)
2682 {
2683 nBest = nTotal;
2684 vfBest = vfIncluded;
2685 }
2686 nTotal -= vValue[i].first;
2687 vfIncluded[i] = false;
2688 }
2689 }
2690 }
2691 }
2692 }
2693}
2694
a372168e
MF
2695bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
2696 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
e8ef3da7
WL
2697{
2698 setCoinsRet.clear();
2699 nValueRet = 0;
2700
2701 // List of values less than target
a372168e
MF
2702 pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
2703 coinLowestLarger.first = std::numeric_limits<CAmount>::max();
e8ef3da7 2704 coinLowestLarger.second.first = NULL;
a372168e
MF
2705 vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
2706 CAmount nTotalLower = 0;
e8ef3da7 2707
e333ab56
CM
2708 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2709
c8988460 2710 BOOST_FOREACH(const COutput &output, vCoins)
e8ef3da7 2711 {
c8988460
PW
2712 if (!output.fSpendable)
2713 continue;
2714
9b0369c7 2715 const CWalletTx *pcoin = output.tx;
e8ef3da7 2716
a3e192a3 2717 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
9b0369c7 2718 continue;
e8ef3da7 2719
9b0369c7 2720 int i = output.i;
a372168e 2721 CAmount n = pcoin->vout[i].nValue;
e8ef3da7 2722
a372168e 2723 pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
e8ef3da7 2724
9b0369c7
CM
2725 if (n == nTargetValue)
2726 {
2727 setCoinsRet.insert(coin.second);
2728 nValueRet += coin.first;
2729 return true;
2730 }
2731 else if (n < nTargetValue + CENT)
2732 {
2733 vValue.push_back(coin);
2734 nTotalLower += n;
2735 }
2736 else if (n < coinLowestLarger.first)
2737 {
2738 coinLowestLarger = coin;
e8ef3da7
WL
2739 }
2740 }
2741
831f59ce 2742 if (nTotalLower == nTargetValue)
e8ef3da7 2743 {
c376ac35 2744 for (unsigned int i = 0; i < vValue.size(); ++i)
e8ef3da7
WL
2745 {
2746 setCoinsRet.insert(vValue[i].second);
2747 nValueRet += vValue[i].first;
2748 }
2749 return true;
2750 }
2751
831f59ce 2752 if (nTotalLower < nTargetValue)
e8ef3da7
WL
2753 {
2754 if (coinLowestLarger.second.first == NULL)
2755 return false;
2756 setCoinsRet.insert(coinLowestLarger.second);
2757 nValueRet += coinLowestLarger.first;
2758 return true;
2759 }
2760
e8ef3da7 2761 // Solve subset sum by stochastic approximation
d650f96d 2762 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
831f59ce 2763 vector<char> vfBest;
a372168e 2764 CAmount nBest;
e8ef3da7 2765
831f59ce
CM
2766 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
2767 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
2768 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
e8ef3da7 2769
831f59ce
CM
2770 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2771 // or the next bigger coin is closer), return the bigger coin
2772 if (coinLowestLarger.second.first &&
2773 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
e8ef3da7
WL
2774 {
2775 setCoinsRet.insert(coinLowestLarger.second);
2776 nValueRet += coinLowestLarger.first;
2777 }
2778 else {
c376ac35 2779 for (unsigned int i = 0; i < vValue.size(); i++)
e8ef3da7
WL
2780 if (vfBest[i])
2781 {
2782 setCoinsRet.insert(vValue[i].second);
2783 nValueRet += vValue[i].first;
2784 }
2785
faaeae1e 2786 LogPrint("selectcoins", "SelectCoins() best subset: ");
c376ac35 2787 for (unsigned int i = 0; i < vValue.size(); i++)
e8ef3da7 2788 if (vfBest[i])
7d9d134b
WL
2789 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
2790 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
e8ef3da7
WL
2791 }
2792
2793 return true;
2794}
2795
2b1cda3b 2796bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, bool& fOnlyCoinbaseCoinsRet, bool& fNeedCoinbaseCoinsRet, const CCoinControl* coinControl) const
e8ef3da7 2797{
2b1cda3b
S
2798 // Output parameter fOnlyCoinbaseCoinsRet is set to true when the only available coins are coinbase utxos.
2799 vector<COutput> vCoinsNoCoinbase, vCoinsWithCoinbase;
2800 AvailableCoins(vCoinsNoCoinbase, true, coinControl, false, false);
2801 AvailableCoins(vCoinsWithCoinbase, true, coinControl, false, true);
2802 fOnlyCoinbaseCoinsRet = vCoinsNoCoinbase.size() == 0 && vCoinsWithCoinbase.size() > 0;
2803
2804 // If coinbase utxos can only be sent to zaddrs, exclude any coinbase utxos from coin selection.
2805 bool fProtectCoinbase = Params().GetConsensus().fCoinbaseMustBeProtected;
2806 vector<COutput> vCoins = (fProtectCoinbase) ? vCoinsNoCoinbase : vCoinsWithCoinbase;
2807
2808 // Output parameter fNeedCoinbaseCoinsRet is set to true if coinbase utxos need to be spent to meet target amount
2809 if (fProtectCoinbase && vCoinsWithCoinbase.size() > vCoinsNoCoinbase.size()) {
2810 CAmount value = 0;
2811 for (const COutput& out : vCoinsNoCoinbase) {
2812 if (!out.fSpendable) {
2813 continue;
2814 }
2815 value += out.tx->vout[out.i].nValue;
2816 }
2817 if (value <= nTargetValue) {
2818 CAmount valueWithCoinbase = 0;
2819 for (const COutput& out : vCoinsWithCoinbase) {
2820 if (!out.fSpendable) {
2821 continue;
2822 }
2823 valueWithCoinbase += out.tx->vout[out.i].nValue;
2824 }
2825 fNeedCoinbaseCoinsRet = (valueWithCoinbase >= nTargetValue);
2826 }
2827 }
6a86c24d
CL
2828
2829 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
aa30f655 2830 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
6a86c24d
CL
2831 {
2832 BOOST_FOREACH(const COutput& out, vCoins)
2833 {
aa30f655
MC
2834 if (!out.fSpendable)
2835 continue;
6a86c24d
CL
2836 nValueRet += out.tx->vout[out.i].nValue;
2837 setCoinsRet.insert(make_pair(out.tx, out.i));
2838 }
2839 return (nValueRet >= nTargetValue);
2840 }
9b0369c7 2841
aa30f655
MC
2842 // calculate value from preset inputs and store them
2843 set<pair<const CWalletTx*, uint32_t> > setPresetCoins;
2844 CAmount nValueFromPresetInputs = 0;
2845
2846 std::vector<COutPoint> vPresetInputs;
2847 if (coinControl)
2848 coinControl->ListSelected(vPresetInputs);
2849 BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
2850 {
2851 map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2852 if (it != mapWallet.end())
2853 {
2854 const CWalletTx* pcoin = &it->second;
2855 // Clearly invalid input, fail
2856 if (pcoin->vout.size() <= outpoint.n)
2857 return false;
2858 nValueFromPresetInputs += pcoin->vout[outpoint.n].nValue;
2859 setPresetCoins.insert(make_pair(pcoin, outpoint.n));
2860 } else
2861 return false; // TODO: Allow non-wallet inputs
2862 }
2863
2864 // remove preset inputs from vCoins
2865 for (vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2866 {
2867 if (setPresetCoins.count(make_pair(it->tx, it->i)))
2868 it = vCoins.erase(it);
2869 else
2870 ++it;
2871 }
2872
2873 bool res = nTargetValue <= nValueFromPresetInputs ||
2874 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, vCoins, setCoinsRet, nValueRet) ||
2875 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, vCoins, setCoinsRet, nValueRet) ||
2876 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, vCoins, setCoinsRet, nValueRet));
2877
2878 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2879 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2880
2881 // add preset inputs to the total value selected
2882 nValueRet += nValueFromPresetInputs;
2883
2884 return res;
2885}
2886
2887bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount &nFeeRet, int& nChangePosRet, std::string& strFailReason)
2888{
2889 vector<CRecipient> vecSend;
2890
2891 // Turn the txout set into a CRecipient vector
2892 BOOST_FOREACH(const CTxOut& txOut, tx.vout)
2893 {
2894 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, false};
2895 vecSend.push_back(recipient);
2896 }
2897
2898 CCoinControl coinControl;
2899 coinControl.fAllowOtherInputs = true;
2900 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2901 coinControl.Select(txin.prevout);
2902
2903 CReserveKey reservekey(this);
2904 CWalletTx wtx;
efb7662d 2905
aa30f655
MC
2906 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosRet, strFailReason, &coinControl, false))
2907 return false;
2908
2909 if (nChangePosRet != -1)
2910 tx.vout.insert(tx.vout.begin() + nChangePosRet, wtx.vout[nChangePosRet]);
2911
2912 // Add new txins (keeping original txin scriptSig/order)
2913 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
2914 {
2915 bool found = false;
2916 BOOST_FOREACH(const CTxIn& origTxIn, tx.vin)
2917 {
2918 if (txin.prevout.hash == origTxIn.prevout.hash && txin.prevout.n == origTxIn.prevout.n)
2919 {
2920 found = true;
2921 break;
2922 }
2923 }
2924 if (!found)
2925 tx.vin.push_back(txin);
2926 }
2927
2928 return true;
e8ef3da7
WL
2929}
2930
aa30f655
MC
2931bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2932 int& nChangePosRet, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
e8ef3da7 2933{
a372168e 2934 CAmount nValue = 0;
292623ad
CL
2935 unsigned int nSubtractFeeFromAmount = 0;
2936 BOOST_FOREACH (const CRecipient& recipient, vecSend)
e8ef3da7 2937 {
292623ad 2938 if (nValue < 0 || recipient.nAmount < 0)
1f00f4e9
GA
2939 {
2940 strFailReason = _("Transaction amounts must be positive");
e8ef3da7 2941 return false;
1f00f4e9 2942 }
292623ad
CL
2943 nValue += recipient.nAmount;
2944
2945 if (recipient.fSubtractFeeFromAmount)
2946 nSubtractFeeFromAmount++;
e8ef3da7
WL
2947 }
2948 if (vecSend.empty() || nValue < 0)
1f00f4e9
GA
2949 {
2950 strFailReason = _("Transaction amounts must be positive");
e8ef3da7 2951 return false;
1f00f4e9 2952 }
e8ef3da7 2953
b33d1f5e 2954 wtxNew.fTimeReceivedIsTxTime = true;
4c6e2295 2955 wtxNew.BindWallet(this);
9bb37bf0 2956 int nextBlockHeight = chainActive.Height() + 1;
072099d7 2957 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(
9bb37bf0 2958 Params().GetConsensus(), nextBlockHeight);
e8ef3da7 2959
9bb37bf0 2960 // Activates after Overwinter network upgrade
9bb37bf0 2961 if (NetworkUpgradeActive(nextBlockHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER)) {
fa70084c 2962 if (txNew.nExpiryHeight >= TX_EXPIRY_HEIGHT_THRESHOLD){
9bb37bf0 2963 strFailReason = _("nExpiryHeight must be less than TX_EXPIRY_HEIGHT_THRESHOLD.");
7b92f27e 2964 return false;
9bb37bf0
JG
2965 }
2966 }
15ec5525 2967
25fee350 2968 unsigned int max_tx_size = MAX_TX_SIZE_AFTER_SAPLING;
15ec5525
JG
2969 if (!NetworkUpgradeActive(nextBlockHeight, Params().GetConsensus(), Consensus::UPGRADE_SAPLING)) {
2970 max_tx_size = MAX_TX_SIZE_BEFORE_SAPLING;
2971 }
efb7662d 2972
ba7fcc8d
PT
2973 // Discourage fee sniping.
2974 //
2975 // However because of a off-by-one-error in previous versions we need to
2976 // neuter it by setting nLockTime to at least one less than nBestHeight.
2977 // Secondly currently propagation of transactions created for block heights
2978 // corresponding to blocks that were just mined may be iffy - transactions
2979 // aren't re-accepted into the mempool - we additionally neuter the code by
2980 // going ten blocks back. Doesn't yet do anything for sniping, but does act
2981 // to shake out wallet bugs like not showing nLockTime'd transactions at
2982 // all.
2983 txNew.nLockTime = std::max(0, chainActive.Height() - 10);
2984
2985 // Secondly occasionally randomly pick a nLockTime even further back, so
2986 // that transactions that are delayed after signing for whatever reason,
2987 // e.g. high-latency mix networks and some CoinJoin implementations, have
2988 // better privacy.
2989 if (GetRandInt(10) == 0)
2990 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2991
2992 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2993 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2994
e8ef3da7 2995 {
f8dcd5ca 2996 LOCK2(cs_main, cs_wallet);
e8ef3da7 2997 {
c1c9d5b4 2998 nFeeRet = 0;
050d2e95 2999 while (true)
e8ef3da7 3000 {
4949004d
PW
3001 txNew.vin.clear();
3002 txNew.vout.clear();
e8ef3da7 3003 wtxNew.fFromMe = true;
292623ad
CL
3004 nChangePosRet = -1;
3005 bool fFirst = true;
e8ef3da7 3006
292623ad
CL
3007 CAmount nTotalValue = nValue;
3008 if (nSubtractFeeFromAmount == 0)
3009 nTotalValue += nFeeRet;
e8ef3da7
WL
3010 double dPriority = 0;
3011 // vouts to the payees
292623ad 3012 BOOST_FOREACH (const CRecipient& recipient, vecSend)
8de9bb53 3013 {
292623ad
CL
3014 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
3015
3016 if (recipient.fSubtractFeeFromAmount)
3017 {
3018 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
3019
3020 if (fFirst) // first receiver pays the remainder not divisible by output count
3021 {
3022 fFirst = false;
3023 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
3024 }
3025 }
3026
13fc83c7 3027 if (txout.IsDust(::minRelayTxFee))
1f00f4e9 3028 {
292623ad
CL
3029 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
3030 {
3031 if (txout.nValue < 0)
3032 strFailReason = _("The transaction amount is too small to pay the fee");
3033 else
3034 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
3035 }
3036 else
3037 strFailReason = _("Transaction amount too small");
8de9bb53 3038 return false;
1f00f4e9 3039 }
4949004d 3040 txNew.vout.push_back(txout);
8de9bb53 3041 }
e8ef3da7
WL
3042
3043 // Choose coins to use
3044 set<pair<const CWalletTx*,unsigned int> > setCoins;
a372168e 3045 CAmount nValueIn = 0;
2b1cda3b
S
3046 bool fOnlyCoinbaseCoins = false;
3047 bool fNeedCoinbaseCoins = false;
3048 if (!SelectCoins(nTotalValue, setCoins, nValueIn, fOnlyCoinbaseCoins, fNeedCoinbaseCoins, coinControl))
1f00f4e9 3049 {
2b1cda3b
S
3050 if (fOnlyCoinbaseCoins && Params().GetConsensus().fCoinbaseMustBeProtected) {
3051 strFailReason = _("Coinbase funds can only be sent to a zaddr");
3052 } else if (fNeedCoinbaseCoins) {
3053 strFailReason = _("Insufficient funds, coinbase funds can only be spent after they have been sent to a zaddr");
3054 } else {
3055 strFailReason = _("Insufficient funds");
3056 }
e8ef3da7 3057 return false;
1f00f4e9 3058 }
e8ef3da7
WL
3059 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
3060 {
a372168e 3061 CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
2d9b0b7f 3062 //The coin age after the next block (depth+1) is used instead of the current,
d7836552
GM
3063 //reflecting an assumption the user would accept a bit more delay for
3064 //a chance at a free transaction.
2d9b0b7f
AM
3065 //But mempool inputs might still be in the mempool, so their age stays 0
3066 int age = pcoin.first->GetDepthInMainChain();
3067 if (age != 0)
3068 age += 1;
3069 dPriority += (double)nCredit * age;
e8ef3da7
WL
3070 }
3071
292623ad
CL
3072 CAmount nChange = nValueIn - nValue;
3073 if (nSubtractFeeFromAmount == 0)
3074 nChange -= nFeeRet;
a7dd11c6
PW
3075
3076 if (nChange > 0)
e8ef3da7 3077 {
bf798734
GA
3078 // Fill a vout to ourself
3079 // TODO: pass in scriptChange instead of reservekey so
3080 // change transaction isn't always pay-to-bitcoin-address
e8ef3da7 3081 CScript scriptChange;
6a86c24d
CL
3082
3083 // coin control: send change to custom address
3084 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
0be990ba 3085 scriptChange = GetScriptForDestination(coinControl->destChange);
6a86c24d
CL
3086
3087 // no coin control: send change to newly generated address
3088 else
3089 {
3090 // Note: We use a new key here to keep it from being obvious which side is the change.
3091 // The drawback is that by not reusing a previous key, the change may be lost if a
3092 // backup is restored, if the backup doesn't have the new private key for the change.
3093 // If we reused the old key, it would be possible to add code to look for and
3094 // rediscover unknown transactions that were written with keys of ours to recover
3095 // post-backup change.
3096
3097 // Reserve a new key pair from key pool
3098 CPubKey vchPubKey;
9b59e3bd
GM
3099 bool ret;
3100 ret = reservekey.GetReservedKey(vchPubKey);
3101 assert(ret); // should never fail, as we just unlocked
6a86c24d 3102
0be990ba 3103 scriptChange = GetScriptForDestination(vchPubKey.GetID());
6a86c24d 3104 }
e8ef3da7 3105
8de9bb53
GA
3106 CTxOut newTxOut(nChange, scriptChange);
3107
292623ad
CL
3108 // We do not move dust-change to fees, because the sender would end up paying more than requested.
3109 // This would be against the purpose of the all-inclusive feature.
3110 // So instead we raise the change and deduct from the recipient.
3111 if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust(::minRelayTxFee))
3112 {
3113 CAmount nDust = newTxOut.GetDustThreshold(::minRelayTxFee) - newTxOut.nValue;
3114 newTxOut.nValue += nDust; // raise change until no more dust
3115 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
3116 {
3117 if (vecSend[i].fSubtractFeeFromAmount)
3118 {
3119 txNew.vout[i].nValue -= nDust;
3120 if (txNew.vout[i].IsDust(::minRelayTxFee))
3121 {
3122 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
3123 return false;
3124 }
3125 break;
3126 }
3127 }
3128 }
3129
8de9bb53
GA
3130 // Never create dust outputs; if we would, just
3131 // add the dust to the fee.
13fc83c7 3132 if (newTxOut.IsDust(::minRelayTxFee))
8de9bb53
GA
3133 {
3134 nFeeRet += nChange;
3135 reservekey.ReturnKey();
3136 }
3137 else
3138 {
3139 // Insert change txn at random position:
292623ad
CL
3140 nChangePosRet = GetRandInt(txNew.vout.size()+1);
3141 vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosRet;
4949004d 3142 txNew.vout.insert(position, newTxOut);
8de9bb53 3143 }
e8ef3da7
WL
3144 }
3145 else
3146 reservekey.ReturnKey();
3147
3148 // Fill vin
ba7fcc8d
PT
3149 //
3150 // Note how the sequence number is set to max()-1 so that the
3151 // nLockTime set above actually works.
e8ef3da7 3152 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
805344dc 3153 txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
ba7fcc8d 3154 std::numeric_limits<unsigned int>::max()-1));
e8ef3da7 3155
9e84b5aa
S
3156 // Check mempooltxinputlimit to avoid creating a transaction which the local mempool rejects
3157 size_t limit = (size_t)GetArg("-mempooltxinputlimit", 0);
31afbcc5
JG
3158 {
3159 LOCK(cs_main);
3160 if (NetworkUpgradeActive(chainActive.Height() + 1, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER)) {
3161 limit = 0;
3162 }
3163 }
9e84b5aa
S
3164 if (limit > 0) {
3165 size_t n = txNew.vin.size();
3166 if (n > limit) {
3167 strFailReason = _(strprintf("Too many transparent inputs %zu > limit %zu", n, limit).c_str());
3168 return false;
3169 }
3170 }
3171
be126699
JG
3172 // Grab the current consensus branch ID
3173 auto consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus());
3174
e8ef3da7
WL
3175 // Sign
3176 int nIn = 0;
aa30f655 3177 CTransaction txNewConst(txNew);
e8ef3da7 3178 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
aa30f655
MC
3179 {
3180 bool signSuccess;
3181 const CScript& scriptPubKey = coin.first->vout[coin.second].scriptPubKey;
157a5d0d 3182 SignatureData sigdata;
aa30f655 3183 if (sign)
be126699 3184 signSuccess = ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.first->vout[coin.second].nValue, SIGHASH_ALL), scriptPubKey, sigdata, consensusBranchId);
aa30f655 3185 else
be126699 3186 signSuccess = ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata, consensusBranchId);
aa30f655
MC
3187
3188 if (!signSuccess)
1f00f4e9
GA
3189 {
3190 strFailReason = _("Signing transaction failed");
e8ef3da7 3191 return false;
157a5d0d
PW
3192 } else {
3193 UpdateTransaction(txNew, nIn, sigdata);
1f00f4e9 3194 }
157a5d0d 3195
aa30f655
MC
3196 nIn++;
3197 }
3198
3199 unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
3200
3201 // Remove scriptSigs if we used dummy signatures for fee calculation
3202 if (!sign) {
3203 BOOST_FOREACH (CTxIn& vin, txNew.vin)
3204 vin.scriptSig = CScript();
3205 }
e8ef3da7 3206
4949004d
PW
3207 // Embed the constructed transaction data in wtxNew.
3208 *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
3209
e8ef3da7 3210 // Limit size
15ec5525 3211 if (nBytes >= max_tx_size)
1f00f4e9
GA
3212 {
3213 strFailReason = _("Transaction too large");
e8ef3da7 3214 return false;
1f00f4e9 3215 }
aa30f655 3216
4d707d51 3217 dPriority = wtxNew.ComputePriority(dPriority, nBytes);
e8ef3da7 3218
aa279d61
GM
3219 // Can we complete this as a free transaction?
3220 if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
3221 {
3222 // Not enough fee: enough priority?
3223 double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
3224 // Not enough mempool history to estimate: use hard-coded AllowFree.
3225 if (dPriorityNeeded <= 0 && AllowFree(dPriority))
3226 break;
3227
3228 // Small enough, and priority high enough, to send for free
3229 if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
3230 break;
3231 }
b33d1f5e 3232
aa279d61 3233 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
b33d1f5e 3234
aa279d61
GM
3235 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
3236 // because we must be at the maximum allowed fee.
3237 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
e8ef3da7 3238 {
aa279d61
GM
3239 strFailReason = _("Transaction too large for fee policy");
3240 return false;
e8ef3da7
WL
3241 }
3242
aa279d61
GM
3243 if (nFeeRet >= nFeeNeeded)
3244 break; // Done, enough fee included.
b33d1f5e
GA
3245
3246 // Include more fee and try again.
3247 nFeeRet = nFeeNeeded;
3248 continue;
e8ef3da7
WL
3249 }
3250 }
3251 }
e8ef3da7 3252
292623ad 3253 return true;
e8ef3da7
WL
3254}
3255
5b40d886
MF
3256/**
3257 * Call after CreateTransaction unless you want to abort
3258 */
e8ef3da7
WL
3259bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
3260{
e8ef3da7 3261 {
f8dcd5ca 3262 LOCK2(cs_main, cs_wallet);
7d9d134b 3263 LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
e8ef3da7
WL
3264 {
3265 // This is only to keep the database open to defeat the auto-flush for the
3266 // duration of this scope. This is the only place where this optimization
3267 // maybe makes sense; please don't do it anywhere else.
44bc988e 3268 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r+") : NULL;
e8ef3da7
WL
3269
3270 // Take key pair from key pool so it won't be used again
3271 reservekey.KeepKey();
3272
3273 // Add tx to wallet, because if it has change it's also ours,
3274 // otherwise just for transaction history.
44bc988e 3275 AddToWallet(wtxNew, false, pwalletdb);
e8ef3da7 3276
93a18a36 3277 // Notify that old coins are spent
e8ef3da7
WL
3278 set<CWalletTx*> setCoins;
3279 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
3280 {
3281 CWalletTx &coin = mapWallet[txin.prevout.hash];
4c6e2295 3282 coin.BindWallet(this);
805344dc 3283 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
e8ef3da7
WL
3284 }
3285
3286 if (fFileBacked)
3287 delete pwalletdb;
3288 }
3289
3290 // Track how many getdata requests our transaction gets
805344dc 3291 mapRequestCount[wtxNew.GetHash()] = 0;
e8ef3da7 3292
6f252627 3293 if (fBroadcastTransactions)
e8ef3da7 3294 {
6f252627
WL
3295 // Broadcast
3296 if (!wtxNew.AcceptToMemoryPool(false))
3297 {
3298 // This must not fail. The transaction has already been signed and recorded.
7ff9d122 3299 LogPrintf("CommitTransaction(): Error: Transaction not valid\n");
6f252627
WL
3300 return false;
3301 }
3302 wtxNew.RelayWalletTransaction();
e8ef3da7 3303 }
e8ef3da7 3304 }
e8ef3da7
WL
3305 return true;
3306}
3307
a372168e 3308CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
b33d1f5e
GA
3309{
3310 // payTxFee is user-set "I want to pay this much"
a372168e 3311 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
c1c9d5b4
CL
3312 // user selected total at least (default=true)
3313 if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
3314 nFeeNeeded = payTxFee.GetFeePerK();
b33d1f5e
GA
3315 // User didn't set: use -txconfirmtarget to estimate...
3316 if (nFeeNeeded == 0)
3317 nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
3318 // ... unless we don't have enough mempool data, in which case fall
3319 // back to a hard-coded fee
3320 if (nFeeNeeded == 0)
13fc83c7 3321 nFeeNeeded = minTxFee.GetFee(nTxBytes);
aa279d61
GM
3322 // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
3323 if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
3324 nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
3325 // But always obey the maximum
3326 if (nFeeNeeded > maxTxFee)
3327 nFeeNeeded = maxTxFee;
b33d1f5e
GA
3328 return nFeeNeeded;
3329}
3330
e8ef3da7
WL
3331
3332
3333
eed1785f 3334DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
e8ef3da7
WL
3335{
3336 if (!fFileBacked)
4f76be1d 3337 return DB_LOAD_OK;
e8ef3da7 3338 fFirstRunRet = false;
eed1785f 3339 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
d764d916 3340 if (nLoadWalletRet == DB_NEED_REWRITE)
9e9869d0 3341 {
d764d916
GA
3342 if (CDB::Rewrite(strWalletFile, "\x04pool"))
3343 {
012ca1c9 3344 LOCK(cs_wallet);
d764d916
GA
3345 setKeyPool.clear();
3346 // Note: can't top-up keypool here, because wallet is locked.
3347 // User will be prompted to unlock wallet the next operation
c6de7c35 3348 // that requires a new key.
d764d916 3349 }
9e9869d0
PW
3350 }
3351
7ec55267
MC
3352 if (nLoadWalletRet != DB_LOAD_OK)
3353 return nLoadWalletRet;
fd61d6f5 3354 fFirstRunRet = !vchDefaultKey.IsValid();
e8ef3da7 3355
39278369
CL
3356 uiInterface.LoadWallet(this);
3357
116df55e 3358 return DB_LOAD_OK;
e8ef3da7
WL
3359}
3360
ae3d0aba 3361
77cbd462 3362DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
518f3bda
JG
3363{
3364 if (!fFileBacked)
3365 return DB_LOAD_OK;
77cbd462 3366 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
518f3bda
JG
3367 if (nZapWalletTxRet == DB_NEED_REWRITE)
3368 {
3369 if (CDB::Rewrite(strWalletFile, "\x04pool"))
3370 {
3371 LOCK(cs_wallet);
3372 setKeyPool.clear();
3373 // Note: can't top-up keypool here, because wallet is locked.
3374 // User will be prompted to unlock wallet the next operation
5b40d886 3375 // that requires a new key.
518f3bda
JG
3376 }
3377 }
3378
3379 if (nZapWalletTxRet != DB_LOAD_OK)
3380 return nZapWalletTxRet;
3381
3382 return DB_LOAD_OK;
3383}
3384
3385
a41d5fe0 3386bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
ae3d0aba 3387{
ca4cf5cf
GA
3388 bool fUpdated = false;
3389 {
3390 LOCK(cs_wallet); // mapAddressBook
3391 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3392 fUpdated = mi != mapAddressBook.end();
3393 mapAddressBook[address].name = strName;
3394 if (!strPurpose.empty()) /* update purpose only if requested */
3395 mapAddressBook[address].purpose = strPurpose;
3396 }
8d657a65 3397 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
ca4cf5cf 3398 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
ae3d0aba
WL
3399 if (!fFileBacked)
3400 return false;
07444da1 3401 if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(EncodeDestination(address), strPurpose))
a41d5fe0 3402 return false;
07444da1 3403 return CWalletDB(strWalletFile).WriteName(EncodeDestination(address), strName);
ae3d0aba
WL
3404}
3405
a41d5fe0 3406bool CWallet::DelAddressBook(const CTxDestination& address)
ae3d0aba 3407{
b10e1470 3408 {
ca4cf5cf
GA
3409 LOCK(cs_wallet); // mapAddressBook
3410
3411 if(fFileBacked)
b10e1470 3412 {
ca4cf5cf 3413 // Delete destdata tuples associated with address
07444da1 3414 std::string strAddress = EncodeDestination(address);
ca4cf5cf
GA
3415 BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
3416 {
3417 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
3418 }
b10e1470 3419 }
ca4cf5cf 3420 mapAddressBook.erase(address);
b10e1470
WL
3421 }
3422
8d657a65 3423 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
ca4cf5cf 3424
ae3d0aba
WL
3425 if (!fFileBacked)
3426 return false;
07444da1
PW
3427 CWalletDB(strWalletFile).ErasePurpose(EncodeDestination(address));
3428 return CWalletDB(strWalletFile).EraseName(EncodeDestination(address));
ae3d0aba
WL
3429}
3430
fd61d6f5 3431bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
ae3d0aba
WL
3432{
3433 if (fFileBacked)
3434 {
3435 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
3436 return false;
3437 }
3438 vchDefaultKey = vchPubKey;
3439 return true;
3440}
3441
5b40d886
MF
3442/**
3443 * Mark old keypool keys as used,
efb7662d 3444 * and generate all new keys
5b40d886 3445 */
37971fcc
GA
3446bool CWallet::NewKeyPool()
3447{
37971fcc 3448 {
f8dcd5ca 3449 LOCK(cs_wallet);
37971fcc 3450 CWalletDB walletdb(strWalletFile);
51ed9ec9 3451 BOOST_FOREACH(int64_t nIndex, setKeyPool)
37971fcc
GA
3452 walletdb.ErasePool(nIndex);
3453 setKeyPool.clear();
3454
3455 if (IsLocked())
3456 return false;
3457
51ed9ec9 3458 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
37971fcc
GA
3459 for (int i = 0; i < nKeys; i++)
3460 {
51ed9ec9 3461 int64_t nIndex = i+1;
37971fcc
GA
3462 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
3463 setKeyPool.insert(nIndex);
3464 }
f48742c2 3465 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
37971fcc
GA
3466 }
3467 return true;
3468}
3469
13dd2d09 3470bool CWallet::TopUpKeyPool(unsigned int kpSize)
e8ef3da7 3471{
e8ef3da7 3472 {
f8dcd5ca
PW
3473 LOCK(cs_wallet);
3474
4e87d341
MC
3475 if (IsLocked())
3476 return false;
3477
e8ef3da7
WL
3478 CWalletDB walletdb(strWalletFile);
3479
3480 // Top up key pool
13dd2d09
JG
3481 unsigned int nTargetSize;
3482 if (kpSize > 0)
3483 nTargetSize = kpSize;
3484 else
51ed9ec9 3485 nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0);
13dd2d09 3486
faf705a4 3487 while (setKeyPool.size() < (nTargetSize + 1))
e8ef3da7 3488 {
51ed9ec9 3489 int64_t nEnd = 1;
e8ef3da7
WL
3490 if (!setKeyPool.empty())
3491 nEnd = *(--setKeyPool.end()) + 1;
3492 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
5262fde0 3493 throw runtime_error("TopUpKeyPool(): writing generated key failed");
e8ef3da7 3494 setKeyPool.insert(nEnd);
783b182c 3495 LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
e8ef3da7 3496 }
4e87d341
MC
3497 }
3498 return true;
3499}
3500
51ed9ec9 3501void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
4e87d341
MC
3502{
3503 nIndex = -1;
fd61d6f5 3504 keypool.vchPubKey = CPubKey();
4e87d341 3505 {
f8dcd5ca
PW
3506 LOCK(cs_wallet);
3507
4e87d341
MC
3508 if (!IsLocked())
3509 TopUpKeyPool();
e8ef3da7
WL
3510
3511 // Get the oldest key
4e87d341
MC
3512 if(setKeyPool.empty())
3513 return;
3514
3515 CWalletDB walletdb(strWalletFile);
3516
e8ef3da7
WL
3517 nIndex = *(setKeyPool.begin());
3518 setKeyPool.erase(setKeyPool.begin());
3519 if (!walletdb.ReadPool(nIndex, keypool))
5262fde0 3520 throw runtime_error("ReserveKeyFromKeyPool(): read failed");
fd61d6f5 3521 if (!HaveKey(keypool.vchPubKey.GetID()))
5262fde0 3522 throw runtime_error("ReserveKeyFromKeyPool(): unknown key in key pool");
fd61d6f5 3523 assert(keypool.vchPubKey.IsValid());
f48742c2 3524 LogPrintf("keypool reserve %d\n", nIndex);
e8ef3da7
WL
3525 }
3526}
3527
51ed9ec9 3528void CWallet::KeepKey(int64_t nIndex)
e8ef3da7
WL
3529{
3530 // Remove from key pool
3531 if (fFileBacked)
3532 {
3533 CWalletDB walletdb(strWalletFile);
6cc4a62c 3534 walletdb.ErasePool(nIndex);
e8ef3da7 3535 }
f48742c2 3536 LogPrintf("keypool keep %d\n", nIndex);
e8ef3da7
WL
3537}
3538
51ed9ec9 3539void CWallet::ReturnKey(int64_t nIndex)
e8ef3da7
WL
3540{
3541 // Return to key pool
f8dcd5ca
PW
3542 {
3543 LOCK(cs_wallet);
e8ef3da7 3544 setKeyPool.insert(nIndex);
f8dcd5ca 3545 }
f48742c2 3546 LogPrintf("keypool return %d\n", nIndex);
e8ef3da7
WL
3547}
3548
71ac5052 3549bool CWallet::GetKeyFromPool(CPubKey& result)
e8ef3da7 3550{
51ed9ec9 3551 int64_t nIndex = 0;
e8ef3da7 3552 CKeyPool keypool;
7db3b75b 3553 {
f8dcd5ca 3554 LOCK(cs_wallet);
ed02c95d
GA
3555 ReserveKeyFromKeyPool(nIndex, keypool);
3556 if (nIndex == -1)
7db3b75b 3557 {
ed02c95d
GA
3558 if (IsLocked()) return false;
3559 result = GenerateNewKey();
7db3b75b
GA
3560 return true;
3561 }
ed02c95d
GA
3562 KeepKey(nIndex);
3563 result = keypool.vchPubKey;
7db3b75b 3564 }
7db3b75b 3565 return true;
e8ef3da7
WL
3566}
3567
51ed9ec9 3568int64_t CWallet::GetOldestKeyPoolTime()
e8ef3da7 3569{
51ed9ec9 3570 int64_t nIndex = 0;
e8ef3da7
WL
3571 CKeyPool keypool;
3572 ReserveKeyFromKeyPool(nIndex, keypool);
4e87d341
MC
3573 if (nIndex == -1)
3574 return GetTime();
e8ef3da7
WL
3575 ReturnKey(nIndex);
3576 return keypool.nTime;
3577}
3578
a372168e 3579std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
22dfd735 3580{
a372168e 3581 map<CTxDestination, CAmount> balances;
22dfd735 3582
3583 {
3584 LOCK(cs_wallet);
3585 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3586 {
3587 CWalletTx *pcoin = &walletEntry.second;
3588
75a4d512 3589 if (!CheckFinalTx(*pcoin) || !pcoin->IsTrusted())
22dfd735 3590 continue;
3591
3592 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3593 continue;
3594
3595 int nDepth = pcoin->GetDepthInMainChain();
a3e192a3 3596 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
22dfd735 3597 continue;
3598
b1093efa 3599 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
22dfd735 3600 {
b1093efa 3601 CTxDestination addr;
22dfd735 3602 if (!IsMine(pcoin->vout[i]))
3603 continue;
b1093efa
GM
3604 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
3605 continue;
22dfd735 3606
a372168e 3607 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
22dfd735 3608
22dfd735 3609 if (!balances.count(addr))
3610 balances[addr] = 0;
3611 balances[addr] += n;
3612 }
3613 }
3614 }
3615
3616 return balances;
3617}
3618
b1093efa 3619set< set<CTxDestination> > CWallet::GetAddressGroupings()
22dfd735 3620{
95691680 3621 AssertLockHeld(cs_wallet); // mapWallet
b1093efa
GM
3622 set< set<CTxDestination> > groupings;
3623 set<CTxDestination> grouping;
22dfd735 3624
3625 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3626 {
3627 CWalletTx *pcoin = &walletEntry.second;
3628
a3fad211 3629 if (pcoin->vin.size() > 0)
22dfd735 3630 {
a3fad211 3631 bool any_mine = false;
22dfd735 3632 // group all input addresses with each other
3633 BOOST_FOREACH(CTxIn txin, pcoin->vin)
b1093efa
GM
3634 {
3635 CTxDestination address;
a3fad211
GM
3636 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3637 continue;
b1093efa
GM
3638 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
3639 continue;
3640 grouping.insert(address);
a3fad211 3641 any_mine = true;
b1093efa 3642 }
22dfd735 3643
3644 // group change with input addresses
a3fad211
GM
3645 if (any_mine)
3646 {
3647 BOOST_FOREACH(CTxOut txout, pcoin->vout)
3648 if (IsChange(txout))
3649 {
3650 CTxDestination txoutAddr;
3651 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3652 continue;
3653 grouping.insert(txoutAddr);
3654 }
3655 }
3656 if (grouping.size() > 0)
3657 {
3658 groupings.insert(grouping);
3659 grouping.clear();
3660 }
22dfd735 3661 }
3662
3663 // group lone addrs by themselves
b1093efa 3664 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
22dfd735 3665 if (IsMine(pcoin->vout[i]))
3666 {
b1093efa
GM
3667 CTxDestination address;
3668 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
3669 continue;
3670 grouping.insert(address);
22dfd735 3671 groupings.insert(grouping);
3672 grouping.clear();
3673 }
3674 }
3675
b1093efa
GM
3676 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3677 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3678 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
22dfd735 3679 {
3680 // make a set of all the groups hit by this new group
b1093efa
GM
3681 set< set<CTxDestination>* > hits;
3682 map< CTxDestination, set<CTxDestination>* >::iterator it;
3683 BOOST_FOREACH(CTxDestination address, grouping)
22dfd735 3684 if ((it = setmap.find(address)) != setmap.end())
3685 hits.insert((*it).second);
3686
3687 // merge all hit groups into a new single group and delete old groups
b1093efa
GM
3688 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
3689 BOOST_FOREACH(set<CTxDestination>* hit, hits)
22dfd735 3690 {
3691 merged->insert(hit->begin(), hit->end());
3692 uniqueGroupings.erase(hit);
3693 delete hit;
3694 }
3695 uniqueGroupings.insert(merged);
3696
3697 // update setmap
b1093efa 3698 BOOST_FOREACH(CTxDestination element, *merged)
22dfd735 3699 setmap[element] = merged;
3700 }
3701
b1093efa
GM
3702 set< set<CTxDestination> > ret;
3703 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
22dfd735 3704 {
3705 ret.insert(*uniqueGrouping);
3706 delete uniqueGrouping;
3707 }
3708
3709 return ret;
3710}
3711
db954a65 3712std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3624356e 3713{
43422a01 3714 LOCK(cs_wallet);
3624356e
GA
3715 set<CTxDestination> result;
3716 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
3717 {
3718 const CTxDestination& address = item.first;
3719 const string& strName = item.second.name;
3720 if (strName == strAccount)
3721 result.insert(address);
3722 }
3723 return result;
3724}
3725
360cfe14 3726bool CReserveKey::GetReservedKey(CPubKey& pubkey)
e8ef3da7
WL
3727{
3728 if (nIndex == -1)
3729 {
3730 CKeyPool keypool;
3731 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
0d7b28e5
MC
3732 if (nIndex != -1)
3733 vchPubKey = keypool.vchPubKey;
360cfe14 3734 else {
6c37f7fd 3735 return false;
cee69980 3736 }
e8ef3da7 3737 }
fd61d6f5 3738 assert(vchPubKey.IsValid());
360cfe14
PW
3739 pubkey = vchPubKey;
3740 return true;
e8ef3da7
WL
3741}
3742
3743void CReserveKey::KeepKey()
3744{
3745 if (nIndex != -1)
3746 pwallet->KeepKey(nIndex);
3747 nIndex = -1;
fd61d6f5 3748 vchPubKey = CPubKey();
e8ef3da7
WL
3749}
3750
3751void CReserveKey::ReturnKey()
3752{
3753 if (nIndex != -1)
3754 pwallet->ReturnKey(nIndex);
3755 nIndex = -1;
fd61d6f5 3756 vchPubKey = CPubKey();
e8ef3da7 3757}
ae3d0aba 3758
434e4273 3759void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
30ab2c9c
PW
3760{
3761 setAddress.clear();
3762
3763 CWalletDB walletdb(strWalletFile);
3764
f8dcd5ca 3765 LOCK2(cs_main, cs_wallet);
51ed9ec9 3766 BOOST_FOREACH(const int64_t& id, setKeyPool)
30ab2c9c
PW
3767 {
3768 CKeyPool keypool;
3769 if (!walletdb.ReadPool(id, keypool))
5262fde0 3770 throw runtime_error("GetAllReserveKeyHashes(): read failed");
fd61d6f5 3771 assert(keypool.vchPubKey.IsValid());
10254401
PW
3772 CKeyID keyID = keypool.vchPubKey.GetID();
3773 if (!HaveKey(keyID))
5262fde0 3774 throw runtime_error("GetAllReserveKeyHashes(): unknown key in key pool");
10254401 3775 setAddress.insert(keyID);
30ab2c9c
PW
3776 }
3777}
fe4a6550
WL
3778
3779void CWallet::UpdatedTransaction(const uint256 &hashTx)
3780{
3781 {
3782 LOCK(cs_wallet);
3783 // Only notify UI if this transaction is in this wallet
3784 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
3785 if (mi != mapWallet.end())
3786 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
3787 }
3788}
fdbb537d
JG
3789
3790void CWallet::LockCoin(COutPoint& output)
3791{
95691680 3792 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
3793 setLockedCoins.insert(output);
3794}
3795
3796void CWallet::UnlockCoin(COutPoint& output)
3797{
95691680 3798 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
3799 setLockedCoins.erase(output);
3800}
3801
3802void CWallet::UnlockAllCoins()
3803{
95691680 3804 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
3805 setLockedCoins.clear();
3806}
3807
3808bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3809{
95691680 3810 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
3811 COutPoint outpt(hash, n);
3812
3813 return (setLockedCoins.count(outpt) > 0);
3814}
3815
3816void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
3817{
95691680 3818 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
3819 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3820 it != setLockedCoins.end(); it++) {
3821 COutPoint outpt = (*it);
3822 vOutpts.push_back(outpt);
3823 }
3824}
3825
4e6400bc
BM
3826
3827// Note Locking Operations
3828
e935beb8 3829void CWallet::LockNote(const JSOutPoint& output)
4e6400bc
BM
3830{
3831 AssertLockHeld(cs_wallet); // setLockedNotes
3832 setLockedNotes.insert(output);
3833}
3834
e935beb8 3835void CWallet::UnlockNote(const JSOutPoint& output)
4e6400bc
BM
3836{
3837 AssertLockHeld(cs_wallet); // setLockedNotes
3838 setLockedNotes.erase(output);
3839}
3840
3841void CWallet::UnlockAllNotes()
3842{
3843 AssertLockHeld(cs_wallet); // setLockedNotes
3844 setLockedNotes.clear();
3845}
3846
e935beb8 3847bool CWallet::IsLockedNote(const JSOutPoint& outpt) const
4e6400bc
BM
3848{
3849 AssertLockHeld(cs_wallet); // setLockedNotes
4e6400bc
BM
3850
3851 return (setLockedNotes.count(outpt) > 0);
3852}
3853
3854std::vector<JSOutPoint> CWallet::ListLockedNotes()
3855{
3856 AssertLockHeld(cs_wallet); // setLockedNotes
3857 std::vector<JSOutPoint> vOutpts(setLockedNotes.begin(), setLockedNotes.end());
3858 return vOutpts;
3859}
3860
5b40d886 3861/** @} */ // end of Actions
8b59a3d3 3862
3863class CAffectedKeysVisitor : public boost::static_visitor<void> {
3864private:
3865 const CKeyStore &keystore;
3866 std::vector<CKeyID> &vKeys;
3867
3868public:
3869 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
3870
3871 void Process(const CScript &script) {
3872 txnouttype type;
3873 std::vector<CTxDestination> vDest;
3874 int nRequired;
3875 if (ExtractDestinations(script, type, vDest, nRequired)) {
3876 BOOST_FOREACH(const CTxDestination &dest, vDest)
3877 boost::apply_visitor(*this, dest);
3878 }
3879 }
3880
3881 void operator()(const CKeyID &keyId) {
3882 if (keystore.HaveKey(keyId))
3883 vKeys.push_back(keyId);
3884 }
3885
3886 void operator()(const CScriptID &scriptId) {
3887 CScript script;
3888 if (keystore.GetCScript(scriptId, script))
3889 Process(script);
3890 }
3891
3892 void operator()(const CNoDestination &none) {}
3893};
3894
51ed9ec9 3895void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
95691680 3896 AssertLockHeld(cs_wallet); // mapKeyMetadata
434e4273
PW
3897 mapKeyBirth.clear();
3898
3899 // get birth times for keys with metadata
3900 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
3901 if (it->second.nCreateTime)
3902 mapKeyBirth[it->first] = it->second.nCreateTime;
3903
3904 // map in which we'll infer heights of other keys
4c6d41b8 3905 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
434e4273
PW
3906 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3907 std::set<CKeyID> setKeys;
3908 GetKeys(setKeys);
3909 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
3910 if (mapKeyBirth.count(keyid) == 0)
3911 mapKeyFirstBlock[keyid] = pindexMax;
3912 }
3913 setKeys.clear();
3914
3915 // if there are no such keys, we're done
3916 if (mapKeyFirstBlock.empty())
3917 return;
3918
3919 // find first block that affects those keys, if there are any left
3920 std::vector<CKeyID> vAffected;
3921 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3922 // iterate over all wallet transactions...
3923 const CWalletTx &wtx = (*it).second;
145d5be8 3924 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
4c6d41b8 3925 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
434e4273
PW
3926 // ... which are already in a block
3927 int nHeight = blit->second->nHeight;
3928 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
3929 // iterate over all their outputs
8b59a3d3 3930 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
434e4273
PW
3931 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
3932 // ... and all their affected keys
3933 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3934 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3935 rit->second = blit->second;
3936 }
3937 vAffected.clear();
3938 }
3939 }
3940 }
3941
3942 // Extract block timestamps for those keys
3943 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
209377a7 3944 mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
434e4273 3945}
b10e1470
WL
3946
3947bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3948{
8476d5d4
CL
3949 if (boost::get<CNoDestination>(&dest))
3950 return false;
3951
b10e1470
WL
3952 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3953 if (!fFileBacked)
3954 return true;
07444da1 3955 return CWalletDB(strWalletFile).WriteDestData(EncodeDestination(dest), key, value);
b10e1470
WL
3956}
3957
3958bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3959{
3960 if (!mapAddressBook[dest].destdata.erase(key))
3961 return false;
3962 if (!fFileBacked)
3963 return true;
07444da1 3964 return CWalletDB(strWalletFile).EraseDestData(EncodeDestination(dest), key);
b10e1470
WL
3965}
3966
3967bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3968{
3969 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3970 return true;
3971}
3972
3973bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3974{
3975 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3976 if(i != mapAddressBook.end())
3977 {
3978 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3979 if(j != i->second.destdata.end())
3980 {
3981 if(value)
3982 *value = j->second;
3983 return true;
3984 }
3985 }
3986 return false;
3987}
af8297c0
WL
3988
3989CKeyPool::CKeyPool()
3990{
3991 nTime = GetTime();
3992}
3993
3994CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
3995{
3996 nTime = GetTime();
3997 vchPubKey = vchPubKeyIn;
3998}
3999
4000CWalletKey::CWalletKey(int64_t nExpires)
4001{
4002 nTimeCreated = (nExpires ? GetTime() : 0);
4003 nTimeExpires = nExpires;
4004}
0101483f 4005
4b0deb3b 4006int CMerkleTx::SetMerkleBranch(const CBlock& block)
0101483f
WL
4007{
4008 AssertLockHeld(cs_main);
4009 CBlock blockTmp;
4010
4b0deb3b
DK
4011 // Update the tx's hashBlock
4012 hashBlock = block.GetHash();
0101483f 4013
4b0deb3b
DK
4014 // Locate the transaction
4015 for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
4016 if (block.vtx[nIndex] == *(CTransaction*)this)
4017 break;
4018 if (nIndex == (int)block.vtx.size())
4019 {
4020 vMerkleBranch.clear();
4021 nIndex = -1;
5262fde0 4022 LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
4b0deb3b 4023 return 0;
0101483f
WL
4024 }
4025
4b0deb3b
DK
4026 // Fill in merkle branch
4027 vMerkleBranch = block.GetMerkleBranch(nIndex);
4028
0101483f 4029 // Is the tx in a block that's in the main chain
145d5be8 4030 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
0101483f
WL
4031 if (mi == mapBlockIndex.end())
4032 return 0;
4b0deb3b 4033 const CBlockIndex* pindex = (*mi).second;
0101483f
WL
4034 if (!pindex || !chainActive.Contains(pindex))
4035 return 0;
4036
4037 return chainActive.Height() - pindex->nHeight + 1;
4038}
4039
a31e8bad 4040int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const
0101483f 4041{
4f152496 4042 if (hashBlock.IsNull() || nIndex == -1)
0101483f
WL
4043 return 0;
4044 AssertLockHeld(cs_main);
4045
4046 // Find the block it claims to be in
145d5be8 4047 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
0101483f
WL
4048 if (mi == mapBlockIndex.end())
4049 return 0;
4050 CBlockIndex* pindex = (*mi).second;
4051 if (!pindex || !chainActive.Contains(pindex))
4052 return 0;
4053
4054 // Make sure the merkle branch connects to this block
4055 if (!fMerkleVerified)
4056 {
805344dc 4057 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
0101483f
WL
4058 return 0;
4059 fMerkleVerified = true;
4060 }
4061
4062 pindexRet = pindex;
4063 return chainActive.Height() - pindex->nHeight + 1;
4064}
4065
a31e8bad 4066int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
0101483f
WL
4067{
4068 AssertLockHeld(cs_main);
4069 int nResult = GetDepthInMainChainINTERNAL(pindexRet);
805344dc 4070 if (nResult == 0 && !mempool.exists(GetHash()))
0101483f
WL
4071 return -1; // Not in chain, not in mempool
4072
4073 return nResult;
4074}
4075
4076int CMerkleTx::GetBlocksToMaturity() const
4077{
4078 if (!IsCoinBase())
4079 return 0;
4080 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4081}
4082
4083
1371e6f5 4084bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectAbsurdFee)
0101483f
WL
4085{
4086 CValidationState state;
1371e6f5 4087 return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectAbsurdFee);
0101483f
WL
4088}
4089
cb0d208f
S
4090/**
4091 * Find notes in the wallet filtered by payment address, min depth and ability to spend.
4092 * These notes are decrypted and added to the output parameter vector, outEntries.
4093 */
5020a936 4094void CWallet::GetFilteredNotes(std::vector<CSproutNotePlaintextEntry> & outEntries, std::string address, int minDepth, bool ignoreSpent, bool ignoreUnspendable)
a5ac2e25 4095{
bdbe8e85
JG
4096 std::set<PaymentAddress> filterAddresses;
4097
a5ac2e25 4098 if (address.length() > 0) {
e5eab182 4099 filterAddresses.insert(DecodePaymentAddress(address));
a5ac2e25
S
4100 }
4101
bdbe8e85
JG
4102 GetFilteredNotes(outEntries, filterAddresses, minDepth, ignoreSpent, ignoreUnspendable);
4103}
4104
4105/**
4106 * Find notes in the wallet filtered by payment addresses, min depth and ability to spend.
4107 * These notes are decrypted and added to the output parameter vector, outEntries.
4108 */
4109void CWallet::GetFilteredNotes(
5020a936 4110 std::vector<CSproutNotePlaintextEntry>& outEntries,
bdbe8e85
JG
4111 std::set<PaymentAddress>& filterAddresses,
4112 int minDepth,
4113 bool ignoreSpent,
4114 bool ignoreUnspendable)
4115{
a5ac2e25
S
4116 LOCK2(cs_main, cs_wallet);
4117
4118 for (auto & p : mapWallet) {
4119 CWalletTx wtx = p.second;
4120
4121 // Filter the transactions before checking for notes
4122 if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < minDepth) {
4123 continue;
4124 }
4125
005f3ad1 4126 if (wtx.mapSproutNoteData.size() == 0) {
a5ac2e25
S
4127 continue;
4128 }
4129
005f3ad1 4130 for (auto & pair : wtx.mapSproutNoteData) {
a5ac2e25 4131 JSOutPoint jsop = pair.first;
005f3ad1 4132 SproutNoteData nd = pair.second;
e5eab182 4133 SproutPaymentAddress pa = nd.address;
a5ac2e25
S
4134
4135 // skip notes which belong to a different payment address in the wallet
bdbe8e85 4136 if (!(filterAddresses.empty() || filterAddresses.count(pa))) {
a5ac2e25
S
4137 continue;
4138 }
4139
4140 // skip note which has been spent
3b6dd486 4141 if (ignoreSpent && nd.nullifier && IsSproutSpent(*nd.nullifier)) {
a5ac2e25
S
4142 continue;
4143 }
4144
9a2b8ae5 4145 // skip notes which cannot be spent
25d5e80c 4146 if (ignoreUnspendable && !HaveSproutSpendingKey(pa)) {
9a2b8ae5
JG
4147 continue;
4148 }
efb7662d 4149
4e6400bc 4150 // skip locked notes
b87e271a 4151 if (IsLockedNote(jsop)) {
4e6400bc
BM
4152 continue;
4153 }
9a2b8ae5 4154
a5ac2e25
S
4155 int i = jsop.js; // Index into CTransaction.vjoinsplit
4156 int j = jsop.n; // Index into JSDescription.ciphertexts
4157
4158 // Get cached decryptor
4159 ZCNoteDecryption decryptor;
4160 if (!GetNoteDecryptor(pa, decryptor)) {
4161 // Note decryptors are created when the wallet is loaded, so it should always exist
80ed13d5 4162 throw std::runtime_error(strprintf("Could not find note decryptor for payment address %s", EncodePaymentAddress(pa)));
a5ac2e25
S
4163 }
4164
4165 // determine amount of funds in the note
4166 auto hSig = wtx.vjoinsplit[i].h_sig(*pzcashParams, wtx.joinSplitPubKey);
4167 try {
5020a936 4168 SproutNotePlaintext plaintext = SproutNotePlaintext::decrypt(
a5ac2e25
S
4169 decryptor,
4170 wtx.vjoinsplit[i].ciphertexts[j],
4171 wtx.vjoinsplit[i].ephemeralKey,
4172 hSig,
4173 (unsigned char) j);
4174
5020a936 4175 outEntries.push_back(CSproutNotePlaintextEntry{jsop, pa, plaintext});
a5ac2e25 4176
51fde9ea 4177 } catch (const note_decryption_failed &err) {
a5ac2e25 4178 // Couldn't decrypt with this spending key
80ed13d5 4179 throw std::runtime_error(strprintf("Could not decrypt note for payment address %s", EncodePaymentAddress(pa)));
51fde9ea
JG
4180 } catch (const std::exception &exc) {
4181 // Unexpected failure
80ed13d5 4182 throw std::runtime_error(strprintf("Error while decrypting note for payment address %s: %s", EncodePaymentAddress(pa), exc.what()));
a5ac2e25
S
4183 }
4184 }
4185 }
4186}
d72c19a6
S
4187
4188
4189/* Find unspent notes filtered by payment address, min depth and max depth */
4190void CWallet::GetUnspentFilteredNotes(
5020a936 4191 std::vector<CUnspentSproutNotePlaintextEntry>& outEntries,
d72c19a6
S
4192 std::set<PaymentAddress>& filterAddresses,
4193 int minDepth,
4194 int maxDepth,
4195 bool requireSpendingKey)
4196{
4197 LOCK2(cs_main, cs_wallet);
4198
4199 for (auto & p : mapWallet) {
4200 CWalletTx wtx = p.second;
4201
4202 // Filter the transactions before checking for notes
4203 if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < minDepth || wtx.GetDepthInMainChain() > maxDepth) {
4204 continue;
4205 }
4206
005f3ad1 4207 if (wtx.mapSproutNoteData.size() == 0) {
d72c19a6
S
4208 continue;
4209 }
4210
005f3ad1 4211 for (auto & pair : wtx.mapSproutNoteData) {
d72c19a6 4212 JSOutPoint jsop = pair.first;
005f3ad1 4213 SproutNoteData nd = pair.second;
e5eab182 4214 SproutPaymentAddress pa = nd.address;
d72c19a6
S
4215
4216 // skip notes which belong to a different payment address in the wallet
4217 if (!(filterAddresses.empty() || filterAddresses.count(pa))) {
4218 continue;
4219 }
4220
4221 // skip note which has been spent
3b6dd486 4222 if (nd.nullifier && IsSproutSpent(*nd.nullifier)) {
d72c19a6
S
4223 continue;
4224 }
4225
4226 // skip notes where the spending key is not available
25d5e80c 4227 if (requireSpendingKey && !HaveSproutSpendingKey(pa)) {
d72c19a6
S
4228 continue;
4229 }
4230
4231 int i = jsop.js; // Index into CTransaction.vjoinsplit
4232 int j = jsop.n; // Index into JSDescription.ciphertexts
4233
4234 // Get cached decryptor
4235 ZCNoteDecryption decryptor;
4236 if (!GetNoteDecryptor(pa, decryptor)) {
4237 // Note decryptors are created when the wallet is loaded, so it should always exist
80ed13d5 4238 throw std::runtime_error(strprintf("Could not find note decryptor for payment address %s", EncodePaymentAddress(pa)));
d72c19a6
S
4239 }
4240
4241 // determine amount of funds in the note
4242 auto hSig = wtx.vjoinsplit[i].h_sig(*pzcashParams, wtx.joinSplitPubKey);
4243 try {
5020a936 4244 SproutNotePlaintext plaintext = SproutNotePlaintext::decrypt(
d72c19a6
S
4245 decryptor,
4246 wtx.vjoinsplit[i].ciphertexts[j],
4247 wtx.vjoinsplit[i].ephemeralKey,
4248 hSig,
4249 (unsigned char) j);
4250
5020a936 4251 outEntries.push_back(CUnspentSproutNotePlaintextEntry{jsop, pa, plaintext, wtx.GetDepthInMainChain()});
d72c19a6
S
4252
4253 } catch (const note_decryption_failed &err) {
4254 // Couldn't decrypt with this spending key
80ed13d5 4255 throw std::runtime_error(strprintf("Could not decrypt note for payment address %s", EncodePaymentAddress(pa)));
d72c19a6
S
4256 } catch (const std::exception &exc) {
4257 // Unexpected failure
80ed13d5 4258 throw std::runtime_error(strprintf("Error while decrypting note for payment address %s: %s", EncodePaymentAddress(pa), exc.what()));
d72c19a6
S
4259 }
4260 }
4261 }
4262}
4263
This page took 1.006147 seconds and 4 git commands to generate.