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