]> Git Repo - VerusCoin.git/blame - src/wallet/wallet.cpp
Update to use new API in CCryptoKeyStore and store a viewing key in walletdb.
[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
10254401 8#include "base58.h"
3e1cf9b6 9#include "checkpoints.h"
6a86c24d 10#include "coincontrol.h"
da29ecbc 11#include "consensus/validation.h"
02e67455 12#include "init.h"
8a893c94 13#include "main.h"
0689f46c 14#include "net.h"
e088d65a 15#include "script/script.h"
16#include "script/sign.h"
14f888ca 17#include "timedata.h"
ad49c256
WL
18#include "util.h"
19#include "utilmoneystr.h"
02e67455 20#include "zcash/Note.hpp"
73699cea 21#include "crypter.h"
51ed9ec9 22
d0c4197e
PK
23#include <assert.h>
24
cae686d3 25#include <boost/algorithm/string/replace.hpp>
2bb1c877 26#include <boost/filesystem.hpp>
ad49c256 27#include <boost/thread.hpp>
e8ef3da7
WL
28
29using namespace std;
c1c45943 30using namespace libzcash;
e8ef3da7 31
5b40d886
MF
32/**
33 * Settings
34 */
c6cb21d1 35CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
aa279d61 36CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
77ed59df 37unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
1bbca249 38bool bSpendZeroConfChange = true;
c1c9d5b4 39bool fSendFreeTransactions = false;
ed3e5e46 40bool fPayAtLeastCustomFee = true;
e8ef3da7 41
7e6d23b1
CD
42/**
43 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
5b40d886
MF
44 * Override with -mintxfee
45 */
9b1627d1 46CFeeRate CWallet::minTxFee = CFeeRate(1000);
13fc83c7 47
5b40d886
MF
48/** @defgroup mapWallet
49 *
50 * @{
51 */
e8ef3da7 52
d650f96d
CM
53struct CompareValueOnly
54{
a372168e
MF
55 bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
56 const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
d650f96d
CM
57 {
58 return t1.first < t2.first;
59 }
60};
61
02e67455
JG
62std::string JSOutPoint::ToString() const
63{
64 return strprintf("JSOutPoint(%s, %d, %d)", hash.ToString().substr(0,10), js, n);
65}
66
ad49c256
WL
67std::string COutput::ToString() const
68{
805344dc 69 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
ad49c256
WL
70}
71
93a18a36
GA
72const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
73{
74 LOCK(cs_wallet);
75 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
76 if (it == mapWallet.end())
77 return NULL;
78 return &(it->second);
79}
80
c1c45943
S
81// Generate a new spending key and return its public payment address
82CZCPaymentAddress CWallet::GenerateNewZKey()
83{
84 AssertLockHeld(cs_wallet); // mapZKeyMetadata
85 auto k = SpendingKey::random();
86 auto addr = k.address();
87
88 // Check for collision, even though it is unlikely to ever occur
89 if (CCryptoKeyStore::HaveSpendingKey(addr))
0feffd14 90 throw std::runtime_error("CWallet::GenerateNewZKey(): Collision detected");
c1c45943
S
91
92 // Create new metadata
93 int64_t nCreationTime = GetTime();
94 mapZKeyMetadata[addr] = CKeyMetadata(nCreationTime);
95
96 CZCPaymentAddress pubaddr(addr);
97 if (!AddZKey(k))
0feffd14 98 throw std::runtime_error("CWallet::GenerateNewZKey(): AddZKey failed");
c1c45943
S
99 return pubaddr;
100}
101
102// Add spending key to keystore and persist to disk
103bool CWallet::AddZKey(const libzcash::SpendingKey &key)
104{
105 AssertLockHeld(cs_wallet); // mapZKeyMetadata
106 auto addr = key.address();
107
108 if (!CCryptoKeyStore::AddSpendingKey(key))
109 return false;
110
111 if (!fFileBacked)
112 return true;
113
114 if (!IsCrypted()) {
115 return CWalletDB(strWalletFile).WriteZKey(addr,
116 key,
117 mapZKeyMetadata[addr]);
118 }
119 return true;
120}
121
fd61d6f5 122CPubKey CWallet::GenerateNewKey()
9976cf07 123{
95691680 124 AssertLockHeld(cs_wallet); // mapKeyMetadata
439e1497 125 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
38067c18 126
dfa23b94
PW
127 CKey secret;
128 secret.MakeNewKey(fCompressed);
38067c18
PW
129
130 // Compressed public keys were introduced in version 0.6.0
131 if (fCompressed)
439e1497 132 SetMinVersion(FEATURE_COMPRPUBKEY);
38067c18 133
dfa23b94 134 CPubKey pubkey = secret.GetPubKey();
d0c41a73 135 assert(secret.VerifyPubKey(pubkey));
4addb2c0
PW
136
137 // Create new metadata
51ed9ec9 138 int64_t nCreationTime = GetTime();
4addb2c0
PW
139 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
140 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
141 nTimeFirstKey = nCreationTime;
142
dfa23b94 143 if (!AddKeyPubKey(secret, pubkey))
5262fde0 144 throw std::runtime_error("CWallet::GenerateNewKey(): AddKey failed");
dfa23b94 145 return pubkey;
9976cf07 146}
e8ef3da7 147
4addb2c0 148bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
e8ef3da7 149{
95691680 150 AssertLockHeld(cs_wallet); // mapKeyMetadata
dfa23b94 151 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
acd65016 152 return false;
ccca27a7
CL
153
154 // check if we need to remove from watch-only
155 CScript script;
156 script = GetScriptForDestination(pubkey.GetID());
157 if (HaveWatchOnly(script))
158 RemoveWatchOnly(script);
159
e8ef3da7
WL
160 if (!fFileBacked)
161 return true;
dfa23b94 162 if (!IsCrypted()) {
3869fb89
JG
163 return CWalletDB(strWalletFile).WriteKey(pubkey,
164 secret.GetPrivKey(),
4addb2c0 165 mapKeyMetadata[pubkey.GetID()]);
dfa23b94 166 }
84c3c2eb 167 return true;
4e87d341
MC
168}
169
3869fb89 170bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
4addb2c0 171 const vector<unsigned char> &vchCryptedSecret)
4e87d341 172{
73699cea 173
4e87d341
MC
174 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
175 return false;
176 if (!fFileBacked)
177 return true;
96f34cd5 178 {
f8dcd5ca 179 LOCK(cs_wallet);
96f34cd5 180 if (pwalletdbEncryption)
3869fb89
JG
181 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
182 vchCryptedSecret,
4addb2c0 183 mapKeyMetadata[vchPubKey.GetID()]);
96f34cd5 184 else
3869fb89
JG
185 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
186 vchCryptedSecret,
4addb2c0 187 mapKeyMetadata[vchPubKey.GetID()]);
96f34cd5 188 }
0767e691 189 return false;
4e87d341
MC
190}
191
73699cea
S
192
193bool CWallet::AddCryptedSpendingKey(const libzcash::PaymentAddress &address,
2aa9c025 194 const libzcash::ViewingKey &vk,
73699cea
S
195 const std::vector<unsigned char> &vchCryptedSecret)
196{
2aa9c025 197 if (!CCryptoKeyStore::AddCryptedSpendingKey(address, vk, vchCryptedSecret))
73699cea
S
198 return false;
199 if (!fFileBacked)
200 return true;
201 {
202 LOCK(cs_wallet);
203 if (pwalletdbEncryption)
204 return pwalletdbEncryption->WriteCryptedZKey(address,
2aa9c025 205 vk,
73699cea
S
206 vchCryptedSecret,
207 mapZKeyMetadata[address]);
208 else
209 return CWalletDB(strWalletFile).WriteCryptedZKey(address,
2aa9c025 210 vk,
73699cea
S
211 vchCryptedSecret,
212 mapZKeyMetadata[address]);
213 }
214 return false;
215}
216
4addb2c0
PW
217bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
218{
95691680 219 AssertLockHeld(cs_wallet); // mapKeyMetadata
4addb2c0
PW
220 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
221 nTimeFirstKey = meta.nCreateTime;
222
223 mapKeyMetadata[pubkey.GetID()] = meta;
224 return true;
225}
226
c1c45943
S
227bool CWallet::LoadZKeyMetadata(const PaymentAddress &addr, const CKeyMetadata &meta)
228{
229 AssertLockHeld(cs_wallet); // mapZKeyMetadata
230 mapZKeyMetadata[addr] = meta;
231 return true;
232}
233
2f15e86a
GA
234bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
235{
236 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
237}
238
2aa9c025 239bool CWallet::LoadCryptedZKey(const libzcash::PaymentAddress &addr, const libzcash::ViewingKey &vk, const std::vector<unsigned char> &vchCryptedSecret)
73699cea 240{
2aa9c025 241 return CCryptoKeyStore::AddCryptedSpendingKey(addr, vk, vchCryptedSecret);
73699cea
S
242}
243
c1c45943
S
244bool CWallet::LoadZKey(const libzcash::SpendingKey &key)
245{
246 return CCryptoKeyStore::AddSpendingKey(key);
247}
248
922e8e29 249bool CWallet::AddCScript(const CScript& redeemScript)
e679ec96 250{
922e8e29 251 if (!CCryptoKeyStore::AddCScript(redeemScript))
e679ec96
GA
252 return false;
253 if (!fFileBacked)
254 return true;
922e8e29 255 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
e679ec96
GA
256}
257
18116b06
WL
258bool CWallet::LoadCScript(const CScript& redeemScript)
259{
260 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
261 * that never can be redeemed. However, old wallets may still contain
262 * these. Do not add them to the wallet and warn. */
263 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
264 {
066e2a14 265 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
18116b06
WL
266 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",
267 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
268 return true;
269 }
270
271 return CCryptoKeyStore::AddCScript(redeemScript);
272}
273
d5087d1b 274bool CWallet::AddWatchOnly(const CScript &dest)
c8988460
PW
275{
276 if (!CCryptoKeyStore::AddWatchOnly(dest))
277 return false;
278 nTimeFirstKey = 1; // No birthday information for watch-only keys.
939ed973 279 NotifyWatchonlyChanged(true);
c8988460
PW
280 if (!fFileBacked)
281 return true;
282 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
283}
284
ccca27a7
CL
285bool CWallet::RemoveWatchOnly(const CScript &dest)
286{
287 AssertLockHeld(cs_wallet);
288 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
289 return false;
290 if (!HaveWatchOnly())
291 NotifyWatchonlyChanged(false);
292 if (fFileBacked)
293 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
294 return false;
295
296 return true;
297}
298
d5087d1b 299bool CWallet::LoadWatchOnly(const CScript &dest)
c8988460 300{
c8988460
PW
301 return CCryptoKeyStore::AddWatchOnly(dest);
302}
303
94f778bd 304bool CWallet::Unlock(const SecureString& strWalletPassphrase)
4e87d341 305{
6cc4a62c
GA
306 CCrypter crypter;
307 CKeyingMaterial vMasterKey;
4e87d341 308
f8dcd5ca
PW
309 {
310 LOCK(cs_wallet);
4e87d341
MC
311 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
312 {
313 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
314 return false;
315 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
92f2c1fe 316 continue; // try another master key
4e87d341
MC
317 if (CCryptoKeyStore::Unlock(vMasterKey))
318 return true;
319 }
f8dcd5ca 320 }
4e87d341
MC
321 return false;
322}
323
94f778bd 324bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
4e87d341 325{
6cc4a62c 326 bool fWasLocked = IsLocked();
4e87d341 327
6cc4a62c 328 {
f8dcd5ca 329 LOCK(cs_wallet);
4e87d341
MC
330 Lock();
331
332 CCrypter crypter;
333 CKeyingMaterial vMasterKey;
334 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
335 {
336 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
337 return false;
6cc4a62c 338 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
4e87d341
MC
339 return false;
340 if (CCryptoKeyStore::Unlock(vMasterKey))
341 {
51ed9ec9 342 int64_t nStartTime = GetTimeMillis();
ddebdd9a
MC
343 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
344 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
345
346 nStartTime = GetTimeMillis();
347 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
348 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
349
350 if (pMasterKey.second.nDeriveIterations < 25000)
351 pMasterKey.second.nDeriveIterations = 25000;
352
881a85a2 353 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
ddebdd9a 354
4e87d341
MC
355 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
356 return false;
357 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
358 return false;
359 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
360 if (fWasLocked)
361 Lock();
362 return true;
363 }
364 }
365 }
6cc4a62c 366
4e87d341
MC
367 return false;
368}
369
de42390f
JG
370void CWallet::ChainTip(const CBlockIndex *pindex, const CBlock *pblock,
371 ZCIncrementalMerkleTree tree, bool added)
769e031c
JG
372{
373 if (added) {
de42390f 374 IncrementNoteWitnesses(pindex, pblock, tree);
769e031c
JG
375 } else {
376 DecrementNoteWitnesses();
377 }
378}
379
ed6d0b5f
PW
380void CWallet::SetBestChain(const CBlockLocator& loc)
381{
382 CWalletDB walletdb(strWalletFile);
383 walletdb.WriteBestBlock(loc);
384}
7414733b 385
439e1497 386bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
0b807a41 387{
ca4cf5cf 388 LOCK(cs_wallet); // nWalletVersion
0b807a41
PW
389 if (nWalletVersion >= nVersion)
390 return true;
391
439e1497
PW
392 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
393 if (fExplicit && nVersion > nWalletMaxVersion)
394 nVersion = FEATURE_LATEST;
395
0b807a41
PW
396 nWalletVersion = nVersion;
397
439e1497
PW
398 if (nVersion > nWalletMaxVersion)
399 nWalletMaxVersion = nVersion;
400
0b807a41
PW
401 if (fFileBacked)
402 {
403 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
0b807a41
PW
404 if (nWalletVersion > 40000)
405 pwalletdb->WriteMinVersion(nWalletVersion);
406 if (!pwalletdbIn)
407 delete pwalletdb;
408 }
409
410 return true;
411}
412
439e1497
PW
413bool CWallet::SetMaxVersion(int nVersion)
414{
ca4cf5cf 415 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
439e1497
PW
416 // cannot downgrade below current version
417 if (nWalletVersion > nVersion)
418 return false;
419
420 nWalletMaxVersion = nVersion;
421
422 return true;
423}
424
3015e0bc 425set<uint256> CWallet::GetConflicts(const uint256& txid) const
731b89b8
GA
426{
427 set<uint256> result;
428 AssertLockHeld(cs_wallet);
429
430 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
431 if (it == mapWallet.end())
432 return result;
433 const CWalletTx& wtx = it->second;
434
93a18a36 435 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
731b89b8
GA
436
437 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
438 {
93a18a36
GA
439 if (mapTxSpends.count(txin.prevout) <= 1)
440 continue; // No conflict if zero or one spends
441 range = mapTxSpends.equal_range(txin.prevout);
442 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
3015e0bc 443 result.insert(it->second);
731b89b8 444 }
0f106047
JG
445
446 std::pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range_n;
447
448 for (const JSDescription& jsdesc : wtx.vjoinsplit) {
449 for (const uint256& nullifier : jsdesc.nullifiers) {
450 if (mapTxNullifiers.count(nullifier) <= 1) {
451 continue; // No conflict if zero or one spends
452 }
453 range_n = mapTxNullifiers.equal_range(nullifier);
454 for (TxNullifiers::const_iterator it = range_n.first; it != range_n.second; ++it) {
455 result.insert(it->second);
456 }
457 }
458 }
731b89b8
GA
459 return result;
460}
461
2bb1c877
JS
462void CWallet::Flush(bool shutdown)
463{
464 bitdb.Flush(shutdown);
465}
466
341e2385 467bool CWallet::Verify(const string& walletFile, string& warningString, string& errorString)
2bb1c877
JS
468{
469 if (!bitdb.Open(GetDataDir()))
470 {
471 // try moving the database env out of the way
472 boost::filesystem::path pathDatabase = GetDataDir() / "database";
473 boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
474 try {
475 boost::filesystem::rename(pathDatabase, pathDatabaseBak);
476 LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
477 } catch (const boost::filesystem::filesystem_error&) {
478 // failure is ok (well, not really, but it's not worse than what we started with)
479 }
480
481 // try again
482 if (!bitdb.Open(GetDataDir())) {
483 // if it still fails, it probably means we can't even create the database env
484 string msg = strprintf(_("Error initializing wallet database environment %s!"), GetDataDir());
485 errorString += msg;
486 return true;
487 }
488 }
489
490 if (GetBoolArg("-salvagewallet", false))
491 {
492 // Recover readable keypairs:
493 if (!CWalletDB::Recover(bitdb, walletFile, true))
494 return false;
495 }
496
497 if (boost::filesystem::exists(GetDataDir() / walletFile))
498 {
499 CDBEnv::VerifyResult r = bitdb.Verify(walletFile, CWalletDB::Recover);
500 if (r == CDBEnv::RECOVER_OK)
501 {
502 warningString += strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
503 " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
504 " your balance or transactions are incorrect you should"
505 " restore from a backup."), GetDataDir());
506 }
507 if (r == CDBEnv::RECOVER_FAIL)
508 errorString += _("wallet.dat corrupt, salvage failed");
509 }
510
511 return true;
512}
513
0f106047
JG
514template <class T>
515void CWallet::SyncMetaData(pair<typename TxSpendMap<T>::iterator, typename TxSpendMap<T>::iterator> range)
731b89b8
GA
516{
517 // We want all the wallet transactions in range to have the same metadata as
518 // the oldest (smallest nOrderPos).
519 // So: find smallest nOrderPos:
520
521 int nMinOrderPos = std::numeric_limits<int>::max();
522 const CWalletTx* copyFrom = NULL;
0f106047 523 for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
731b89b8
GA
524 {
525 const uint256& hash = it->second;
526 int n = mapWallet[hash].nOrderPos;
527 if (n < nMinOrderPos)
528 {
529 nMinOrderPos = n;
530 copyFrom = &mapWallet[hash];
531 }
532 }
533 // Now copy data from copyFrom to rest:
0f106047 534 for (typename TxSpendMap<T>::iterator it = range.first; it != range.second; ++it)
731b89b8
GA
535 {
536 const uint256& hash = it->second;
537 CWalletTx* copyTo = &mapWallet[hash];
538 if (copyFrom == copyTo) continue;
539 copyTo->mapValue = copyFrom->mapValue;
c3a7307a
JG
540 // mapNoteData not copied on purpose
541 // (it is always set correctly for each CWalletTx)
731b89b8
GA
542 copyTo->vOrderForm = copyFrom->vOrderForm;
543 // fTimeReceivedIsTxTime not copied on purpose
544 // nTimeReceived not copied on purpose
545 copyTo->nTimeSmart = copyFrom->nTimeSmart;
546 copyTo->fFromMe = copyFrom->fFromMe;
547 copyTo->strFromAccount = copyFrom->strFromAccount;
731b89b8
GA
548 // nOrderPos not copied on purpose
549 // cached members not copied on purpose
550 }
551}
552
5b40d886
MF
553/**
554 * Outpoint is spent if any non-conflicted transaction
555 * spends it:
556 */
93a18a36 557bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
731b89b8 558{
93a18a36
GA
559 const COutPoint outpoint(hash, n);
560 pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
561 range = mapTxSpends.equal_range(outpoint);
731b89b8 562
93a18a36 563 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
731b89b8 564 {
93a18a36
GA
565 const uint256& wtxid = it->second;
566 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
567 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
568 return true; // Spent
731b89b8 569 }
93a18a36
GA
570 return false;
571}
572
0f106047
JG
573/**
574 * Note is spent if any non-conflicted transaction
575 * spends it:
576 */
577bool CWallet::IsSpent(const uint256& nullifier) const
578{
579 pair<TxNullifiers::const_iterator, TxNullifiers::const_iterator> range;
580 range = mapTxNullifiers.equal_range(nullifier);
581
582 for (TxNullifiers::const_iterator it = range.first; it != range.second; ++it) {
583 const uint256& wtxid = it->second;
584 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
585 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) {
586 return true; // Spent
587 }
588 }
589 return false;
590}
591
93a18a36
GA
592void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
593{
594 mapTxSpends.insert(make_pair(outpoint, wtxid));
595
596 pair<TxSpends::iterator, TxSpends::iterator> range;
597 range = mapTxSpends.equal_range(outpoint);
0f106047 598 SyncMetaData<COutPoint>(range);
93a18a36
GA
599}
600
0f106047
JG
601void CWallet::AddToSpends(const uint256& nullifier, const uint256& wtxid)
602{
603 mapTxNullifiers.insert(make_pair(nullifier, wtxid));
604
605 pair<TxNullifiers::iterator, TxNullifiers::iterator> range;
606 range = mapTxNullifiers.equal_range(nullifier);
607 SyncMetaData<uint256>(range);
608}
93a18a36
GA
609
610void CWallet::AddToSpends(const uint256& wtxid)
611{
612 assert(mapWallet.count(wtxid));
613 CWalletTx& thisTx = mapWallet[wtxid];
614 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
615 return;
616
0f106047 617 for (const CTxIn& txin : thisTx.vin) {
93a18a36 618 AddToSpends(txin.prevout, wtxid);
0f106047
JG
619 }
620 for (const JSDescription& jsdesc : thisTx.vjoinsplit) {
621 for (const uint256& nullifier : jsdesc.nullifiers) {
622 AddToSpends(nullifier, wtxid);
623 }
624 }
731b89b8
GA
625}
626
be74c80d
JG
627void CWallet::IncrementNoteWitnesses(const CBlockIndex* pindex,
628 const CBlock* pblockIn,
de42390f 629 ZCIncrementalMerkleTree tree)
be74c80d
JG
630{
631 {
632 LOCK(cs_wallet);
633 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
634 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
635 CNoteData* nd = &(item.second);
32a103aa
JG
636 // Check the validity of the cache
637 assert(nWitnessCacheSize >= nd->witnesses.size());
be74c80d
JG
638 // Copy the witness for the previous block if we have one
639 if (nd->witnesses.size() > 0) {
640 nd->witnesses.push_front(nd->witnesses.front());
641 }
642 if (nd->witnesses.size() > WITNESS_CACHE_SIZE) {
643 nd->witnesses.pop_back();
644 }
645 }
646 }
647
648 const CBlock* pblock {pblockIn};
649 CBlock block;
650 if (!pblock) {
651 ReadBlockFromDisk(block, pindex);
652 pblock = &block;
653 }
654
be74c80d 655 for (const CTransaction& tx : pblock->vtx) {
fa511e10 656 auto hash = tx.GetHash();
be74c80d
JG
657 bool txIsOurs = mapWallet.count(hash);
658 for (size_t i = 0; i < tx.vjoinsplit.size(); i++) {
659 const JSDescription& jsdesc = tx.vjoinsplit[i];
660 for (uint8_t j = 0; j < jsdesc.commitments.size(); j++) {
661 const uint256& note_commitment = jsdesc.commitments[j];
662 tree.append(note_commitment);
663
664 // Increment existing witnesses
665 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
666 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
667 CNoteData* nd = &(item.second);
668 if (nd->witnesses.size() > 0) {
669 nd->witnesses.front().append(note_commitment);
670 }
671 }
672 }
673
674 // If this is our note, witness it
675 if (txIsOurs) {
676 JSOutPoint jsoutpt {hash, i, j};
677 if (mapWallet[hash].mapNoteData.count(jsoutpt)) {
678 mapWallet[hash].mapNoteData[jsoutpt].witnesses.push_front(
679 tree.witness());
680 }
681 }
682 }
683 }
684 }
4086e5ce
JG
685 if (nWitnessCacheSize < WITNESS_CACHE_SIZE) {
686 nWitnessCacheSize += 1;
be74c80d
JG
687 }
688 if (fFileBacked) {
56fb1bb8 689 WriteWitnessCache();
be74c80d
JG
690 }
691 }
692}
693
694void CWallet::DecrementNoteWitnesses()
695{
696 {
697 LOCK(cs_wallet);
698 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
699 for (mapNoteData_t::value_type& item : wtxItem.second.mapNoteData) {
700 CNoteData* nd = &(item.second);
701 if (nd->witnesses.size() > 0) {
702 nd->witnesses.pop_front();
703 }
704 }
705 }
4086e5ce
JG
706 nWitnessCacheSize -= 1;
707 // TODO: If nWitnessCache is zero, we need to regenerate the caches (#1302)
708 assert(nWitnessCacheSize > 0);
be74c80d 709 if (fFileBacked) {
56fb1bb8 710 WriteWitnessCache();
be74c80d
JG
711 }
712 }
713}
714
56fb1bb8
JG
715void CWallet::WriteWitnessCache() {
716 CWalletDB walletdb(strWalletFile);
717 if (!walletdb.TxnBegin()) {
718 // This needs to be done atomically, so don't do it at all
719 LogPrintf("WriteWitnessCache(): Couldn't start atomic write\n");
720 return;
721 }
722 for (std::pair<const uint256, CWalletTx>& wtxItem : mapWallet) {
723 if (!walletdb.WriteTx(wtxItem.first, wtxItem.second)) {
724 LogPrintf("WriteWitnessCache(): Failed to write CWalletTx, aborting atomic write\n");
725 walletdb.TxnAbort();
726 return;
727 }
728 }
729 if (!walletdb.WriteWitnessCacheSize(nWitnessCacheSize)) {
730 LogPrintf("WriteWitnessCache(): Failed to write nWitnessCacheSize, aborting atomic write\n");
731 walletdb.TxnAbort();
732 return;
733 }
734 if (!walletdb.TxnCommit()) {
735 // Couldn't commit all to db, but in-memory state is fine
736 LogPrintf("WriteWitnessCache(): Couldn't commit atomic write\n");
737 return;
738 }
739}
740
94f778bd 741bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
4e87d341 742{
6cc4a62c
GA
743 if (IsCrypted())
744 return false;
4e87d341 745
6cc4a62c
GA
746 CKeyingMaterial vMasterKey;
747 RandAddSeedPerfmon();
4e87d341 748
6cc4a62c 749 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
65e3a1e7 750 GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
4e87d341 751
6cc4a62c 752 CMasterKey kMasterKey;
6cc4a62c 753 RandAddSeedPerfmon();
001a53d7 754
6cc4a62c 755 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
65e3a1e7 756 GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
4e87d341 757
6cc4a62c 758 CCrypter crypter;
51ed9ec9 759 int64_t nStartTime = GetTimeMillis();
6cc4a62c
GA
760 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
761 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
ddebdd9a 762
6cc4a62c
GA
763 nStartTime = GetTimeMillis();
764 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
765 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
ddebdd9a 766
6cc4a62c
GA
767 if (kMasterKey.nDeriveIterations < 25000)
768 kMasterKey.nDeriveIterations = 25000;
ddebdd9a 769
881a85a2 770 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
ddebdd9a 771
6cc4a62c
GA
772 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
773 return false;
774 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
775 return false;
4e87d341 776
6cc4a62c 777 {
f8dcd5ca 778 LOCK(cs_wallet);
4e87d341
MC
779 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
780 if (fFileBacked)
781 {
870da77d 782 assert(!pwalletdbEncryption);
96f34cd5 783 pwalletdbEncryption = new CWalletDB(strWalletFile);
870da77d
PK
784 if (!pwalletdbEncryption->TxnBegin()) {
785 delete pwalletdbEncryption;
786 pwalletdbEncryption = NULL;
0fb78eae 787 return false;
870da77d 788 }
96f34cd5 789 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
4e87d341
MC
790 }
791
792 if (!EncryptKeys(vMasterKey))
96f34cd5 793 {
870da77d 794 if (fFileBacked) {
96f34cd5 795 pwalletdbEncryption->TxnAbort();
870da77d
PK
796 delete pwalletdbEncryption;
797 }
798 // We now probably have half of our keys encrypted in memory, and half not...
7e6d23b1 799 // die and let the user reload the unencrypted wallet.
d0c4197e 800 assert(false);
96f34cd5
MC
801 }
802
0b807a41 803 // Encryption was introduced in version 0.4.0
439e1497 804 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
0b807a41 805
96f34cd5
MC
806 if (fFileBacked)
807 {
870da77d
PK
808 if (!pwalletdbEncryption->TxnCommit()) {
809 delete pwalletdbEncryption;
5b40d886 810 // We now have keys encrypted in memory, but not on disk...
7e6d23b1 811 // die to avoid confusion and let the user reload the unencrypted wallet.
d0c4197e 812 assert(false);
870da77d 813 }
96f34cd5 814
fcfd7ff8 815 delete pwalletdbEncryption;
96f34cd5
MC
816 pwalletdbEncryption = NULL;
817 }
4e87d341 818
37971fcc
GA
819 Lock();
820 Unlock(strWalletPassphrase);
821 NewKeyPool();
4e87d341 822 Lock();
6cc4a62c 823
d764d916
GA
824 // Need to completely rewrite the wallet file; if we don't, bdb might keep
825 // bits of the unencrypted private key in slack space in the database file.
b2d3b2d6 826 CDB::Rewrite(strWalletFile);
fe4a6550 827
d764d916 828 }
ab1b288f 829 NotifyStatusChanged(this);
9e9869d0 830
4e87d341 831 return true;
e8ef3da7
WL
832}
833
51ed9ec9 834int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
da7b8c12 835{
95691680 836 AssertLockHeld(cs_wallet); // nOrderPosNext
51ed9ec9 837 int64_t nRet = nOrderPosNext++;
4291e8fe
PW
838 if (pwalletdb) {
839 pwalletdb->WriteOrderPosNext(nOrderPosNext);
840 } else {
841 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
842 }
da7b8c12
LD
843 return nRet;
844}
845
ddb709e9 846CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
c3f95ef1 847{
95691680 848 AssertLockHeld(cs_wallet); // mapWallet
c3f95ef1
LD
849 CWalletDB walletdb(strWalletFile);
850
851 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
852 TxItems txOrdered;
853
854 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
855 // would make this much faster for applications that do this a lot.
856 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
857 {
858 CWalletTx* wtx = &((*it).second);
859 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
860 }
ddb709e9 861 acentries.clear();
c3f95ef1
LD
862 walletdb.ListAccountCreditDebit(strAccount, acentries);
863 BOOST_FOREACH(CAccountingEntry& entry, acentries)
864 {
865 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
866 }
867
868 return txOrdered;
869}
870
95d888a6
PW
871void CWallet::MarkDirty()
872{
95d888a6 873 {
f8dcd5ca 874 LOCK(cs_wallet);
95d888a6
PW
875 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
876 item.second.MarkDirty();
877 }
878}
879
8db7e25c
JG
880void CWallet::UpdateNullifierNoteMap(const CWalletTx& wtx)
881{
882 {
883 LOCK(cs_wallet);
884 for (const mapNoteData_t::value_type& item : wtx.mapNoteData) {
ad20f214 885 mapNullifiersToNotes[item.second.nullifier] = item.first;
8db7e25c
JG
886 }
887 }
888}
889
44bc988e 890bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb)
e8ef3da7 891{
805344dc 892 uint256 hash = wtxIn.GetHash();
731b89b8
GA
893
894 if (fFromLoadWallet)
895 {
896 mapWallet[hash] = wtxIn;
09ec3af1 897 mapWallet[hash].BindWallet(this);
8db7e25c 898 UpdateNullifierNoteMap(mapWallet[hash]);
93a18a36 899 AddToSpends(hash);
731b89b8
GA
900 }
901 else
e8ef3da7 902 {
f8dcd5ca 903 LOCK(cs_wallet);
e8ef3da7
WL
904 // Inserts only if not already there, returns tx inserted or tx found
905 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
906 CWalletTx& wtx = (*ret.first).second;
4c6e2295 907 wtx.BindWallet(this);
8db7e25c 908 UpdateNullifierNoteMap(wtx);
e8ef3da7
WL
909 bool fInsertedNew = ret.second;
910 if (fInsertedNew)
9c7722b7 911 {
e8ef3da7 912 wtx.nTimeReceived = GetAdjustedTime();
44bc988e 913 wtx.nOrderPos = IncOrderPosNext(pwalletdb);
c3f95ef1
LD
914
915 wtx.nTimeSmart = wtx.nTimeReceived;
4f152496 916 if (!wtxIn.hashBlock.IsNull())
c3f95ef1
LD
917 {
918 if (mapBlockIndex.count(wtxIn.hashBlock))
919 {
209377a7 920 int64_t latestNow = wtx.nTimeReceived;
921 int64_t latestEntry = 0;
c3f95ef1
LD
922 {
923 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
51ed9ec9 924 int64_t latestTolerated = latestNow + 300;
ddb709e9
LD
925 std::list<CAccountingEntry> acentries;
926 TxItems txOrdered = OrderedTxItems(acentries);
c3f95ef1
LD
927 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
928 {
929 CWalletTx *const pwtx = (*it).second.first;
930 if (pwtx == &wtx)
931 continue;
932 CAccountingEntry *const pacentry = (*it).second.second;
51ed9ec9 933 int64_t nSmartTime;
c3f95ef1
LD
934 if (pwtx)
935 {
936 nSmartTime = pwtx->nTimeSmart;
937 if (!nSmartTime)
938 nSmartTime = pwtx->nTimeReceived;
939 }
940 else
941 nSmartTime = pacentry->nTime;
942 if (nSmartTime <= latestTolerated)
943 {
944 latestEntry = nSmartTime;
945 if (nSmartTime > latestNow)
946 latestNow = nSmartTime;
947 break;
948 }
949 }
950 }
951
209377a7 952 int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
c3f95ef1
LD
953 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
954 }
955 else
5262fde0 956 LogPrintf("AddToWallet(): found %s in block %s not in index\n",
805344dc 957 wtxIn.GetHash().ToString(),
7d9d134b 958 wtxIn.hashBlock.ToString());
c3f95ef1 959 }
93a18a36 960 AddToSpends(hash);
9c7722b7 961 }
e8ef3da7
WL
962
963 bool fUpdated = false;
964 if (!fInsertedNew)
965 {
966 // Merge
4f152496 967 if (!wtxIn.hashBlock.IsNull() && wtxIn.hashBlock != wtx.hashBlock)
e8ef3da7
WL
968 {
969 wtx.hashBlock = wtxIn.hashBlock;
970 fUpdated = true;
971 }
972 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
973 {
974 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
975 wtx.nIndex = wtxIn.nIndex;
976 fUpdated = true;
977 }
ac1c9435 978 if (UpdatedNoteData(wtxIn, wtx)) {
c3a7307a
JG
979 fUpdated = true;
980 }
e8ef3da7
WL
981 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
982 {
983 wtx.fFromMe = wtxIn.fFromMe;
984 fUpdated = true;
985 }
e8ef3da7
WL
986 }
987
988 //// debug print
805344dc 989 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
e8ef3da7
WL
990
991 // Write to disk
992 if (fInsertedNew || fUpdated)
44bc988e 993 if (!wtx.WriteToDisk(pwalletdb))
e8ef3da7 994 return false;
ee4b170c 995
93a18a36
GA
996 // Break debit/credit balance caches:
997 wtx.MarkDirty();
e8ef3da7 998
fe4a6550
WL
999 // Notify UI of new or updated transaction
1000 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
cae686d3 1001
1002 // notify an external script when a wallet transaction comes in or is updated
1003 std::string strCmd = GetArg("-walletnotify", "");
1004
1005 if ( !strCmd.empty())
1006 {
805344dc 1007 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
cae686d3 1008 boost::thread t(runCommand, strCmd); // thread runs free
1009 }
1010
fe4a6550 1011 }
e8ef3da7
WL
1012 return true;
1013}
1014
ac1c9435
JG
1015bool CWallet::UpdatedNoteData(const CWalletTx& wtxIn, CWalletTx& wtx)
1016{
1017 if (wtxIn.mapNoteData.empty() || wtxIn.mapNoteData == wtx.mapNoteData) {
1018 return false;
1019 }
1020 auto tmp = wtxIn.mapNoteData;
1021 // Ensure we keep any cached witnesses we may already have
1022 for (const std::pair<JSOutPoint, CNoteData> nd : wtx.mapNoteData) {
1023 if (tmp.count(nd.first) && nd.second.witnesses.size() > 0) {
1024 tmp.at(nd.first).witnesses.assign(
1025 nd.second.witnesses.cbegin(), nd.second.witnesses.cend());
1026 }
1027 }
1028 // Now copy over the updated note data
1029 wtx.mapNoteData = tmp;
1030 return true;
1031}
1032
5b40d886
MF
1033/**
1034 * Add a transaction to the wallet, or update it.
1035 * pblock is optional, but should be provided if the transaction is known to be in a block.
1036 * If fUpdate is true, existing transactions will be updated.
1037 */
d38da59b 1038bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
e8ef3da7 1039{
e8ef3da7 1040 {
53d56881 1041 AssertLockHeld(cs_wallet);
805344dc 1042 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
6cc4a62c 1043 if (fExisted && !fUpdate) return false;
c3a7307a
JG
1044 auto noteData = FindMyNotes(tx);
1045 if (fExisted || IsMine(tx) || IsFromMe(tx) || noteData.size() > 0)
6cc4a62c
GA
1046 {
1047 CWalletTx wtx(this,tx);
44bc988e 1048
be74c80d 1049 if (noteData.size() > 0) {
c3a7307a 1050 wtx.SetNoteData(noteData);
be74c80d 1051 }
c3a7307a 1052
6cc4a62c
GA
1053 // Get merkle branch if transaction was found in a block
1054 if (pblock)
4b0deb3b 1055 wtx.SetMerkleBranch(*pblock);
44bc988e
CL
1056
1057 // Do not flush the wallet here for performance reasons
1058 // this is safe, as in case of a crash, we rescan the necessary blocks on startup through our SetBestChain-mechanism
1059 CWalletDB walletdb(strWalletFile, "r+", false);
1060
1061 return AddToWallet(wtx, false, &walletdb);
6cc4a62c 1062 }
e8ef3da7 1063 }
e8ef3da7
WL
1064 return false;
1065}
1066
d38da59b 1067void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
93a18a36 1068{
55a1db4f 1069 LOCK2(cs_main, cs_wallet);
d38da59b 1070 if (!AddToWalletIfInvolvingMe(tx, pblock, true))
93a18a36
GA
1071 return; // Not one of ours
1072
ac1c9435
JG
1073 MarkAffectedTransactionsDirty(tx);
1074}
1075
1076void CWallet::MarkAffectedTransactionsDirty(const CTransaction& tx)
1077{
93a18a36
GA
1078 // If a transaction changes 'conflicted' state, that changes the balance
1079 // available of the outputs it spends. So force those to be
1080 // recomputed, also:
1081 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1082 {
1083 if (mapWallet.count(txin.prevout.hash))
1084 mapWallet[txin.prevout.hash].MarkDirty();
1085 }
8db7e25c
JG
1086 for (const JSDescription& jsdesc : tx.vjoinsplit) {
1087 for (const uint256& nullifier : jsdesc.nullifiers) {
ad20f214
JG
1088 if (mapNullifiersToNotes.count(nullifier) &&
1089 mapWallet.count(mapNullifiersToNotes[nullifier].hash)) {
1090 mapWallet[mapNullifiersToNotes[nullifier].hash].MarkDirty();
8db7e25c
JG
1091 }
1092 }
1093 }
00588c3f
PW
1094}
1095
1096void CWallet::EraseFromWallet(const uint256 &hash)
e8ef3da7
WL
1097{
1098 if (!fFileBacked)
00588c3f 1099 return;
e8ef3da7 1100 {
f8dcd5ca 1101 LOCK(cs_wallet);
e8ef3da7
WL
1102 if (mapWallet.erase(hash))
1103 CWalletDB(strWalletFile).EraseTx(hash);
1104 }
00588c3f 1105 return;
e8ef3da7
WL
1106}
1107
1108
02e67455
JG
1109mapNoteData_t CWallet::FindMyNotes(const CTransaction& tx) const
1110{
3fac1020 1111 LOCK(cs_SpendingKeyStore);
fa511e10 1112 uint256 hash = tx.GetHash();
02e67455
JG
1113
1114 mapNoteData_t noteData;
02e67455
JG
1115 libzcash::SpendingKey key;
1116 for (size_t i = 0; i < tx.vjoinsplit.size(); i++) {
1117 auto hSig = tx.vjoinsplit[i].h_sig(*pzcashParams, tx.joinSplitPubKey);
1118 for (uint8_t j = 0; j < tx.vjoinsplit[i].ciphertexts.size(); j++) {
3fac1020 1119 for (const NoteDecryptorMap::value_type& item : mapNoteDecryptors) {
02e67455
JG
1120 try {
1121 auto note_pt = libzcash::NotePlaintext::decrypt(
1122 item.second,
1123 tx.vjoinsplit[i].ciphertexts[j],
1124 tx.vjoinsplit[i].ephemeralKey,
1125 hSig,
1126 (unsigned char) j);
1127 auto address = item.first;
1128 // Decryptors are only cached when SpendingKeys are added
1129 assert(GetSpendingKey(address, key));
1130 auto note = note_pt.note(address);
1131 JSOutPoint jsoutpt {hash, i, j};
1132 CNoteData nd {address, note.nullifier(key)};
1133 noteData.insert(std::make_pair(jsoutpt, nd));
1134 break;
32a103aa 1135 } catch (const std::runtime_error &) {
02e67455 1136 // Couldn't decrypt with this spending key
32a103aa
JG
1137 } catch (const std::exception &exc) {
1138 // Unexpected failure
1139 LogPrintf("FindMyNotes(): Unexpected error while testing decrypt:\n");
1140 LogPrintf("%s\n", exc.what());
02e67455
JG
1141 }
1142 }
1143 }
1144 }
1145 return noteData;
1146}
1147
1551db87
JG
1148bool CWallet::IsFromMe(const uint256& nullifier) const
1149{
1150 {
1151 LOCK(cs_wallet);
1152 if (mapNullifiersToNotes.count(nullifier) &&
1153 mapWallet.count(mapNullifiersToNotes.at(nullifier).hash)) {
1154 return true;
1155 }
1156 }
1157 return false;
1158}
1159
be74c80d
JG
1160void CWallet::GetNoteWitnesses(std::vector<JSOutPoint> notes,
1161 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
1162 uint256 &final_anchor)
1163{
1164 {
1165 LOCK(cs_wallet);
1166 witnesses.resize(notes.size());
4086e5ce 1167 boost::optional<uint256> rt;
be74c80d
JG
1168 int i = 0;
1169 for (JSOutPoint note : notes) {
1170 if (mapWallet.count(note.hash) &&
1171 mapWallet[note.hash].mapNoteData.count(note) &&
1172 mapWallet[note.hash].mapNoteData[note].witnesses.size() > 0) {
1173 witnesses[i] = mapWallet[note.hash].mapNoteData[note].witnesses.front();
4086e5ce
JG
1174 if (!rt) {
1175 rt = witnesses[i]->root();
1176 } else {
1177 assert(*rt == witnesses[i]->root());
1178 }
be74c80d
JG
1179 }
1180 i++;
1181 }
4086e5ce
JG
1182 // All returned witnesses have the same anchor
1183 if (rt) {
1184 final_anchor = *rt;
be74c80d
JG
1185 }
1186 }
1187}
1188
c8988460 1189isminetype CWallet::IsMine(const CTxIn &txin) const
e8ef3da7 1190{
e8ef3da7 1191 {
f8dcd5ca 1192 LOCK(cs_wallet);
e8ef3da7
WL
1193 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1194 if (mi != mapWallet.end())
1195 {
1196 const CWalletTx& prev = (*mi).second;
1197 if (txin.prevout.n < prev.vout.size())
c8988460 1198 return IsMine(prev.vout[txin.prevout.n]);
e8ef3da7
WL
1199 }
1200 }
a3e192a3 1201 return ISMINE_NO;
e8ef3da7
WL
1202}
1203
a372168e 1204CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
e8ef3da7 1205{
e8ef3da7 1206 {
f8dcd5ca 1207 LOCK(cs_wallet);
e8ef3da7
WL
1208 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1209 if (mi != mapWallet.end())
1210 {
1211 const CWalletTx& prev = (*mi).second;
1212 if (txin.prevout.n < prev.vout.size())
d4640d7d 1213 if (IsMine(prev.vout[txin.prevout.n]) & filter)
e8ef3da7
WL
1214 return prev.vout[txin.prevout.n].nValue;
1215 }
1216 }
1217 return 0;
1218}
1219
eca0b1ea
JT
1220isminetype CWallet::IsMine(const CTxOut& txout) const
1221{
1222 return ::IsMine(*this, txout.scriptPubKey);
1223}
1224
1225CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1226{
1227 if (!MoneyRange(txout.nValue))
1228 throw std::runtime_error("CWallet::GetCredit(): value out of range");
1229 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1230}
1231
e679ec96
GA
1232bool CWallet::IsChange(const CTxOut& txout) const
1233{
2a45a494 1234 // TODO: fix handling of 'change' outputs. The assumption is that any
d5087d1b 1235 // payment to a script that is ours, but is not in the address book
2a45a494
GA
1236 // is change. That assumption is likely to break when we implement multisignature
1237 // wallets that return change back into a multi-signature-protected address;
1238 // a better way of identifying which outputs are 'the send' and which are
1239 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1240 // which output, if any, was change).
d5087d1b 1241 if (::IsMine(*this, txout.scriptPubKey))
f8dcd5ca 1242 {
d5087d1b
PW
1243 CTxDestination address;
1244 if (!ExtractDestination(txout.scriptPubKey, address))
1245 return true;
1246
f8dcd5ca
PW
1247 LOCK(cs_wallet);
1248 if (!mapAddressBook.count(address))
1249 return true;
1250 }
e679ec96
GA
1251 return false;
1252}
1253
eca0b1ea
JT
1254CAmount CWallet::GetChange(const CTxOut& txout) const
1255{
1256 if (!MoneyRange(txout.nValue))
1257 throw std::runtime_error("CWallet::GetChange(): value out of range");
1258 return (IsChange(txout) ? txout.nValue : 0);
1259}
1260
1261bool CWallet::IsMine(const CTransaction& tx) const
1262{
1263 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1264 if (IsMine(txout))
1265 return true;
1266 return false;
1267}
1268
1269bool CWallet::IsFromMe(const CTransaction& tx) const
1270{
1551db87
JG
1271 if (GetDebit(tx, ISMINE_ALL) > 0) {
1272 return true;
1273 }
1274 for (const JSDescription& jsdesc : tx.vjoinsplit) {
1275 for (const uint256& nullifier : jsdesc.nullifiers) {
1276 if (IsFromMe(nullifier)) {
1277 return true;
1278 }
1279 }
1280 }
1281 return false;
eca0b1ea
JT
1282}
1283
1284CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1285{
1286 CAmount nDebit = 0;
1287 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1288 {
1289 nDebit += GetDebit(txin, filter);
1290 if (!MoneyRange(nDebit))
1291 throw std::runtime_error("CWallet::GetDebit(): value out of range");
1292 }
1293 return nDebit;
1294}
1295
1296CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1297{
1298 CAmount nCredit = 0;
1299 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1300 {
1301 nCredit += GetCredit(txout, filter);
1302 if (!MoneyRange(nCredit))
1303 throw std::runtime_error("CWallet::GetCredit(): value out of range");
1304 }
1305 return nCredit;
1306}
1307
1308CAmount CWallet::GetChange(const CTransaction& tx) const
1309{
1310 CAmount nChange = 0;
1311 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1312 {
1313 nChange += GetChange(txout);
1314 if (!MoneyRange(nChange))
1315 throw std::runtime_error("CWallet::GetChange(): value out of range");
1316 }
1317 return nChange;
1318}
1319
c3a7307a
JG
1320void CWalletTx::SetNoteData(mapNoteData_t &noteData)
1321{
1322 mapNoteData.clear();
1323 for (const std::pair<JSOutPoint, CNoteData> nd : noteData) {
1324 if (nd.first.js < vjoinsplit.size() &&
1325 nd.first.n < vjoinsplit[nd.first.js].ciphertexts.size()) {
1326 // Store the address and nullifier for the Note
1327 mapNoteData[nd.first] = nd.second;
1328 } else {
1329 // If FindMyNotes() was used to obtain noteData,
1330 // this should never happen
32a103aa 1331 throw std::logic_error("CWalletTx::SetNoteData(): Invalid note");
c3a7307a
JG
1332 }
1333 }
1334}
1335
51ed9ec9 1336int64_t CWalletTx::GetTxTime() const
e8ef3da7 1337{
51ed9ec9 1338 int64_t n = nTimeSmart;
c3f95ef1 1339 return n ? n : nTimeReceived;
e8ef3da7
WL
1340}
1341
1342int CWalletTx::GetRequestCount() const
1343{
1344 // Returns -1 if it wasn't being tracked
1345 int nRequests = -1;
e8ef3da7 1346 {
f8dcd5ca 1347 LOCK(pwallet->cs_wallet);
e8ef3da7
WL
1348 if (IsCoinBase())
1349 {
1350 // Generated block
4f152496 1351 if (!hashBlock.IsNull())
e8ef3da7
WL
1352 {
1353 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1354 if (mi != pwallet->mapRequestCount.end())
1355 nRequests = (*mi).second;
1356 }
1357 }
1358 else
1359 {
1360 // Did anyone request this transaction?
805344dc 1361 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
e8ef3da7
WL
1362 if (mi != pwallet->mapRequestCount.end())
1363 {
1364 nRequests = (*mi).second;
1365
1366 // How about the block it's in?
4f152496 1367 if (nRequests == 0 && !hashBlock.IsNull())
e8ef3da7
WL
1368 {
1369 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1370 if (mi != pwallet->mapRequestCount.end())
1371 nRequests = (*mi).second;
1372 else
1373 nRequests = 1; // If it's in someone else's block it must have got out
1374 }
1375 }
1376 }
1377 }
1378 return nRequests;
1379}
1380
1b4568cb 1381void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
a372168e 1382 list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
e8ef3da7 1383{
e07c8e91 1384 nFee = 0;
e8ef3da7
WL
1385 listReceived.clear();
1386 listSent.clear();
1387 strSentAccount = strFromAccount;
1388
e8ef3da7 1389 // Compute fee:
a372168e 1390 CAmount nDebit = GetDebit(filter);
e8ef3da7
WL
1391 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1392 {
a372168e 1393 CAmount nValueOut = GetValueOut();
e8ef3da7
WL
1394 nFee = nDebit - nValueOut;
1395 }
1396
e679ec96 1397 // Sent/received.
5bb76550 1398 for (unsigned int i = 0; i < vout.size(); ++i)
e8ef3da7 1399 {
1b4568cb 1400 const CTxOut& txout = vout[i];
a5c6c5d6 1401 isminetype fIsMine = pwallet->IsMine(txout);
96ed6821
LD
1402 // Only need to handle txouts if AT LEAST one of these is true:
1403 // 1) they debit from us (sent)
1404 // 2) the output is to us (received)
1405 if (nDebit > 0)
1406 {
1407 // Don't report 'change' txouts
1408 if (pwallet->IsChange(txout))
1409 continue;
96ed6821 1410 }
a5c6c5d6 1411 else if (!(fIsMine & filter))
96ed6821
LD
1412 continue;
1413
1414 // In either case, we need to get the destination address
10254401 1415 CTxDestination address;
10254401 1416 if (!ExtractDestination(txout.scriptPubKey, address))
e8ef3da7 1417 {
881a85a2 1418 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
805344dc 1419 this->GetHash().ToString());
96ed6821 1420 address = CNoDestination();
e8ef3da7
WL
1421 }
1422
5bb76550 1423 COutputEntry output = {address, txout.nValue, (int)i};
1b4568cb 1424
96ed6821 1425 // If we are debited by the transaction, add the output as a "sent" entry
e8ef3da7 1426 if (nDebit > 0)
1b4568cb 1427 listSent.push_back(output);
e8ef3da7 1428
96ed6821 1429 // If we are receiving the output, add it as a "received" entry
d512534c 1430 if (fIsMine & filter)
1b4568cb 1431 listReceived.push_back(output);
e8ef3da7
WL
1432 }
1433
1434}
1435
a372168e
MF
1436void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
1437 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
e8ef3da7 1438{
e07c8e91 1439 nReceived = nSent = nFee = 0;
e8ef3da7 1440
a372168e 1441 CAmount allFee;
e8ef3da7 1442 string strSentAccount;
1b4568cb
CL
1443 list<COutputEntry> listReceived;
1444 list<COutputEntry> listSent;
d4640d7d 1445 GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
e8ef3da7 1446
e8ef3da7
WL
1447 if (strAccount == strSentAccount)
1448 {
1b4568cb
CL
1449 BOOST_FOREACH(const COutputEntry& s, listSent)
1450 nSent += s.amount;
e8ef3da7
WL
1451 nFee = allFee;
1452 }
e8ef3da7 1453 {
f8dcd5ca 1454 LOCK(pwallet->cs_wallet);
1b4568cb 1455 BOOST_FOREACH(const COutputEntry& r, listReceived)
e8ef3da7 1456 {
1b4568cb 1457 if (pwallet->mapAddressBook.count(r.destination))
e8ef3da7 1458 {
1b4568cb 1459 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
61885513 1460 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
1b4568cb 1461 nReceived += r.amount;
e8ef3da7
WL
1462 }
1463 else if (strAccount.empty())
1464 {
1b4568cb 1465 nReceived += r.amount;
e8ef3da7
WL
1466 }
1467 }
1468 }
1469}
1470
722fa283 1471
44bc988e 1472bool CWalletTx::WriteToDisk(CWalletDB *pwalletdb)
e8ef3da7 1473{
805344dc 1474 return pwalletdb->WriteTx(GetHash(), *this);
e8ef3da7
WL
1475}
1476
4bc00dc1
DH
1477void CWallet::WitnessNoteCommitment(std::vector<uint256> commitments,
1478 std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,
1479 uint256 &final_anchor)
a8ac403d 1480{
2dc35992 1481 witnesses.resize(commitments.size());
a8ac403d 1482 CBlockIndex* pindex = chainActive.Genesis();
1760b3cd 1483 ZCIncrementalMerkleTree tree;
a8ac403d
SB
1484
1485 while (pindex) {
1486 CBlock block;
1487 ReadBlockFromDisk(block, pindex);
1488
1489 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1490 {
22de1602 1491 BOOST_FOREACH(const JSDescription& jsdesc, tx.vjoinsplit)
a8ac403d 1492 {
22de1602 1493 BOOST_FOREACH(const uint256 &note_commitment, jsdesc.commitments)
a8ac403d 1494 {
4bc00dc1 1495 tree.append(note_commitment);
1760b3cd 1496
2dc35992
SB
1497 BOOST_FOREACH(boost::optional<ZCIncrementalWitness>& wit, witnesses) {
1498 if (wit) {
4bc00dc1 1499 wit->append(note_commitment);
2dc35992
SB
1500 }
1501 }
1502
1503 size_t i = 0;
1504 BOOST_FOREACH(uint256& commitment, commitments) {
4bc00dc1 1505 if (note_commitment == commitment) {
2dc35992 1506 witnesses.at(i) = tree.witness();
1760b3cd 1507 }
2dc35992 1508 i++;
a8ac403d
SB
1509 }
1510 }
1511 }
1512 }
1513
ccb439c5 1514 uint256 current_anchor = tree.root();
a8ac403d
SB
1515
1516 // Consistency check: we should be able to find the current tree
1517 // in our CCoins view.
434f3284 1518 ZCIncrementalMerkleTree dummy_tree;
a8ac403d
SB
1519 assert(pcoinsTip->GetAnchorAt(current_anchor, dummy_tree));
1520
1521 pindex = chainActive.Next(pindex);
1522 }
1523
ccb439c5
SB
1524 // TODO: #93; Select a root via some heuristic.
1525 final_anchor = tree.root();
a8ac403d 1526
2dc35992
SB
1527 BOOST_FOREACH(boost::optional<ZCIncrementalWitness>& wit, witnesses) {
1528 if (wit) {
1529 assert(final_anchor == wit->root());
1530 }
1760b3cd 1531 }
a8ac403d
SB
1532}
1533
5b40d886
MF
1534/**
1535 * Scan the block chain (starting in pindexStart) for transactions
1536 * from or to us. If fUpdate is true, found transactions that already
1537 * exist in the wallet will be updated.
1538 */
e8ef3da7
WL
1539int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1540{
1541 int ret = 0;
75b8953a 1542 int64_t nNow = GetTime();
11982d36 1543 const CChainParams& chainParams = Params();
e8ef3da7
WL
1544
1545 CBlockIndex* pindex = pindexStart;
e8ef3da7 1546 {
55a1db4f 1547 LOCK2(cs_main, cs_wallet);
39278369
CL
1548
1549 // no need to read and scan block, if block was created before
1550 // our wallet birthday (as adjusted for block time variability)
209377a7 1551 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
39278369
CL
1552 pindex = chainActive.Next(pindex);
1553
1554 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
11982d36
CF
1555 double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
1556 double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip(), false);
e8ef3da7
WL
1557 while (pindex)
1558 {
39278369 1559 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
11982d36 1560 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
8da9dd07 1561
e8ef3da7 1562 CBlock block;
7db120d5 1563 ReadBlockFromDisk(block, pindex);
e8ef3da7
WL
1564 BOOST_FOREACH(CTransaction& tx, block.vtx)
1565 {
d38da59b 1566 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
e8ef3da7
WL
1567 ret++;
1568 }
4c6d41b8 1569 pindex = chainActive.Next(pindex);
75b8953a
B
1570 if (GetTime() >= nNow + 60) {
1571 nNow = GetTime();
11982d36 1572 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex));
75b8953a 1573 }
e8ef3da7 1574 }
39278369 1575 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
e8ef3da7
WL
1576 }
1577 return ret;
1578}
1579
1580void CWallet::ReacceptWalletTransactions()
1581{
7e6d23b1 1582 // If transactions aren't being broadcasted, don't let them into local mempool either
6f252627
WL
1583 if (!fBroadcastTransactions)
1584 return;
55a1db4f 1585 LOCK2(cs_main, cs_wallet);
e9c3215b 1586 std::map<int64_t, CWalletTx*> mapSorted;
1587
1588 // Sort pending wallet transactions based on their initial wallet insertion order
93a18a36 1589 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
e8ef3da7 1590 {
93a18a36
GA
1591 const uint256& wtxid = item.first;
1592 CWalletTx& wtx = item.second;
805344dc 1593 assert(wtx.GetHash() == wtxid);
e8ef3da7 1594
93a18a36
GA
1595 int nDepth = wtx.GetDepthInMainChain();
1596
e9c3215b 1597 if (!wtx.IsCoinBase() && nDepth < 0) {
1598 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
e8ef3da7
WL
1599 }
1600 }
e9c3215b 1601
1602 // Try to add wallet transactions to memory pool
1603 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1604 {
1605 CWalletTx& wtx = *(item.second);
1606
1607 LOCK(mempool.cs);
1608 wtx.AcceptToMemoryPool(false);
1609 }
e8ef3da7
WL
1610}
1611
0f5954c4 1612bool CWalletTx::RelayWalletTransaction()
e8ef3da7 1613{
6f252627 1614 assert(pwallet->GetBroadcastTransactions());
e8ef3da7
WL
1615 if (!IsCoinBase())
1616 {
5eaf91a4 1617 if (GetDepthInMainChain() == 0) {
805344dc 1618 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
d38da59b 1619 RelayTransaction((CTransaction)*this);
0f5954c4 1620 return true;
e8ef3da7
WL
1621 }
1622 }
0f5954c4 1623 return false;
e8ef3da7
WL
1624}
1625
3015e0bc 1626set<uint256> CWalletTx::GetConflicts() const
731b89b8
GA
1627{
1628 set<uint256> result;
1629 if (pwallet != NULL)
1630 {
805344dc 1631 uint256 myHash = GetHash();
3015e0bc 1632 result = pwallet->GetConflicts(myHash);
731b89b8
GA
1633 result.erase(myHash);
1634 }
1635 return result;
1636}
1637
bbacd882
CF
1638CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1639{
1640 if (vin.empty())
1641 return 0;
1642
1643 CAmount debit = 0;
1644 if(filter & ISMINE_SPENDABLE)
1645 {
1646 if (fDebitCached)
1647 debit += nDebitCached;
1648 else
1649 {
1650 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1651 fDebitCached = true;
1652 debit += nDebitCached;
1653 }
1654 }
1655 if(filter & ISMINE_WATCH_ONLY)
1656 {
1657 if(fWatchDebitCached)
1658 debit += nWatchDebitCached;
1659 else
1660 {
1661 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1662 fWatchDebitCached = true;
1663 debit += nWatchDebitCached;
1664 }
1665 }
1666 return debit;
1667}
1668
1669CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1670{
1671 // Must wait until coinbase is safely deep enough in the chain before valuing it
1672 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1673 return 0;
1674
1675 int64_t credit = 0;
1676 if (filter & ISMINE_SPENDABLE)
1677 {
1678 // GetBalance can assume transactions in mapWallet won't change
1679 if (fCreditCached)
1680 credit += nCreditCached;
1681 else
1682 {
1683 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1684 fCreditCached = true;
1685 credit += nCreditCached;
1686 }
1687 }
1688 if (filter & ISMINE_WATCH_ONLY)
1689 {
1690 if (fWatchCreditCached)
1691 credit += nWatchCreditCached;
1692 else
1693 {
1694 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1695 fWatchCreditCached = true;
1696 credit += nWatchCreditCached;
1697 }
1698 }
1699 return credit;
1700}
1701
1702CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1703{
1704 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1705 {
1706 if (fUseCache && fImmatureCreditCached)
1707 return nImmatureCreditCached;
1708 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1709 fImmatureCreditCached = true;
1710 return nImmatureCreditCached;
1711 }
1712
1713 return 0;
1714}
1715
1716CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1717{
1718 if (pwallet == 0)
1719 return 0;
1720
1721 // Must wait until coinbase is safely deep enough in the chain before valuing it
1722 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1723 return 0;
1724
1725 if (fUseCache && fAvailableCreditCached)
1726 return nAvailableCreditCached;
1727
1728 CAmount nCredit = 0;
805344dc 1729 uint256 hashTx = GetHash();
bbacd882
CF
1730 for (unsigned int i = 0; i < vout.size(); i++)
1731 {
1732 if (!pwallet->IsSpent(hashTx, i))
1733 {
1734 const CTxOut &txout = vout[i];
1735 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1736 if (!MoneyRange(nCredit))
1737 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1738 }
1739 }
1740
1741 nAvailableCreditCached = nCredit;
1742 fAvailableCreditCached = true;
1743 return nCredit;
1744}
1745
1746CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1747{
1748 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1749 {
1750 if (fUseCache && fImmatureWatchCreditCached)
1751 return nImmatureWatchCreditCached;
1752 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1753 fImmatureWatchCreditCached = true;
1754 return nImmatureWatchCreditCached;
1755 }
1756
1757 return 0;
1758}
1759
1760CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1761{
1762 if (pwallet == 0)
1763 return 0;
1764
1765 // Must wait until coinbase is safely deep enough in the chain before valuing it
1766 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1767 return 0;
1768
1769 if (fUseCache && fAvailableWatchCreditCached)
1770 return nAvailableWatchCreditCached;
1771
1772 CAmount nCredit = 0;
1773 for (unsigned int i = 0; i < vout.size(); i++)
1774 {
805344dc 1775 if (!pwallet->IsSpent(GetHash(), i))
bbacd882
CF
1776 {
1777 const CTxOut &txout = vout[i];
1778 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1779 if (!MoneyRange(nCredit))
1780 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1781 }
1782 }
1783
1784 nAvailableWatchCreditCached = nCredit;
1785 fAvailableWatchCreditCached = true;
1786 return nCredit;
1787}
1788
1789CAmount CWalletTx::GetChange() const
1790{
1791 if (fChangeCached)
1792 return nChangeCached;
1793 nChangeCached = pwallet->GetChange(*this);
1794 fChangeCached = true;
1795 return nChangeCached;
1796}
1797
1798bool CWalletTx::IsTrusted() const
1799{
1800 // Quick answer in most cases
75a4d512 1801 if (!CheckFinalTx(*this))
bbacd882
CF
1802 return false;
1803 int nDepth = GetDepthInMainChain();
1804 if (nDepth >= 1)
1805 return true;
1806 if (nDepth < 0)
1807 return false;
1808 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1809 return false;
1810
1811 // Trusted if all inputs are from us and are in the mempool:
1812 BOOST_FOREACH(const CTxIn& txin, vin)
1813 {
1814 // Transactions not sent by us: not trusted
1815 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1816 if (parent == NULL)
1817 return false;
1818 const CTxOut& parentOut = parent->vout[txin.prevout.n];
1819 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1820 return false;
1821 }
1822 return true;
1823}
1824
0f5954c4
GA
1825std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
1826{
1827 std::vector<uint256> result;
1828
1829 LOCK(cs_wallet);
1830 // Sort them in chronological order
1831 multimap<unsigned int, CWalletTx*> mapSorted;
1832 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1833 {
1834 CWalletTx& wtx = item.second;
1835 // Don't rebroadcast if newer than nTime:
1836 if (wtx.nTimeReceived > nTime)
1837 continue;
1838 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1839 }
1840 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1841 {
1842 CWalletTx& wtx = *item.second;
1843 if (wtx.RelayWalletTransaction())
805344dc 1844 result.push_back(wtx.GetHash());
0f5954c4
GA
1845 }
1846 return result;
1847}
1848
1849void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
e8ef3da7
WL
1850{
1851 // Do this infrequently and randomly to avoid giving away
1852 // that these are our transactions.
6f252627 1853 if (GetTime() < nNextResend || !fBroadcastTransactions)
e8ef3da7 1854 return;
203d1ae6
LD
1855 bool fFirst = (nNextResend == 0);
1856 nNextResend = GetTime() + GetRand(30 * 60);
e8ef3da7
WL
1857 if (fFirst)
1858 return;
1859
1860 // Only do it if there's been a new block since last time
0f5954c4 1861 if (nBestBlockTime < nLastResend)
e8ef3da7 1862 return;
203d1ae6 1863 nLastResend = GetTime();
e8ef3da7 1864
0f5954c4
GA
1865 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1866 // block was found:
1867 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60);
1868 if (!relayed.empty())
1869 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
e8ef3da7
WL
1870}
1871
5b40d886 1872/** @} */ // end of mapWallet
e8ef3da7
WL
1873
1874
1875
1876
5b40d886
MF
1877/** @defgroup Actions
1878 *
1879 * @{
1880 */
e8ef3da7
WL
1881
1882
a372168e 1883CAmount CWallet::GetBalance() const
e8ef3da7 1884{
a372168e 1885 CAmount nTotal = 0;
e8ef3da7 1886 {
55a1db4f 1887 LOCK2(cs_main, cs_wallet);
e8ef3da7
WL
1888 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1889 {
1890 const CWalletTx* pcoin = &(*it).second;
0542619d 1891 if (pcoin->IsTrusted())
8fdb7e10 1892 nTotal += pcoin->GetAvailableCredit();
e8ef3da7
WL
1893 }
1894 }
1895
e8ef3da7
WL
1896 return nTotal;
1897}
1898
a372168e 1899CAmount CWallet::GetUnconfirmedBalance() const
df5ccbd2 1900{
a372168e 1901 CAmount nTotal = 0;
df5ccbd2 1902 {
55a1db4f 1903 LOCK2(cs_main, cs_wallet);
df5ccbd2
WL
1904 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1905 {
1906 const CWalletTx* pcoin = &(*it).second;
75a4d512 1907 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
8fdb7e10 1908 nTotal += pcoin->GetAvailableCredit();
1909 }
1910 }
1911 return nTotal;
1912}
1913
a372168e 1914CAmount CWallet::GetImmatureBalance() const
8fdb7e10 1915{
a372168e 1916 CAmount nTotal = 0;
8fdb7e10 1917 {
55a1db4f 1918 LOCK2(cs_main, cs_wallet);
8fdb7e10 1919 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1920 {
966a0e8c
PK
1921 const CWalletTx* pcoin = &(*it).second;
1922 nTotal += pcoin->GetImmatureCredit();
df5ccbd2
WL
1923 }
1924 }
1925 return nTotal;
1926}
e8ef3da7 1927
a372168e 1928CAmount CWallet::GetWatchOnlyBalance() const
ffd40da3 1929{
a372168e 1930 CAmount nTotal = 0;
ffd40da3 1931 {
39cc4922 1932 LOCK2(cs_main, cs_wallet);
ffd40da3
J
1933 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1934 {
1935 const CWalletTx* pcoin = &(*it).second;
1936 if (pcoin->IsTrusted())
1937 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1938 }
1939 }
870da77d 1940
ffd40da3
J
1941 return nTotal;
1942}
1943
a372168e 1944CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
ffd40da3 1945{
a372168e 1946 CAmount nTotal = 0;
ffd40da3 1947 {
39cc4922 1948 LOCK2(cs_main, cs_wallet);
ffd40da3
J
1949 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1950 {
1951 const CWalletTx* pcoin = &(*it).second;
75a4d512 1952 if (!CheckFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
ffd40da3
J
1953 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1954 }
1955 }
1956 return nTotal;
1957}
1958
a372168e 1959CAmount CWallet::GetImmatureWatchOnlyBalance() const
ffd40da3 1960{
a372168e 1961 CAmount nTotal = 0;
ffd40da3 1962 {
39cc4922 1963 LOCK2(cs_main, cs_wallet);
ffd40da3
J
1964 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1965 {
1966 const CWalletTx* pcoin = &(*it).second;
1967 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1968 }
1969 }
1970 return nTotal;
1971}
1972
5b40d886
MF
1973/**
1974 * populate vCoins with vector of available COutputs.
1975 */
219953ce 1976void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue) const
9b0369c7
CM
1977{
1978 vCoins.clear();
1979
1980 {
ea3acaf3 1981 LOCK2(cs_main, cs_wallet);
9b0369c7
CM
1982 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1983 {
93a18a36 1984 const uint256& wtxid = it->first;
9b0369c7
CM
1985 const CWalletTx* pcoin = &(*it).second;
1986
75a4d512 1987 if (!CheckFinalTx(*pcoin))
a2709fad
GA
1988 continue;
1989
0542619d 1990 if (fOnlyConfirmed && !pcoin->IsTrusted())
9b0369c7
CM
1991 continue;
1992
1993 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1994 continue;
1995
2b72d46f
GA
1996 int nDepth = pcoin->GetDepthInMainChain();
1997 if (nDepth < 0)
1998 continue;
1999
fdbb537d 2000 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
c8988460 2001 isminetype mine = IsMine(pcoin->vout[i]);
a3e192a3 2002 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
219953ce 2003 !IsLockedCoin((*it).first, i) && (pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
6a86c24d 2004 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
8d657a65 2005 vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO));
fdbb537d 2006 }
9b0369c7
CM
2007 }
2008 }
2009}
2010
a372168e
MF
2011static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2012 vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
831f59ce
CM
2013{
2014 vector<char> vfIncluded;
2015
2016 vfBest.assign(vValue.size(), true);
2017 nBest = nTotalLower;
2018
907a2aa4
GM
2019 seed_insecure_rand();
2020
831f59ce
CM
2021 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2022 {
2023 vfIncluded.assign(vValue.size(), false);
a372168e 2024 CAmount nTotal = 0;
831f59ce
CM
2025 bool fReachedTarget = false;
2026 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2027 {
2028 for (unsigned int i = 0; i < vValue.size(); i++)
2029 {
907a2aa4
GM
2030 //The solver here uses a randomized algorithm,
2031 //the randomness serves no real security purpose but is just
2032 //needed to prevent degenerate behavior and it is important
5b40d886 2033 //that the rng is fast. We do not use a constant random sequence,
907a2aa4
GM
2034 //because there may be some privacy improvement by making
2035 //the selection random.
2036 if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
831f59ce
CM
2037 {
2038 nTotal += vValue[i].first;
2039 vfIncluded[i] = true;
2040 if (nTotal >= nTargetValue)
2041 {
2042 fReachedTarget = true;
2043 if (nTotal < nBest)
2044 {
2045 nBest = nTotal;
2046 vfBest = vfIncluded;
2047 }
2048 nTotal -= vValue[i].first;
2049 vfIncluded[i] = false;
2050 }
2051 }
2052 }
2053 }
2054 }
2055}
2056
a372168e
MF
2057bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
2058 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
e8ef3da7
WL
2059{
2060 setCoinsRet.clear();
2061 nValueRet = 0;
2062
2063 // List of values less than target
a372168e
MF
2064 pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
2065 coinLowestLarger.first = std::numeric_limits<CAmount>::max();
e8ef3da7 2066 coinLowestLarger.second.first = NULL;
a372168e
MF
2067 vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
2068 CAmount nTotalLower = 0;
e8ef3da7 2069
e333ab56
CM
2070 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2071
c8988460 2072 BOOST_FOREACH(const COutput &output, vCoins)
e8ef3da7 2073 {
c8988460
PW
2074 if (!output.fSpendable)
2075 continue;
2076
9b0369c7 2077 const CWalletTx *pcoin = output.tx;
e8ef3da7 2078
a3e192a3 2079 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
9b0369c7 2080 continue;
e8ef3da7 2081
9b0369c7 2082 int i = output.i;
a372168e 2083 CAmount n = pcoin->vout[i].nValue;
e8ef3da7 2084
a372168e 2085 pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
e8ef3da7 2086
9b0369c7
CM
2087 if (n == nTargetValue)
2088 {
2089 setCoinsRet.insert(coin.second);
2090 nValueRet += coin.first;
2091 return true;
2092 }
2093 else if (n < nTargetValue + CENT)
2094 {
2095 vValue.push_back(coin);
2096 nTotalLower += n;
2097 }
2098 else if (n < coinLowestLarger.first)
2099 {
2100 coinLowestLarger = coin;
e8ef3da7
WL
2101 }
2102 }
2103
831f59ce 2104 if (nTotalLower == nTargetValue)
e8ef3da7 2105 {
c376ac35 2106 for (unsigned int i = 0; i < vValue.size(); ++i)
e8ef3da7
WL
2107 {
2108 setCoinsRet.insert(vValue[i].second);
2109 nValueRet += vValue[i].first;
2110 }
2111 return true;
2112 }
2113
831f59ce 2114 if (nTotalLower < nTargetValue)
e8ef3da7
WL
2115 {
2116 if (coinLowestLarger.second.first == NULL)
2117 return false;
2118 setCoinsRet.insert(coinLowestLarger.second);
2119 nValueRet += coinLowestLarger.first;
2120 return true;
2121 }
2122
e8ef3da7 2123 // Solve subset sum by stochastic approximation
d650f96d 2124 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
831f59ce 2125 vector<char> vfBest;
a372168e 2126 CAmount nBest;
e8ef3da7 2127
831f59ce
CM
2128 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
2129 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
2130 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
e8ef3da7 2131
831f59ce
CM
2132 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2133 // or the next bigger coin is closer), return the bigger coin
2134 if (coinLowestLarger.second.first &&
2135 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
e8ef3da7
WL
2136 {
2137 setCoinsRet.insert(coinLowestLarger.second);
2138 nValueRet += coinLowestLarger.first;
2139 }
2140 else {
c376ac35 2141 for (unsigned int i = 0; i < vValue.size(); i++)
e8ef3da7
WL
2142 if (vfBest[i])
2143 {
2144 setCoinsRet.insert(vValue[i].second);
2145 nValueRet += vValue[i].first;
2146 }
2147
faaeae1e 2148 LogPrint("selectcoins", "SelectCoins() best subset: ");
c376ac35 2149 for (unsigned int i = 0; i < vValue.size(); i++)
e8ef3da7 2150 if (vfBest[i])
7d9d134b
WL
2151 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
2152 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
e8ef3da7
WL
2153 }
2154
2155 return true;
2156}
2157
a372168e 2158bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
e8ef3da7 2159{
9b0369c7 2160 vector<COutput> vCoins;
6a86c24d
CL
2161 AvailableCoins(vCoins, true, coinControl);
2162
2163 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2164 if (coinControl && coinControl->HasSelected())
2165 {
2166 BOOST_FOREACH(const COutput& out, vCoins)
2167 {
2935b211
WL
2168 if(!out.fSpendable)
2169 continue;
6a86c24d
CL
2170 nValueRet += out.tx->vout[out.i].nValue;
2171 setCoinsRet.insert(make_pair(out.tx, out.i));
2172 }
2173 return (nValueRet >= nTargetValue);
2174 }
9b0369c7
CM
2175
2176 return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) ||
2177 SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1bbca249 2178 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet)));
e8ef3da7
WL
2179}
2180
292623ad
CL
2181bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend,
2182 CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosRet, std::string& strFailReason, const CCoinControl* coinControl)
e8ef3da7 2183{
a372168e 2184 CAmount nValue = 0;
292623ad
CL
2185 unsigned int nSubtractFeeFromAmount = 0;
2186 BOOST_FOREACH (const CRecipient& recipient, vecSend)
e8ef3da7 2187 {
292623ad 2188 if (nValue < 0 || recipient.nAmount < 0)
1f00f4e9
GA
2189 {
2190 strFailReason = _("Transaction amounts must be positive");
e8ef3da7 2191 return false;
1f00f4e9 2192 }
292623ad
CL
2193 nValue += recipient.nAmount;
2194
2195 if (recipient.fSubtractFeeFromAmount)
2196 nSubtractFeeFromAmount++;
e8ef3da7
WL
2197 }
2198 if (vecSend.empty() || nValue < 0)
1f00f4e9
GA
2199 {
2200 strFailReason = _("Transaction amounts must be positive");
e8ef3da7 2201 return false;
1f00f4e9 2202 }
e8ef3da7 2203
b33d1f5e 2204 wtxNew.fTimeReceivedIsTxTime = true;
4c6e2295 2205 wtxNew.BindWallet(this);
4949004d 2206 CMutableTransaction txNew;
e8ef3da7 2207
ba7fcc8d
PT
2208 // Discourage fee sniping.
2209 //
2210 // However because of a off-by-one-error in previous versions we need to
2211 // neuter it by setting nLockTime to at least one less than nBestHeight.
2212 // Secondly currently propagation of transactions created for block heights
2213 // corresponding to blocks that were just mined may be iffy - transactions
2214 // aren't re-accepted into the mempool - we additionally neuter the code by
2215 // going ten blocks back. Doesn't yet do anything for sniping, but does act
2216 // to shake out wallet bugs like not showing nLockTime'd transactions at
2217 // all.
2218 txNew.nLockTime = std::max(0, chainActive.Height() - 10);
2219
2220 // Secondly occasionally randomly pick a nLockTime even further back, so
2221 // that transactions that are delayed after signing for whatever reason,
2222 // e.g. high-latency mix networks and some CoinJoin implementations, have
2223 // better privacy.
2224 if (GetRandInt(10) == 0)
2225 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2226
2227 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2228 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2229
e8ef3da7 2230 {
f8dcd5ca 2231 LOCK2(cs_main, cs_wallet);
e8ef3da7 2232 {
c1c9d5b4 2233 nFeeRet = 0;
050d2e95 2234 while (true)
e8ef3da7 2235 {
4949004d
PW
2236 txNew.vin.clear();
2237 txNew.vout.clear();
e8ef3da7 2238 wtxNew.fFromMe = true;
292623ad
CL
2239 nChangePosRet = -1;
2240 bool fFirst = true;
e8ef3da7 2241
292623ad
CL
2242 CAmount nTotalValue = nValue;
2243 if (nSubtractFeeFromAmount == 0)
2244 nTotalValue += nFeeRet;
e8ef3da7
WL
2245 double dPriority = 0;
2246 // vouts to the payees
292623ad 2247 BOOST_FOREACH (const CRecipient& recipient, vecSend)
8de9bb53 2248 {
292623ad
CL
2249 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2250
2251 if (recipient.fSubtractFeeFromAmount)
2252 {
2253 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2254
2255 if (fFirst) // first receiver pays the remainder not divisible by output count
2256 {
2257 fFirst = false;
2258 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2259 }
2260 }
2261
13fc83c7 2262 if (txout.IsDust(::minRelayTxFee))
1f00f4e9 2263 {
292623ad
CL
2264 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2265 {
2266 if (txout.nValue < 0)
2267 strFailReason = _("The transaction amount is too small to pay the fee");
2268 else
2269 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2270 }
2271 else
2272 strFailReason = _("Transaction amount too small");
8de9bb53 2273 return false;
1f00f4e9 2274 }
4949004d 2275 txNew.vout.push_back(txout);
8de9bb53 2276 }
e8ef3da7
WL
2277
2278 // Choose coins to use
2279 set<pair<const CWalletTx*,unsigned int> > setCoins;
a372168e 2280 CAmount nValueIn = 0;
6a86c24d 2281 if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl))
1f00f4e9
GA
2282 {
2283 strFailReason = _("Insufficient funds");
e8ef3da7 2284 return false;
1f00f4e9 2285 }
e8ef3da7
WL
2286 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
2287 {
a372168e 2288 CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
2d9b0b7f 2289 //The coin age after the next block (depth+1) is used instead of the current,
d7836552
GM
2290 //reflecting an assumption the user would accept a bit more delay for
2291 //a chance at a free transaction.
2d9b0b7f
AM
2292 //But mempool inputs might still be in the mempool, so their age stays 0
2293 int age = pcoin.first->GetDepthInMainChain();
2294 if (age != 0)
2295 age += 1;
2296 dPriority += (double)nCredit * age;
e8ef3da7
WL
2297 }
2298
292623ad
CL
2299 CAmount nChange = nValueIn - nValue;
2300 if (nSubtractFeeFromAmount == 0)
2301 nChange -= nFeeRet;
a7dd11c6
PW
2302
2303 if (nChange > 0)
e8ef3da7 2304 {
bf798734
GA
2305 // Fill a vout to ourself
2306 // TODO: pass in scriptChange instead of reservekey so
2307 // change transaction isn't always pay-to-bitcoin-address
e8ef3da7 2308 CScript scriptChange;
6a86c24d
CL
2309
2310 // coin control: send change to custom address
2311 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
0be990ba 2312 scriptChange = GetScriptForDestination(coinControl->destChange);
6a86c24d
CL
2313
2314 // no coin control: send change to newly generated address
2315 else
2316 {
2317 // Note: We use a new key here to keep it from being obvious which side is the change.
2318 // The drawback is that by not reusing a previous key, the change may be lost if a
2319 // backup is restored, if the backup doesn't have the new private key for the change.
2320 // If we reused the old key, it would be possible to add code to look for and
2321 // rediscover unknown transactions that were written with keys of ours to recover
2322 // post-backup change.
2323
2324 // Reserve a new key pair from key pool
2325 CPubKey vchPubKey;
9b59e3bd
GM
2326 bool ret;
2327 ret = reservekey.GetReservedKey(vchPubKey);
2328 assert(ret); // should never fail, as we just unlocked
6a86c24d 2329
0be990ba 2330 scriptChange = GetScriptForDestination(vchPubKey.GetID());
6a86c24d 2331 }
e8ef3da7 2332
8de9bb53
GA
2333 CTxOut newTxOut(nChange, scriptChange);
2334
292623ad
CL
2335 // We do not move dust-change to fees, because the sender would end up paying more than requested.
2336 // This would be against the purpose of the all-inclusive feature.
2337 // So instead we raise the change and deduct from the recipient.
2338 if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust(::minRelayTxFee))
2339 {
2340 CAmount nDust = newTxOut.GetDustThreshold(::minRelayTxFee) - newTxOut.nValue;
2341 newTxOut.nValue += nDust; // raise change until no more dust
2342 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
2343 {
2344 if (vecSend[i].fSubtractFeeFromAmount)
2345 {
2346 txNew.vout[i].nValue -= nDust;
2347 if (txNew.vout[i].IsDust(::minRelayTxFee))
2348 {
2349 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2350 return false;
2351 }
2352 break;
2353 }
2354 }
2355 }
2356
8de9bb53
GA
2357 // Never create dust outputs; if we would, just
2358 // add the dust to the fee.
13fc83c7 2359 if (newTxOut.IsDust(::minRelayTxFee))
8de9bb53
GA
2360 {
2361 nFeeRet += nChange;
2362 reservekey.ReturnKey();
2363 }
2364 else
2365 {
2366 // Insert change txn at random position:
292623ad
CL
2367 nChangePosRet = GetRandInt(txNew.vout.size()+1);
2368 vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosRet;
4949004d 2369 txNew.vout.insert(position, newTxOut);
8de9bb53 2370 }
e8ef3da7
WL
2371 }
2372 else
2373 reservekey.ReturnKey();
2374
2375 // Fill vin
ba7fcc8d
PT
2376 //
2377 // Note how the sequence number is set to max()-1 so that the
2378 // nLockTime set above actually works.
e8ef3da7 2379 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
805344dc 2380 txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
ba7fcc8d 2381 std::numeric_limits<unsigned int>::max()-1));
e8ef3da7
WL
2382
2383 // Sign
2384 int nIn = 0;
2385 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
4949004d 2386 if (!SignSignature(*this, *coin.first, txNew, nIn++))
1f00f4e9
GA
2387 {
2388 strFailReason = _("Signing transaction failed");
e8ef3da7 2389 return false;
1f00f4e9 2390 }
e8ef3da7 2391
4949004d
PW
2392 // Embed the constructed transaction data in wtxNew.
2393 *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
2394
e8ef3da7 2395 // Limit size
6b6aaa16 2396 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
41e1a0d7 2397 if (nBytes >= MAX_STANDARD_TX_SIZE)
1f00f4e9
GA
2398 {
2399 strFailReason = _("Transaction too large");
e8ef3da7 2400 return false;
1f00f4e9 2401 }
4d707d51 2402 dPriority = wtxNew.ComputePriority(dPriority, nBytes);
e8ef3da7 2403
aa279d61
GM
2404 // Can we complete this as a free transaction?
2405 if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
2406 {
2407 // Not enough fee: enough priority?
2408 double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
2409 // Not enough mempool history to estimate: use hard-coded AllowFree.
2410 if (dPriorityNeeded <= 0 && AllowFree(dPriority))
2411 break;
2412
2413 // Small enough, and priority high enough, to send for free
2414 if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
2415 break;
2416 }
b33d1f5e 2417
aa279d61 2418 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
b33d1f5e 2419
aa279d61
GM
2420 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2421 // because we must be at the maximum allowed fee.
2422 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
e8ef3da7 2423 {
aa279d61
GM
2424 strFailReason = _("Transaction too large for fee policy");
2425 return false;
e8ef3da7
WL
2426 }
2427
aa279d61
GM
2428 if (nFeeRet >= nFeeNeeded)
2429 break; // Done, enough fee included.
b33d1f5e
GA
2430
2431 // Include more fee and try again.
2432 nFeeRet = nFeeNeeded;
2433 continue;
e8ef3da7
WL
2434 }
2435 }
2436 }
e8ef3da7 2437
292623ad 2438 return true;
e8ef3da7
WL
2439}
2440
5b40d886
MF
2441/**
2442 * Call after CreateTransaction unless you want to abort
2443 */
e8ef3da7
WL
2444bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2445{
e8ef3da7 2446 {
f8dcd5ca 2447 LOCK2(cs_main, cs_wallet);
7d9d134b 2448 LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
e8ef3da7
WL
2449 {
2450 // This is only to keep the database open to defeat the auto-flush for the
2451 // duration of this scope. This is the only place where this optimization
2452 // maybe makes sense; please don't do it anywhere else.
44bc988e 2453 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r+") : NULL;
e8ef3da7
WL
2454
2455 // Take key pair from key pool so it won't be used again
2456 reservekey.KeepKey();
2457
2458 // Add tx to wallet, because if it has change it's also ours,
2459 // otherwise just for transaction history.
44bc988e 2460 AddToWallet(wtxNew, false, pwalletdb);
e8ef3da7 2461
93a18a36 2462 // Notify that old coins are spent
e8ef3da7
WL
2463 set<CWalletTx*> setCoins;
2464 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2465 {
2466 CWalletTx &coin = mapWallet[txin.prevout.hash];
4c6e2295 2467 coin.BindWallet(this);
805344dc 2468 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
e8ef3da7
WL
2469 }
2470
2471 if (fFileBacked)
2472 delete pwalletdb;
2473 }
2474
2475 // Track how many getdata requests our transaction gets
805344dc 2476 mapRequestCount[wtxNew.GetHash()] = 0;
e8ef3da7 2477
6f252627 2478 if (fBroadcastTransactions)
e8ef3da7 2479 {
6f252627
WL
2480 // Broadcast
2481 if (!wtxNew.AcceptToMemoryPool(false))
2482 {
2483 // This must not fail. The transaction has already been signed and recorded.
7ff9d122 2484 LogPrintf("CommitTransaction(): Error: Transaction not valid\n");
6f252627
WL
2485 return false;
2486 }
2487 wtxNew.RelayWalletTransaction();
e8ef3da7 2488 }
e8ef3da7 2489 }
e8ef3da7
WL
2490 return true;
2491}
2492
a372168e 2493CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
b33d1f5e
GA
2494{
2495 // payTxFee is user-set "I want to pay this much"
a372168e 2496 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
c1c9d5b4
CL
2497 // user selected total at least (default=true)
2498 if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
2499 nFeeNeeded = payTxFee.GetFeePerK();
b33d1f5e
GA
2500 // User didn't set: use -txconfirmtarget to estimate...
2501 if (nFeeNeeded == 0)
2502 nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
2503 // ... unless we don't have enough mempool data, in which case fall
2504 // back to a hard-coded fee
2505 if (nFeeNeeded == 0)
13fc83c7 2506 nFeeNeeded = minTxFee.GetFee(nTxBytes);
aa279d61
GM
2507 // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
2508 if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
2509 nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
2510 // But always obey the maximum
2511 if (nFeeNeeded > maxTxFee)
2512 nFeeNeeded = maxTxFee;
b33d1f5e
GA
2513 return nFeeNeeded;
2514}
2515
e8ef3da7
WL
2516
2517
2518
eed1785f 2519DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
e8ef3da7
WL
2520{
2521 if (!fFileBacked)
4f76be1d 2522 return DB_LOAD_OK;
e8ef3da7 2523 fFirstRunRet = false;
eed1785f 2524 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
d764d916 2525 if (nLoadWalletRet == DB_NEED_REWRITE)
9e9869d0 2526 {
d764d916
GA
2527 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2528 {
012ca1c9 2529 LOCK(cs_wallet);
d764d916
GA
2530 setKeyPool.clear();
2531 // Note: can't top-up keypool here, because wallet is locked.
2532 // User will be prompted to unlock wallet the next operation
c6de7c35 2533 // that requires a new key.
d764d916 2534 }
9e9869d0
PW
2535 }
2536
7ec55267
MC
2537 if (nLoadWalletRet != DB_LOAD_OK)
2538 return nLoadWalletRet;
fd61d6f5 2539 fFirstRunRet = !vchDefaultKey.IsValid();
e8ef3da7 2540
39278369
CL
2541 uiInterface.LoadWallet(this);
2542
116df55e 2543 return DB_LOAD_OK;
e8ef3da7
WL
2544}
2545
ae3d0aba 2546
77cbd462 2547DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
518f3bda
JG
2548{
2549 if (!fFileBacked)
2550 return DB_LOAD_OK;
77cbd462 2551 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
518f3bda
JG
2552 if (nZapWalletTxRet == DB_NEED_REWRITE)
2553 {
2554 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2555 {
2556 LOCK(cs_wallet);
2557 setKeyPool.clear();
2558 // Note: can't top-up keypool here, because wallet is locked.
2559 // User will be prompted to unlock wallet the next operation
5b40d886 2560 // that requires a new key.
518f3bda
JG
2561 }
2562 }
2563
2564 if (nZapWalletTxRet != DB_LOAD_OK)
2565 return nZapWalletTxRet;
2566
2567 return DB_LOAD_OK;
2568}
2569
2570
a41d5fe0 2571bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
ae3d0aba 2572{
ca4cf5cf
GA
2573 bool fUpdated = false;
2574 {
2575 LOCK(cs_wallet); // mapAddressBook
2576 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
2577 fUpdated = mi != mapAddressBook.end();
2578 mapAddressBook[address].name = strName;
2579 if (!strPurpose.empty()) /* update purpose only if requested */
2580 mapAddressBook[address].purpose = strPurpose;
2581 }
8d657a65 2582 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
ca4cf5cf 2583 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
ae3d0aba
WL
2584 if (!fFileBacked)
2585 return false;
a41d5fe0
GA
2586 if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
2587 return false;
10254401 2588 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
ae3d0aba
WL
2589}
2590
a41d5fe0 2591bool CWallet::DelAddressBook(const CTxDestination& address)
ae3d0aba 2592{
b10e1470 2593 {
ca4cf5cf
GA
2594 LOCK(cs_wallet); // mapAddressBook
2595
2596 if(fFileBacked)
b10e1470 2597 {
ca4cf5cf
GA
2598 // Delete destdata tuples associated with address
2599 std::string strAddress = CBitcoinAddress(address).ToString();
2600 BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
2601 {
2602 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
2603 }
b10e1470 2604 }
ca4cf5cf 2605 mapAddressBook.erase(address);
b10e1470
WL
2606 }
2607
8d657a65 2608 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
ca4cf5cf 2609
ae3d0aba
WL
2610 if (!fFileBacked)
2611 return false;
a41d5fe0 2612 CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
10254401 2613 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
ae3d0aba
WL
2614}
2615
fd61d6f5 2616bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
ae3d0aba
WL
2617{
2618 if (fFileBacked)
2619 {
2620 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2621 return false;
2622 }
2623 vchDefaultKey = vchPubKey;
2624 return true;
2625}
2626
5b40d886
MF
2627/**
2628 * Mark old keypool keys as used,
2629 * and generate all new keys
2630 */
37971fcc
GA
2631bool CWallet::NewKeyPool()
2632{
37971fcc 2633 {
f8dcd5ca 2634 LOCK(cs_wallet);
37971fcc 2635 CWalletDB walletdb(strWalletFile);
51ed9ec9 2636 BOOST_FOREACH(int64_t nIndex, setKeyPool)
37971fcc
GA
2637 walletdb.ErasePool(nIndex);
2638 setKeyPool.clear();
2639
2640 if (IsLocked())
2641 return false;
2642
51ed9ec9 2643 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
37971fcc
GA
2644 for (int i = 0; i < nKeys; i++)
2645 {
51ed9ec9 2646 int64_t nIndex = i+1;
37971fcc
GA
2647 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2648 setKeyPool.insert(nIndex);
2649 }
f48742c2 2650 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
37971fcc
GA
2651 }
2652 return true;
2653}
2654
13dd2d09 2655bool CWallet::TopUpKeyPool(unsigned int kpSize)
e8ef3da7 2656{
e8ef3da7 2657 {
f8dcd5ca
PW
2658 LOCK(cs_wallet);
2659
4e87d341
MC
2660 if (IsLocked())
2661 return false;
2662
e8ef3da7
WL
2663 CWalletDB walletdb(strWalletFile);
2664
2665 // Top up key pool
13dd2d09
JG
2666 unsigned int nTargetSize;
2667 if (kpSize > 0)
2668 nTargetSize = kpSize;
2669 else
51ed9ec9 2670 nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0);
13dd2d09 2671
faf705a4 2672 while (setKeyPool.size() < (nTargetSize + 1))
e8ef3da7 2673 {
51ed9ec9 2674 int64_t nEnd = 1;
e8ef3da7
WL
2675 if (!setKeyPool.empty())
2676 nEnd = *(--setKeyPool.end()) + 1;
2677 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
5262fde0 2678 throw runtime_error("TopUpKeyPool(): writing generated key failed");
e8ef3da7 2679 setKeyPool.insert(nEnd);
783b182c 2680 LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
e8ef3da7 2681 }
4e87d341
MC
2682 }
2683 return true;
2684}
2685
51ed9ec9 2686void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
4e87d341
MC
2687{
2688 nIndex = -1;
fd61d6f5 2689 keypool.vchPubKey = CPubKey();
4e87d341 2690 {
f8dcd5ca
PW
2691 LOCK(cs_wallet);
2692
4e87d341
MC
2693 if (!IsLocked())
2694 TopUpKeyPool();
e8ef3da7
WL
2695
2696 // Get the oldest key
4e87d341
MC
2697 if(setKeyPool.empty())
2698 return;
2699
2700 CWalletDB walletdb(strWalletFile);
2701
e8ef3da7
WL
2702 nIndex = *(setKeyPool.begin());
2703 setKeyPool.erase(setKeyPool.begin());
2704 if (!walletdb.ReadPool(nIndex, keypool))
5262fde0 2705 throw runtime_error("ReserveKeyFromKeyPool(): read failed");
fd61d6f5 2706 if (!HaveKey(keypool.vchPubKey.GetID()))
5262fde0 2707 throw runtime_error("ReserveKeyFromKeyPool(): unknown key in key pool");
fd61d6f5 2708 assert(keypool.vchPubKey.IsValid());
f48742c2 2709 LogPrintf("keypool reserve %d\n", nIndex);
e8ef3da7
WL
2710 }
2711}
2712
51ed9ec9 2713void CWallet::KeepKey(int64_t nIndex)
e8ef3da7
WL
2714{
2715 // Remove from key pool
2716 if (fFileBacked)
2717 {
2718 CWalletDB walletdb(strWalletFile);
6cc4a62c 2719 walletdb.ErasePool(nIndex);
e8ef3da7 2720 }
f48742c2 2721 LogPrintf("keypool keep %d\n", nIndex);
e8ef3da7
WL
2722}
2723
51ed9ec9 2724void CWallet::ReturnKey(int64_t nIndex)
e8ef3da7
WL
2725{
2726 // Return to key pool
f8dcd5ca
PW
2727 {
2728 LOCK(cs_wallet);
e8ef3da7 2729 setKeyPool.insert(nIndex);
f8dcd5ca 2730 }
f48742c2 2731 LogPrintf("keypool return %d\n", nIndex);
e8ef3da7
WL
2732}
2733
71ac5052 2734bool CWallet::GetKeyFromPool(CPubKey& result)
e8ef3da7 2735{
51ed9ec9 2736 int64_t nIndex = 0;
e8ef3da7 2737 CKeyPool keypool;
7db3b75b 2738 {
f8dcd5ca 2739 LOCK(cs_wallet);
ed02c95d
GA
2740 ReserveKeyFromKeyPool(nIndex, keypool);
2741 if (nIndex == -1)
7db3b75b 2742 {
ed02c95d
GA
2743 if (IsLocked()) return false;
2744 result = GenerateNewKey();
7db3b75b
GA
2745 return true;
2746 }
ed02c95d
GA
2747 KeepKey(nIndex);
2748 result = keypool.vchPubKey;
7db3b75b 2749 }
7db3b75b 2750 return true;
e8ef3da7
WL
2751}
2752
51ed9ec9 2753int64_t CWallet::GetOldestKeyPoolTime()
e8ef3da7 2754{
51ed9ec9 2755 int64_t nIndex = 0;
e8ef3da7
WL
2756 CKeyPool keypool;
2757 ReserveKeyFromKeyPool(nIndex, keypool);
4e87d341
MC
2758 if (nIndex == -1)
2759 return GetTime();
e8ef3da7
WL
2760 ReturnKey(nIndex);
2761 return keypool.nTime;
2762}
2763
a372168e 2764std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
22dfd735 2765{
a372168e 2766 map<CTxDestination, CAmount> balances;
22dfd735 2767
2768 {
2769 LOCK(cs_wallet);
2770 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2771 {
2772 CWalletTx *pcoin = &walletEntry.second;
2773
75a4d512 2774 if (!CheckFinalTx(*pcoin) || !pcoin->IsTrusted())
22dfd735 2775 continue;
2776
2777 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2778 continue;
2779
2780 int nDepth = pcoin->GetDepthInMainChain();
a3e192a3 2781 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
22dfd735 2782 continue;
2783
b1093efa 2784 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
22dfd735 2785 {
b1093efa 2786 CTxDestination addr;
22dfd735 2787 if (!IsMine(pcoin->vout[i]))
2788 continue;
b1093efa
GM
2789 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2790 continue;
22dfd735 2791
a372168e 2792 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
22dfd735 2793
22dfd735 2794 if (!balances.count(addr))
2795 balances[addr] = 0;
2796 balances[addr] += n;
2797 }
2798 }
2799 }
2800
2801 return balances;
2802}
2803
b1093efa 2804set< set<CTxDestination> > CWallet::GetAddressGroupings()
22dfd735 2805{
95691680 2806 AssertLockHeld(cs_wallet); // mapWallet
b1093efa
GM
2807 set< set<CTxDestination> > groupings;
2808 set<CTxDestination> grouping;
22dfd735 2809
2810 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2811 {
2812 CWalletTx *pcoin = &walletEntry.second;
2813
a3fad211 2814 if (pcoin->vin.size() > 0)
22dfd735 2815 {
a3fad211 2816 bool any_mine = false;
22dfd735 2817 // group all input addresses with each other
2818 BOOST_FOREACH(CTxIn txin, pcoin->vin)
b1093efa
GM
2819 {
2820 CTxDestination address;
a3fad211
GM
2821 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
2822 continue;
b1093efa
GM
2823 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2824 continue;
2825 grouping.insert(address);
a3fad211 2826 any_mine = true;
b1093efa 2827 }
22dfd735 2828
2829 // group change with input addresses
a3fad211
GM
2830 if (any_mine)
2831 {
2832 BOOST_FOREACH(CTxOut txout, pcoin->vout)
2833 if (IsChange(txout))
2834 {
2835 CTxDestination txoutAddr;
2836 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2837 continue;
2838 grouping.insert(txoutAddr);
2839 }
2840 }
2841 if (grouping.size() > 0)
2842 {
2843 groupings.insert(grouping);
2844 grouping.clear();
2845 }
22dfd735 2846 }
2847
2848 // group lone addrs by themselves
b1093efa 2849 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
22dfd735 2850 if (IsMine(pcoin->vout[i]))
2851 {
b1093efa
GM
2852 CTxDestination address;
2853 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2854 continue;
2855 grouping.insert(address);
22dfd735 2856 groupings.insert(grouping);
2857 grouping.clear();
2858 }
2859 }
2860
b1093efa
GM
2861 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2862 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
2863 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
22dfd735 2864 {
2865 // make a set of all the groups hit by this new group
b1093efa
GM
2866 set< set<CTxDestination>* > hits;
2867 map< CTxDestination, set<CTxDestination>* >::iterator it;
2868 BOOST_FOREACH(CTxDestination address, grouping)
22dfd735 2869 if ((it = setmap.find(address)) != setmap.end())
2870 hits.insert((*it).second);
2871
2872 // merge all hit groups into a new single group and delete old groups
b1093efa
GM
2873 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2874 BOOST_FOREACH(set<CTxDestination>* hit, hits)
22dfd735 2875 {
2876 merged->insert(hit->begin(), hit->end());
2877 uniqueGroupings.erase(hit);
2878 delete hit;
2879 }
2880 uniqueGroupings.insert(merged);
2881
2882 // update setmap
b1093efa 2883 BOOST_FOREACH(CTxDestination element, *merged)
22dfd735 2884 setmap[element] = merged;
2885 }
2886
b1093efa
GM
2887 set< set<CTxDestination> > ret;
2888 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
22dfd735 2889 {
2890 ret.insert(*uniqueGrouping);
2891 delete uniqueGrouping;
2892 }
2893
2894 return ret;
2895}
2896
3624356e
GA
2897set<CTxDestination> CWallet::GetAccountAddresses(string strAccount) const
2898{
43422a01 2899 LOCK(cs_wallet);
3624356e
GA
2900 set<CTxDestination> result;
2901 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
2902 {
2903 const CTxDestination& address = item.first;
2904 const string& strName = item.second.name;
2905 if (strName == strAccount)
2906 result.insert(address);
2907 }
2908 return result;
2909}
2910
360cfe14 2911bool CReserveKey::GetReservedKey(CPubKey& pubkey)
e8ef3da7
WL
2912{
2913 if (nIndex == -1)
2914 {
2915 CKeyPool keypool;
2916 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
0d7b28e5
MC
2917 if (nIndex != -1)
2918 vchPubKey = keypool.vchPubKey;
360cfe14 2919 else {
6c37f7fd 2920 return false;
cee69980 2921 }
e8ef3da7 2922 }
fd61d6f5 2923 assert(vchPubKey.IsValid());
360cfe14
PW
2924 pubkey = vchPubKey;
2925 return true;
e8ef3da7
WL
2926}
2927
2928void CReserveKey::KeepKey()
2929{
2930 if (nIndex != -1)
2931 pwallet->KeepKey(nIndex);
2932 nIndex = -1;
fd61d6f5 2933 vchPubKey = CPubKey();
e8ef3da7
WL
2934}
2935
2936void CReserveKey::ReturnKey()
2937{
2938 if (nIndex != -1)
2939 pwallet->ReturnKey(nIndex);
2940 nIndex = -1;
fd61d6f5 2941 vchPubKey = CPubKey();
e8ef3da7 2942}
ae3d0aba 2943
434e4273 2944void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
30ab2c9c
PW
2945{
2946 setAddress.clear();
2947
2948 CWalletDB walletdb(strWalletFile);
2949
f8dcd5ca 2950 LOCK2(cs_main, cs_wallet);
51ed9ec9 2951 BOOST_FOREACH(const int64_t& id, setKeyPool)
30ab2c9c
PW
2952 {
2953 CKeyPool keypool;
2954 if (!walletdb.ReadPool(id, keypool))
5262fde0 2955 throw runtime_error("GetAllReserveKeyHashes(): read failed");
fd61d6f5 2956 assert(keypool.vchPubKey.IsValid());
10254401
PW
2957 CKeyID keyID = keypool.vchPubKey.GetID();
2958 if (!HaveKey(keyID))
5262fde0 2959 throw runtime_error("GetAllReserveKeyHashes(): unknown key in key pool");
10254401 2960 setAddress.insert(keyID);
30ab2c9c
PW
2961 }
2962}
fe4a6550
WL
2963
2964void CWallet::UpdatedTransaction(const uint256 &hashTx)
2965{
2966 {
2967 LOCK(cs_wallet);
2968 // Only notify UI if this transaction is in this wallet
2969 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2970 if (mi != mapWallet.end())
2971 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2972 }
2973}
fdbb537d
JG
2974
2975void CWallet::LockCoin(COutPoint& output)
2976{
95691680 2977 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
2978 setLockedCoins.insert(output);
2979}
2980
2981void CWallet::UnlockCoin(COutPoint& output)
2982{
95691680 2983 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
2984 setLockedCoins.erase(output);
2985}
2986
2987void CWallet::UnlockAllCoins()
2988{
95691680 2989 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
2990 setLockedCoins.clear();
2991}
2992
2993bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
2994{
95691680 2995 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
2996 COutPoint outpt(hash, n);
2997
2998 return (setLockedCoins.count(outpt) > 0);
2999}
3000
3001void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
3002{
95691680 3003 AssertLockHeld(cs_wallet); // setLockedCoins
fdbb537d
JG
3004 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3005 it != setLockedCoins.end(); it++) {
3006 COutPoint outpt = (*it);
3007 vOutpts.push_back(outpt);
3008 }
3009}
3010
5b40d886 3011/** @} */ // end of Actions
8b59a3d3 3012
3013class CAffectedKeysVisitor : public boost::static_visitor<void> {
3014private:
3015 const CKeyStore &keystore;
3016 std::vector<CKeyID> &vKeys;
3017
3018public:
3019 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
3020
3021 void Process(const CScript &script) {
3022 txnouttype type;
3023 std::vector<CTxDestination> vDest;
3024 int nRequired;
3025 if (ExtractDestinations(script, type, vDest, nRequired)) {
3026 BOOST_FOREACH(const CTxDestination &dest, vDest)
3027 boost::apply_visitor(*this, dest);
3028 }
3029 }
3030
3031 void operator()(const CKeyID &keyId) {
3032 if (keystore.HaveKey(keyId))
3033 vKeys.push_back(keyId);
3034 }
3035
3036 void operator()(const CScriptID &scriptId) {
3037 CScript script;
3038 if (keystore.GetCScript(scriptId, script))
3039 Process(script);
3040 }
3041
3042 void operator()(const CNoDestination &none) {}
3043};
3044
51ed9ec9 3045void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
95691680 3046 AssertLockHeld(cs_wallet); // mapKeyMetadata
434e4273
PW
3047 mapKeyBirth.clear();
3048
3049 // get birth times for keys with metadata
3050 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
3051 if (it->second.nCreateTime)
3052 mapKeyBirth[it->first] = it->second.nCreateTime;
3053
3054 // map in which we'll infer heights of other keys
4c6d41b8 3055 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
434e4273
PW
3056 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3057 std::set<CKeyID> setKeys;
3058 GetKeys(setKeys);
3059 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
3060 if (mapKeyBirth.count(keyid) == 0)
3061 mapKeyFirstBlock[keyid] = pindexMax;
3062 }
3063 setKeys.clear();
3064
3065 // if there are no such keys, we're done
3066 if (mapKeyFirstBlock.empty())
3067 return;
3068
3069 // find first block that affects those keys, if there are any left
3070 std::vector<CKeyID> vAffected;
3071 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3072 // iterate over all wallet transactions...
3073 const CWalletTx &wtx = (*it).second;
145d5be8 3074 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
4c6d41b8 3075 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
434e4273
PW
3076 // ... which are already in a block
3077 int nHeight = blit->second->nHeight;
3078 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
3079 // iterate over all their outputs
8b59a3d3 3080 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
434e4273
PW
3081 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
3082 // ... and all their affected keys
3083 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3084 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3085 rit->second = blit->second;
3086 }
3087 vAffected.clear();
3088 }
3089 }
3090 }
3091
3092 // Extract block timestamps for those keys
3093 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
209377a7 3094 mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
434e4273 3095}
b10e1470
WL
3096
3097bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3098{
8476d5d4
CL
3099 if (boost::get<CNoDestination>(&dest))
3100 return false;
3101
b10e1470
WL
3102 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3103 if (!fFileBacked)
3104 return true;
3105 return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3106}
3107
3108bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3109{
3110 if (!mapAddressBook[dest].destdata.erase(key))
3111 return false;
3112 if (!fFileBacked)
3113 return true;
3114 return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3115}
3116
3117bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3118{
3119 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3120 return true;
3121}
3122
3123bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3124{
3125 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3126 if(i != mapAddressBook.end())
3127 {
3128 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3129 if(j != i->second.destdata.end())
3130 {
3131 if(value)
3132 *value = j->second;
3133 return true;
3134 }
3135 }
3136 return false;
3137}
af8297c0
WL
3138
3139CKeyPool::CKeyPool()
3140{
3141 nTime = GetTime();
3142}
3143
3144CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
3145{
3146 nTime = GetTime();
3147 vchPubKey = vchPubKeyIn;
3148}
3149
3150CWalletKey::CWalletKey(int64_t nExpires)
3151{
3152 nTimeCreated = (nExpires ? GetTime() : 0);
3153 nTimeExpires = nExpires;
3154}
0101483f 3155
4b0deb3b 3156int CMerkleTx::SetMerkleBranch(const CBlock& block)
0101483f
WL
3157{
3158 AssertLockHeld(cs_main);
3159 CBlock blockTmp;
3160
4b0deb3b
DK
3161 // Update the tx's hashBlock
3162 hashBlock = block.GetHash();
0101483f 3163
4b0deb3b
DK
3164 // Locate the transaction
3165 for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
3166 if (block.vtx[nIndex] == *(CTransaction*)this)
3167 break;
3168 if (nIndex == (int)block.vtx.size())
3169 {
3170 vMerkleBranch.clear();
3171 nIndex = -1;
5262fde0 3172 LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
4b0deb3b 3173 return 0;
0101483f
WL
3174 }
3175
4b0deb3b
DK
3176 // Fill in merkle branch
3177 vMerkleBranch = block.GetMerkleBranch(nIndex);
3178
0101483f 3179 // Is the tx in a block that's in the main chain
145d5be8 3180 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
0101483f
WL
3181 if (mi == mapBlockIndex.end())
3182 return 0;
4b0deb3b 3183 const CBlockIndex* pindex = (*mi).second;
0101483f
WL
3184 if (!pindex || !chainActive.Contains(pindex))
3185 return 0;
3186
3187 return chainActive.Height() - pindex->nHeight + 1;
3188}
3189
a31e8bad 3190int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const
0101483f 3191{
4f152496 3192 if (hashBlock.IsNull() || nIndex == -1)
0101483f
WL
3193 return 0;
3194 AssertLockHeld(cs_main);
3195
3196 // Find the block it claims to be in
145d5be8 3197 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
0101483f
WL
3198 if (mi == mapBlockIndex.end())
3199 return 0;
3200 CBlockIndex* pindex = (*mi).second;
3201 if (!pindex || !chainActive.Contains(pindex))
3202 return 0;
3203
3204 // Make sure the merkle branch connects to this block
3205 if (!fMerkleVerified)
3206 {
805344dc 3207 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
0101483f
WL
3208 return 0;
3209 fMerkleVerified = true;
3210 }
3211
3212 pindexRet = pindex;
3213 return chainActive.Height() - pindex->nHeight + 1;
3214}
3215
a31e8bad 3216int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
0101483f
WL
3217{
3218 AssertLockHeld(cs_main);
3219 int nResult = GetDepthInMainChainINTERNAL(pindexRet);
805344dc 3220 if (nResult == 0 && !mempool.exists(GetHash()))
0101483f
WL
3221 return -1; // Not in chain, not in mempool
3222
3223 return nResult;
3224}
3225
3226int CMerkleTx::GetBlocksToMaturity() const
3227{
3228 if (!IsCoinBase())
3229 return 0;
3230 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
3231}
3232
3233
1371e6f5 3234bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectAbsurdFee)
0101483f
WL
3235{
3236 CValidationState state;
1371e6f5 3237 return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectAbsurdFee);
0101483f
WL
3238}
3239
dec49d1f 3240bool CWallet::GetFilteredNotes(std::vector<CNotePlaintextEntry> & outEntries, std::string address, int minDepth, bool ignoreSpent)
a5ac2e25
S
3241{
3242 bool fFilterAddress = false;
3243 libzcash::PaymentAddress filterPaymentAddress;
3244 if (address.length() > 0) {
3245 filterPaymentAddress = CZCPaymentAddress(address).Get();
3246 fFilterAddress = true;
3247 }
3248
3249 LOCK2(cs_main, cs_wallet);
3250
3251 for (auto & p : mapWallet) {
3252 CWalletTx wtx = p.second;
3253
3254 // Filter the transactions before checking for notes
3255 if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < minDepth) {
3256 continue;
3257 }
3258
dec49d1f 3259 if (wtx.mapNoteData.size() == 0) {
a5ac2e25
S
3260 continue;
3261 }
3262
dec49d1f 3263 for (auto & pair : wtx.mapNoteData) {
a5ac2e25
S
3264 JSOutPoint jsop = pair.first;
3265 CNoteData nd = pair.second;
3266 PaymentAddress pa = nd.address;
3267
3268 // skip notes which belong to a different payment address in the wallet
3269 if (fFilterAddress && !(pa == filterPaymentAddress)) {
3270 continue;
3271 }
3272
3273 // skip note which has been spent
1b141933 3274 if (ignoreSpent && IsSpent(nd.nullifier)) {
a5ac2e25
S
3275 continue;
3276 }
3277
3278 int i = jsop.js; // Index into CTransaction.vjoinsplit
3279 int j = jsop.n; // Index into JSDescription.ciphertexts
3280
3281 // Get cached decryptor
3282 ZCNoteDecryption decryptor;
3283 if (!GetNoteDecryptor(pa, decryptor)) {
3284 // Note decryptors are created when the wallet is loaded, so it should always exist
3285 throw std::runtime_error(strprintf("Could not find note decryptor for payment address %s", CZCPaymentAddress(pa).ToString()));
3286 }
3287
3288 // determine amount of funds in the note
3289 auto hSig = wtx.vjoinsplit[i].h_sig(*pzcashParams, wtx.joinSplitPubKey);
3290 try {
3291 NotePlaintext plaintext = NotePlaintext::decrypt(
3292 decryptor,
3293 wtx.vjoinsplit[i].ciphertexts[j],
3294 wtx.vjoinsplit[i].ephemeralKey,
3295 hSig,
3296 (unsigned char) j);
3297
3298 outEntries.push_back(CNotePlaintextEntry{jsop, plaintext});
3299
3300 } catch (const std::exception &) {
3301 // Couldn't decrypt with this spending key
3302 throw std::runtime_error(strprintf("Could not decrypt note for payment address %s", CZCPaymentAddress(pa).ToString()));
3303 }
3304 }
3305 }
3306}
This page took 0.778234 seconds and 4 git commands to generate.