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