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