Line data Source code
1 : // Copyright (c) 2021 The Bitcoin Core developers
2 : // Distributed under the MIT software license, see the accompanying
3 : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 :
5 : #include <coinjoin/options.h>
6 : #include <consensus/consensus.h>
7 : #include <wallet/coinjoin.h>
8 : #include <wallet/receive.h>
9 : #include <wallet/transaction.h>
10 : #include <wallet/wallet.h>
11 :
12 : namespace wallet {
13 0 : isminetype InputIsMine(const CWallet& wallet, const CTxIn& txin)
14 : {
15 0 : AssertLockHeld(wallet.cs_wallet);
16 0 : const CWalletTx* prev = wallet.GetWalletTx(txin.prevout.hash);
17 0 : if (prev && txin.prevout.n < prev->tx->vout.size()) {
18 0 : return wallet.IsMine(prev->tx->vout[txin.prevout.n]);
19 : }
20 0 : return ISMINE_NO;
21 0 : }
22 :
23 0 : bool AllInputsMine(const CWallet& wallet, const CTransaction& tx, const isminefilter& filter)
24 : {
25 0 : LOCK(wallet.cs_wallet);
26 0 : for (const CTxIn& txin : tx.vin) {
27 0 : if (!(InputIsMine(wallet, txin) & filter)) return false;
28 : }
29 0 : return true;
30 0 : }
31 :
32 10 : CAmount OutputGetCredit(const CWallet& wallet, const CTxOut& txout, const isminefilter& filter)
33 : {
34 10 : if (!MoneyRange(txout.nValue))
35 0 : throw std::runtime_error(std::string(__func__) + ": value out of range");
36 10 : LOCK(wallet.cs_wallet);
37 10 : return ((wallet.IsMine(txout) & filter) ? txout.nValue : 0);
38 10 : }
39 :
40 8 : CAmount TxGetCredit(const CWallet& wallet, const CTransaction& tx, const isminefilter& filter)
41 : {
42 8 : CAmount nCredit = 0;
43 16 : for (const CTxOut& txout : tx.vout)
44 : {
45 8 : nCredit += OutputGetCredit(wallet, txout, filter);
46 8 : if (!MoneyRange(nCredit))
47 0 : throw std::runtime_error(std::string(__func__) + ": value out of range");
48 : }
49 8 : return nCredit;
50 0 : }
51 :
52 9 : bool ScriptIsChange(const CWallet& wallet, const CScript& script)
53 : {
54 : // TODO: fix handling of 'change' outputs. The assumption is that any
55 : // payment to a script that is ours, but is not in the address book
56 : // is change. That assumption is likely to break when we implement multisignature
57 : // wallets that return change back into a multi-signature-protected address;
58 : // a better way of identifying which outputs are 'the send' and which are
59 : // 'the change' will need to be implemented (maybe extend CWalletTx to remember
60 : // which output, if any, was change).
61 9 : AssertLockHeld(wallet.cs_wallet);
62 9 : if (wallet.IsMine(script))
63 : {
64 9 : CTxDestination address;
65 9 : if (!ExtractDestination(script, address))
66 0 : return true;
67 9 : if (!wallet.FindAddressBookEntry(address)) {
68 3 : return true;
69 : }
70 6 : }
71 6 : return false;
72 9 : }
73 :
74 7 : bool OutputIsChange(const CWallet& wallet, const CTxOut& txout)
75 : {
76 7 : return ScriptIsChange(wallet, txout.scriptPubKey);
77 : }
78 :
79 0 : CAmount OutputGetChange(const CWallet& wallet, const CTxOut& txout)
80 : {
81 0 : AssertLockHeld(wallet.cs_wallet);
82 0 : if (!MoneyRange(txout.nValue))
83 0 : throw std::runtime_error(std::string(__func__) + ": value out of range");
84 0 : return (OutputIsChange(wallet, txout) ? txout.nValue : 0);
85 0 : }
86 :
87 0 : CAmount TxGetChange(const CWallet& wallet, const CTransaction& tx)
88 : {
89 0 : LOCK(wallet.cs_wallet);
90 0 : CAmount nChange = 0;
91 0 : for (const CTxOut& txout : tx.vout)
92 : {
93 0 : nChange += OutputGetChange(wallet, txout);
94 0 : if (!MoneyRange(nChange))
95 0 : throw std::runtime_error(std::string(__func__) + ": value out of range");
96 : }
97 0 : return nChange;
98 0 : }
99 :
100 1127 : static CAmount GetCachableAmount(const CWallet& wallet, const CWalletTx& wtx, CWalletTx::AmountType type, const isminefilter& filter)
101 : {
102 1127 : auto& amount = wtx.m_amounts[type];
103 1127 : if (!amount.m_cached[filter]) {
104 75 : amount.Set(filter, type == CWalletTx::DEBIT ? wallet.GetDebit(*wtx.tx, filter) : TxGetCredit(wallet, *wtx.tx, filter));
105 75 : wtx.m_is_cache_empty = false;
106 75 : }
107 1127 : return amount.m_value[filter];
108 : }
109 :
110 0 : CAmount CachedTxGetCredit(const CWallet& wallet, const CWalletTx& wtx, const isminefilter& filter)
111 : {
112 0 : AssertLockHeld(wallet.cs_wallet);
113 :
114 : // Must wait until coinbase is safely deep enough in the chain before valuing it
115 0 : if (wallet.IsTxImmatureCoinBase(wtx))
116 0 : return 0;
117 :
118 0 : CAmount credit = 0;
119 0 : const isminefilter get_amount_filter{filter & ISMINE_ALL};
120 0 : if (get_amount_filter) {
121 : // GetBalance can assume transactions in mapWallet won't change
122 0 : credit += GetCachableAmount(wallet, wtx, CWalletTx::CREDIT, get_amount_filter);
123 0 : }
124 0 : return credit;
125 0 : }
126 :
127 1119 : CAmount CachedTxGetDebit(const CWallet& wallet, const CWalletTx& wtx, const isminefilter& filter)
128 : {
129 1119 : if (wtx.tx->vin.empty())
130 0 : return 0;
131 :
132 1119 : CAmount debit = 0;
133 1119 : const isminefilter get_amount_filter{filter & ISMINE_ALL};
134 1119 : if (get_amount_filter) {
135 1119 : debit += GetCachableAmount(wallet, wtx, CWalletTx::DEBIT, get_amount_filter);
136 1119 : }
137 1119 : return debit;
138 1119 : }
139 :
140 0 : CAmount CachedTxGetChange(const CWallet& wallet, const CWalletTx& wtx)
141 : {
142 0 : if (wtx.fChangeCached)
143 0 : return wtx.nChangeCached;
144 0 : wtx.nChangeCached = TxGetChange(wallet, *wtx.tx);
145 0 : wtx.fChangeCached = true;
146 0 : return wtx.nChangeCached;
147 0 : }
148 :
149 8 : CAmount CachedTxGetImmatureCredit(const CWallet& wallet, const CWalletTx& wtx, const isminefilter& filter)
150 : {
151 8 : AssertLockHeld(wallet.cs_wallet);
152 :
153 8 : if (wallet.IsTxImmatureCoinBase(wtx) && wallet.IsTxInMainChain(wtx)) {
154 8 : return GetCachableAmount(wallet, wtx, CWalletTx::IMMATURE_CREDIT, filter);
155 : }
156 :
157 0 : return 0;
158 8 : }
159 :
160 9 : CAmount CachedTxGetAvailableCredit(const CWallet& wallet, const CWalletTx& wtx, const isminefilter& filter)
161 : {
162 9 : AssertLockHeld(wallet.cs_wallet);
163 :
164 : // Avoid caching ismine for NO or ALL cases (could remove this check and simplify in the future).
165 9 : bool allow_cache = (filter & ISMINE_ALL) && (filter & ISMINE_ALL) != ISMINE_ALL;
166 :
167 : // Must wait until coinbase is safely deep enough in the chain before valuing it
168 9 : if (wallet.IsTxImmatureCoinBase(wtx))
169 6 : return 0;
170 :
171 3 : if (allow_cache && wtx.m_amounts[CWalletTx::AVAILABLE_CREDIT].m_cached[filter]) {
172 0 : return wtx.m_amounts[CWalletTx::AVAILABLE_CREDIT].m_value[filter];
173 : }
174 :
175 3 : bool allow_used_addresses = (filter & ISMINE_USED) || !wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE);
176 3 : CAmount nCredit = 0;
177 3 : uint256 hashTx = wtx.GetHash();
178 6 : for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
179 3 : const CTxOut& txout = wtx.tx->vout[i];
180 5 : if (!wallet.IsSpent(COutPoint(hashTx, i)) && (allow_used_addresses || !wallet.IsSpentKey(txout.scriptPubKey))) {
181 2 : nCredit += OutputGetCredit(wallet, txout, filter);
182 2 : if (!MoneyRange(nCredit))
183 0 : throw std::runtime_error(std::string(__func__) + ": value out of range");
184 2 : }
185 3 : }
186 :
187 3 : if (allow_cache) {
188 3 : wtx.m_amounts[CWalletTx::AVAILABLE_CREDIT].Set(filter, nCredit);
189 3 : wtx.m_is_cache_empty = false;
190 3 : }
191 :
192 3 : return nCredit;
193 9 : }
194 :
195 0 : void CachedTxGetAmounts(const CWallet& wallet, const CWalletTx& wtx,
196 : std::list<COutputEntry>& listReceived,
197 : std::list<COutputEntry>& listSent, CAmount& nFee, const isminefilter& filter)
198 : {
199 0 : nFee = 0;
200 0 : listReceived.clear();
201 0 : listSent.clear();
202 :
203 : // Compute fee:
204 0 : CAmount nDebit = CachedTxGetDebit(wallet, wtx, filter);
205 0 : if (nDebit > 0) // debit>0 means we signed/sent this transaction
206 : {
207 0 : CAmount nValueOut = wtx.tx->GetValueOut();
208 0 : nFee = nDebit - nValueOut;
209 0 : }
210 :
211 0 : LOCK(wallet.cs_wallet);
212 : // Sent/received.
213 0 : for (unsigned int i = 0; i < wtx.tx->vout.size(); ++i)
214 : {
215 0 : const CTxOut& txout = wtx.tx->vout[i];
216 0 : isminetype fIsMine = wallet.IsMine(txout);
217 : // Only need to handle txouts if AT LEAST one of these is true:
218 : // 1) they debit from us (sent)
219 : // 2) the output is to us (received)
220 0 : if (nDebit > 0)
221 : {
222 : // Don't report 'change' txouts
223 0 : if (OutputIsChange(wallet, txout))
224 0 : continue;
225 0 : }
226 0 : else if (!(fIsMine & filter))
227 0 : continue;
228 :
229 : // In either case, we need to get the destination address
230 0 : CTxDestination address;
231 :
232 0 : if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
233 : {
234 0 : wallet.WalletLogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
235 0 : wtx.GetHash().ToString());
236 0 : address = CNoDestination();
237 0 : }
238 :
239 0 : COutputEntry output = {address, txout.nValue, (int)i};
240 :
241 : // If we are debited by the transaction, add the output as a "sent" entry
242 0 : if (nDebit > 0)
243 0 : listSent.push_back(output);
244 :
245 : // If we are receiving the output, add it as a "received" entry
246 0 : if (fIsMine & filter)
247 0 : listReceived.push_back(output);
248 0 : }
249 :
250 0 : }
251 :
252 1119 : bool CachedTxIsFromMe(const CWallet& wallet, const CWalletTx& wtx, const isminefilter& filter)
253 : {
254 1119 : return (CachedTxGetDebit(wallet, wtx, filter) > 0);
255 : }
256 :
257 1121 : bool CachedTxIsTrusted(const CWallet& wallet, const CWalletTx& wtx, std::set<uint256>& trusted_parents)
258 : {
259 1121 : AssertLockHeld(wallet.cs_wallet);
260 1121 : int nDepth = wallet.GetTxDepthInMainChain(wtx);
261 1121 : if (nDepth >= 1) return true;
262 1 : if (nDepth < 0) return false;
263 0 : if (wallet.IsTxLockedByInstantSend(wtx)) return true;
264 : // using wtx's cached debit
265 0 : if (!wallet.m_spend_zero_conf_change || !CachedTxIsFromMe(wallet, wtx, ISMINE_ALL)) return false;
266 :
267 : // Don't trust unconfirmed transactions from us unless they are in the mempool.
268 0 : if (!wtx.InMempool()) return false;
269 :
270 : // Trusted if all inputs are from us and are in the mempool:
271 0 : for (const CTxIn& txin : wtx.tx->vin)
272 : {
273 : // Transactions not sent by us: not trusted
274 0 : const CWalletTx* parent = wallet.GetWalletTx(txin.prevout.hash);
275 0 : if (parent == nullptr) return false;
276 0 : const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
277 : // Check that this specific input being spent is trusted
278 0 : if (wallet.IsMine(parentOut) != ISMINE_SPENDABLE) return false;
279 : // If we've already trusted this parent, continue
280 0 : if (trusted_parents.count(parent->GetHash())) continue;
281 : // Recurse to check that the parent is also trusted
282 0 : if (!CachedTxIsTrusted(wallet, *parent, trusted_parents)) return false;
283 0 : trusted_parents.insert(parent->GetHash());
284 : }
285 0 : return true;
286 1121 : }
287 :
288 0 : bool CachedTxIsTrusted(const CWallet& wallet, const CWalletTx& wtx)
289 : {
290 0 : std::set<uint256> trusted_parents;
291 0 : LOCK(wallet.cs_wallet);
292 0 : return CachedTxIsTrusted(wallet, wtx, trusted_parents);
293 0 : }
294 :
295 4 : Balance GetBalance(const CWallet& wallet, const int min_depth, bool avoid_reuse, bool fAddLocked)
296 : {
297 4 : Balance ret;
298 4 : isminefilter reuse_filter = avoid_reuse ? ISMINE_NO : ISMINE_USED;
299 4 : const bool cj_enabled = CCoinJoinClientOptions::IsEnabled();
300 : {
301 4 : LOCK(wallet.cs_wallet);
302 4 : std::set<uint256> trusted_parents;
303 7 : for (const auto* pcoin : wallet.GetSpendableTXs()) {
304 3 : const auto& wtx{*pcoin};
305 :
306 3 : const bool is_trusted{CachedTxIsTrusted(wallet, wtx, trusted_parents)};
307 3 : const int tx_depth{wallet.GetTxDepthInMainChain(wtx)};
308 3 : const CAmount tx_credit_mine{CachedTxGetAvailableCredit(wallet, wtx, ISMINE_SPENDABLE | reuse_filter)};
309 3 : const CAmount tx_credit_watchonly{CachedTxGetAvailableCredit(wallet, wtx, ISMINE_WATCH_ONLY | reuse_filter)};
310 3 : if (is_trusted && ((tx_depth >= min_depth) || (fAddLocked && wallet.IsTxLockedByInstantSend(wtx)))) {
311 3 : ret.m_mine_trusted += tx_credit_mine;
312 3 : ret.m_watchonly_trusted += tx_credit_watchonly;
313 3 : }
314 3 : if (!is_trusted && tx_depth == 0 && wtx.InMempool()) {
315 0 : ret.m_mine_untrusted_pending += tx_credit_mine;
316 0 : ret.m_watchonly_untrusted_pending += tx_credit_watchonly;
317 0 : }
318 3 : ret.m_mine_immature += CachedTxGetImmatureCredit(wallet, wtx, ISMINE_SPENDABLE);
319 3 : ret.m_watchonly_immature += CachedTxGetImmatureCredit(wallet, wtx, ISMINE_WATCH_ONLY);
320 3 : if (cj_enabled) {
321 0 : const auto balance_anonymized = CachedTxGetAvailableCoinJoinCredits(wallet, wtx);
322 0 : ret.m_anonymized += balance_anonymized.m_anonymized;
323 0 : if (balance_anonymized.is_unconfirmed) {
324 0 : ret.m_denominated_untrusted_pending += balance_anonymized.m_denominated;
325 0 : } else {
326 0 : ret.m_denominated_trusted += balance_anonymized.m_denominated;
327 : }
328 0 : }
329 : }
330 4 : }
331 4 : return ret;
332 0 : }
333 :
334 0 : std::map<CTxDestination, CAmount> GetAddressBalances(const CWallet& wallet)
335 : {
336 0 : std::map<CTxDestination, CAmount> balances;
337 :
338 : {
339 0 : LOCK(wallet.cs_wallet);
340 0 : std::set<uint256> trusted_parents;
341 0 : for (const auto& walletEntry : wallet.mapWallet)
342 : {
343 0 : const CWalletTx& wtx = walletEntry.second;
344 :
345 0 : if (!CachedTxIsTrusted(wallet, wtx, trusted_parents))
346 0 : continue;
347 :
348 0 : if (wallet.IsTxImmatureCoinBase(wtx))
349 0 : continue;
350 :
351 0 : int nDepth = wallet.GetTxDepthInMainChain(wtx);
352 0 : if (nDepth < (CachedTxIsFromMe(wallet, wtx, ISMINE_ALL) ? 0 : 1) && !wallet.IsTxLockedByInstantSend(wtx))
353 0 : continue;
354 :
355 0 : for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
356 0 : const auto& output = wtx.tx->vout[i];
357 0 : CTxDestination addr;
358 0 : if (!wallet.IsMine(output))
359 0 : continue;
360 0 : if(!ExtractDestination(output.scriptPubKey, addr))
361 0 : continue;
362 :
363 0 : CAmount n = wallet.IsSpent(COutPoint(walletEntry.first, i)) ? 0 : output.nValue;
364 0 : balances[addr] += n;
365 0 : }
366 : }
367 0 : }
368 :
369 0 : return balances;
370 0 : }
371 :
372 0 : std::set< std::set<CTxDestination> > GetAddressGroupings(const CWallet& wallet)
373 : {
374 0 : AssertLockHeld(wallet.cs_wallet);
375 0 : std::set< std::set<CTxDestination> > groupings;
376 0 : std::set<CTxDestination> grouping;
377 :
378 0 : for (const auto& walletEntry : wallet.mapWallet)
379 : {
380 0 : const CWalletTx& wtx = walletEntry.second;
381 :
382 0 : if (wtx.tx->vin.size() > 0)
383 : {
384 0 : bool any_mine = false;
385 : // group all input addresses with each other
386 0 : for (const CTxIn& txin : wtx.tx->vin)
387 : {
388 0 : CTxDestination address;
389 0 : if(!InputIsMine(wallet, txin)) /* If this input isn't mine, ignore it */
390 0 : continue;
391 0 : if(!ExtractDestination(wallet.mapWallet.at(txin.prevout.hash).tx->vout[txin.prevout.n].scriptPubKey, address))
392 0 : continue;
393 0 : grouping.insert(address);
394 0 : any_mine = true;
395 : }
396 :
397 : // group change with input addresses
398 0 : if (any_mine)
399 : {
400 0 : for (const CTxOut& txout : wtx.tx->vout)
401 0 : if (OutputIsChange(wallet, txout))
402 : {
403 0 : CTxDestination txoutAddr;
404 0 : if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
405 0 : continue;
406 0 : grouping.insert(txoutAddr);
407 0 : }
408 0 : }
409 0 : if (grouping.size() > 0)
410 : {
411 0 : groupings.insert(grouping);
412 0 : grouping.clear();
413 0 : }
414 0 : }
415 :
416 : // group lone addrs by themselves
417 0 : for (const auto& txout : wtx.tx->vout)
418 0 : if (wallet.IsMine(txout))
419 : {
420 0 : CTxDestination address;
421 0 : if(!ExtractDestination(txout.scriptPubKey, address))
422 0 : continue;
423 0 : grouping.insert(address);
424 0 : groupings.insert(grouping);
425 0 : grouping.clear();
426 0 : }
427 : }
428 :
429 0 : std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
430 0 : std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
431 0 : for (const std::set<CTxDestination>& _grouping : groupings)
432 : {
433 : // make a set of all the groups hit by this new group
434 0 : std::set< std::set<CTxDestination>* > hits;
435 0 : std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
436 0 : for (const CTxDestination& address : _grouping)
437 0 : if ((it = setmap.find(address)) != setmap.end())
438 0 : hits.insert((*it).second);
439 :
440 : // merge all hit groups into a new single group and delete old groups
441 0 : std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
442 0 : for (std::set<CTxDestination>* hit : hits)
443 : {
444 0 : merged->insert(hit->begin(), hit->end());
445 0 : uniqueGroupings.erase(hit);
446 0 : delete hit;
447 : }
448 0 : uniqueGroupings.insert(merged);
449 :
450 : // update setmap
451 0 : for (const CTxDestination& element : *merged)
452 0 : setmap[element] = merged;
453 0 : }
454 :
455 0 : std::set< std::set<CTxDestination> > ret;
456 0 : for (const std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
457 : {
458 0 : ret.insert(*uniqueGrouping);
459 0 : delete uniqueGrouping;
460 : }
461 :
462 0 : return ret;
463 0 : }
464 : } // namespace wallet
|