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