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