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