mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 09:08:37 +00:00
wallet: fix mixed-input transaction accounting in history RPCs #34872
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!34872
Loading…
Reference in a new issue
No description provided.
Delete branch "wallet-mixed-input-history-only"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
When a wallet owns only some inputs of a transaction, such as in CoinJoins, payjoins, or other collaborative transactions, wallet history RPCs currently apply normal send accounting.
That works when all inputs are wallet-owned, but breaks for mixed-input transactions.
Example:
Inputs:
Outputs:
The wallet can safely know:
But it cannot reliably know, from wallet history alone, the foreign input value, the total fee, the wallet's fee share, or which non-wallet output should be attributed as the user's payment. This is especially important after restore, rescan, or descriptor import, where any local transaction-intent metadata may be missing.
This PR adds a conservative fallback for that no-metadata case:
sendentry with no address, novout, and no fee, carrying the negative total of wallet-owned inputs spentreceiveentries, so the transaction's entries sum to the wallet's net changeinvolves_mixed_inputs,wallet_debit, andwallet_creditvoutandfeeare optional when attribution is unavailableThis does not try to fully solve collaborative transaction attribution. A richer layer with foreign-output / fee-share / intent metadata would still be useful for wallet-created transactions. This PR only makes the fallback honest when that metadata is unavailable.
Addresses #14136
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
Reviewers, this pull request conflicts with the following ones:
InferScriptcreates invalid descriptors for invalid pubkeys by Eunovo)clang-tidyoptin.performance.Paddingby fanquake)If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.
This won't show even the true send anymore... not sure that's a good idea.
See #25991 for what is needed to fix this properly.
The goal here, in this PR, is a smaller immediate fix: for mixed-input transactions, the history RPCs should stop reporting send entries and full fees when the wallet cannot attribute them objectively.
#25991 is an interesting direction, but as written it depends on manually providing additional wallet-local per-output metadata.
Without that metadata, we still need a safe fallback, and that is what this PR provides.
As I read the related issue #14136, it's unfortunate that the RPC shows incorrect information in the result - glad that this PR tries to address it.
However, I'm leaning towards a NACK because this PR removes the
sendcategory details of such transactions altogether, which is not correct. The wallet does participate (though partially) in sending funds within these transactions and not showing those can be problematic as well.From https://github.com/bitcoin/bitcoin/pull/34872#issue-4104631274
I am also not in favour of having two different views of CachedTxIsFromMe - one without accounting and one with. Having two views is also a sign that there is mismatch between what the wallet shows to the user and what the wallet does for the user.
From https://github.com/bitcoin/bitcoin/pull/34872#issuecomment-4105597428:
Due to the above reasons, I don't believe this is a safe fallback, and it only replaces one issue by another.
From https://github.com/bitcoin/bitcoin/pull/34872#issue-4104631274
It appears that this assumption made by the wallet doesn't hold true anymore and maybe it needs to be reworked for this issue to be completely fixed.
@rkrux Thanks for the review. I agree this isn’t a complete solution for mixed-input accounting.
The goal here is narrower: to prevent history RPCs from reporting send entries and full fees that the wallet cannot objectively attribute from the transaction alone.
So I see this as an improvement over the current behavior.
A complete solution likely requires additional attribution metadata. However, that’s tricky - even if we add something like #25991, or a more automated way to set it, the metadata would not survive an
importdescriptorsrestore, since there’s currently no way to import it.In those cases, we would still need a conservative fallback for history RPCs when attribution is unavailable.
Do you see another way to address this without relying on additional metadata?
NACK
I think it's even more misleading to not show any send entries at all for transactions where we participate in the inputs.
At first glance, I would expect our wallet to be able to recognize which inputs are ours, and I’m astonished that it would just assume that all of the inputs must be ours when it recognizes one. Would it perhaps be possible to recognize such transactions as “multi user transactions” and only apply the inputs that came from our wallet as debits? If our wallet’s balance is decreased by the transaction, we might recognize any outputs from the transaction to our wallet as change output, whereas if the wallet’s balance is increased by the transaction (e.g., a Payjoin that paid us), we would treat the output as an incoming payment. The transaction should then be labeled as having us paid the amount that our wallet balance increased.
That's not really what it is doing. It is correctly treating transactions that have any inputs belonging to the wallet as that transaction belonging to the wallet. The "assumption" comes from
CachedTxGetDebitonly retrieving the total amount of our inputs, which only works when all of the inputs of the transaction belong to the wallet.But without storing more information, there is nothing that we can do to fix that. It shouldn't be astonishing that we are unable to calculate fees when the wallet does not know how much value the inputs that it doesn't know about are providing to the transaction.
This isn't about annotating Bitcoin transactions, it's about annotating logical financial transactions and trying to determine what they are from a single Bitcoin transaction. Because a Bitcoin transaction can have multiple outputs, it can have multiple logical transactions, and the wallet tries to display these as such. For example, a multi party transaction could conceivably contain an output created by someone else in that transaction which pays us, while the same transaction simultaneously has an output that we create paying someone else. These should show as two entries in
listtransactions- one showing a receive and one showing the send. The issue is with annotating the rest of the outputs (we don't store the logical transactions, so how do we know that the remaining outputs are not sends initiated by the user), and showing the correct amount for the fee (we don't know about the inputs that aren't ours, thus we cannot accurately calculate the fees).The solution presented in this PR is to omit all of that logical transaction information entirely for multi party transactions, which I disagree with.
@achow101 @murchandamus Thanks for the feedback.
I pushed a new proposal that addresses it.
As I understand it, a complete solution has two layers:
2. A richer metadata layer, e.g. foreign-output / ownership / fee-share marks, for wallet-created collaborative transactions.
The idea here to solve the layer 1 only.
Layer 2 is still useful, but it cannot replace the fallback. If a wallet is restored from descriptors, rescanned, or imported without the original local metadata, the wallet still needs a reliable way to report history without inventing send outputs or fees.
The new proposal:
In master, wallet history accounting effectively does this when any input is ours:
That works only when all inputs are wallet-owned.
Example:
Inputs:
Outputs:
Master can calculate
wallet_debit = 1.00, but it does not know/store the foreign input value reliably in wallet history. So subtracting all outputs from only wallet-owned inputs gives wrong accounting:fee = 1.00 - 2.99 = -1.99It can also report foreign outputs as wallet send entries, even though the wallet cannot know from the transaction alone whether those outputs are wallet's payment, another participant’s change, or something else.
This new push changes the previous fallback model to:
For the same example:
So the wallet reports the part it can prove: “the wallet balance went down by 0.20 BTC.” It does not guess the fee share or recipient attribution.
Moving this to draft for further discussion.
PR description updated.
Sorry, I had forgotten about this PR. I would prefer a basic conservative solution first without relying on additional metadata by letting the wallet return correct information (as much as it can) while not showing incorrect responses based on any missing transaction data.
Based on a cursory glance, the new proposal seems to be in this^ direction, will review.
CI error unrelated
Concept ACK 29fcb54dac4a8f4b45573ba20b97874eec81be9d
The new approach lgtm, will review when taken out of draft.
Done.
PR description updated.
Split the PR into more commits based on offline feedback
What is this sync needed for on block events? Also, the
called_by_frameworkin the prior line doesn't make sense?Fixed. Thanks.
Thanks for working on this. This sounds like a great improvement regarding multi-user transaction accounting. I have a few questions and I especially found the use of "attributable" somewhat confusing at times.
In "doc: add mixed-input history RPC release note" (eba63bfe77c148a447f44ba0703cb211c7a3213d):
I’m not sure how safety is an issue here. How about "reported correctly", "with improved attribution", "in more detail", or similar?
In "doc: add mixed-input history RPC release note" (eba63bfe77c148a447f44ba0703cb211c7a3213d):
In "doc: add mixed-input history RPC release note" (eba63bfe77c148a447f44ba0703cb211c7a3213d):
The "known zero value" keeps throwing me for a loop. Transactions can only spend TXOs that are in our UTXO set when we first see them. Therefore, we should always know every spent TXO’s value when we first validate a transaction. Shouldn’t it therefore also be available when we store a transaction in the wallet? If not, the wallet should learn it at the time a block is processed, and the value should be in the revert data?
In "doc: add mixed-input history RPC release note" (eba63bfe77c148a447f44ba0703cb211c7a3213d):
I think my issue with "attribute" might be that the verb always needs a target for the attribution that I was missing. Maybe it makes sense when we describe it as the wallet being able to attribute it to itself?
In "doc: add mixed-input history RPC release note" (eba63bfe77c148a447f44ba0703cb211c7a3213d):
In "doc: add mixed-input history RPC release note" (eba63bfe77c148a447f44ba0703cb211c7a3213d):
Maybe:
In "doc: add mixed-input history RPC release note" (eba63bfe77c148a447f44ba0703cb211c7a3213d):
The fee can always be determined per
Σ(inputs)−Σ(outputs), rather we cannot determine our share of the fee.How would this resolve if there were a P2A input?
In "wallet,rpc: attribute zero-value foreign mixed inputs" (056ccd7bab93110d65b5c028f1502238c3a587b9):
This explanation is excellent. "not computable" might be a better expression for the above cases where I found "attributable" to be insufficiently clear.
In "wallet,rpc: attribute zero-value foreign mixed inputs" (056ccd7bab93110d65b5c028f1502238c3a587b9):
Do you mean "every spent input with nonzero value"? Or perhaps "the total input value was contributed by our wallet"?
In "wallet,rpc: rename transaction entry helper" (40d2e72f16c099a15688fa0cc26b7f0bf258636c):
I’m not sure I understand the motivation for this rename. This RPC would print transactions to the terminal based on the given criteria, right? What is it appending to?
Could you please add a short explanation to the commit message why this RPC was renamed?
In "wallet,rpc: report unattributable mixed-input history conservatively" (0d3f1141ef76ef3cbd527f5f1a96518a252f2aed):
What do you mean with "unattributable outputs"? Do you perhaps mean that no outputs go to our wallet, i.e., that
creditis zero?In "wallet,rpc: report unattributable mixed-input history conservatively" (0d3f1141ef76ef3cbd527f5f1a96518a252f2aed):
Even if there are mixed inputs, either the
debitorcreditcould have a greater magnitude. Could you perhaps add an explanation in the commit message why a transaction that overall reduces the balance in the wallet would not be categorized as a send, and a transaction that overall increases the balance in the wallet as a receive?I assume it is because it would be hard to distinguish e.g., a Payjoin in which we get paid and the sender gets a change output from a Payjoin transaction in which we get paid by a sender and also pay another receiver, but it would be good to document the rationale somewhere.
I still think that there might be a special case here, in which there are mixed inputs, but all outputs go to our wallet, in which we might want to categorize it as a receive?
In "wallet,rpc: report unattributable mixed-input history conservatively" (0d3f1141ef76ef3cbd527f5f1a96518a252f2aed):
I find this description confusing. What is "unattributed" about the "aggregate send entry"?
Perhaps: "
In "wallet,rpc: attribute zero-value foreign mixed inputs" (056ccd7bab93110d65b5c028f1502238c3a587b9):
The "known" seems obsolete, as we always know the value of spent TXOs.
In "wallet,rpc: report unattributable mixed-input history conservatively" (0d3f1141ef76ef3cbd527f5f1a96518a252f2aed):
The "cannot be attributed" here also confuses me. FWIU at this point in the review, when no outputs go to ourselves, or all outputs go ourselves, we consider it "attributable", but if there are both foreign-owned inputs and foreign-owned outputs, we call it "not attributable". If that’s the correct understanding, perhaps we can find a more speaking description of that?
In "wallet,rpc: report unattributable mixed-input history conservatively" (0d3f1141ef76ef3cbd527f5f1a96518a252f2aed):
Also here: "cannot attribute" needs more context.
In "wallet,rpc: attribute zero-value foreign mixed inputs" (056ccd7bab93110d65b5c028f1502238c3a587b9):
"known" seems to be extraneous as above.
In "wallet,rpc: attribute zero-value foreign mixed inputs" (056ccd7bab93110d65b5c028f1502238c3a587b9):
If someone only saw this RPC description, "only available when known" would be confusing. How about something along the lines of:
In "wallet,rpc: report unattributable mixed-input history conservatively" (0d3f1141ef76ef3cbd527f5f1a96518a252f2aed):
I’m confused by this line. If all of
credit,debit, andfeeare stored as positive numbers, then surely it should becredit - debit - fee. Iffeeanddebitare stored as negative numbers, it should becredit + debit + fee. Iffeeis stored as a negative number anddebitis stored as a positive number, what are we even doing here? 😅In "wallet: cache transaction input ownership" (3d1134d11fbcbbe4e62a00be06f04648e1bf5e90):
I’d be curious how an anyone-can-spend output such as a P2A output is categorized by
InputIsMine(…), and it might also be a good addition to this test.🐙 This pull request conflicts with the target branch and needs rebase.
@w0xlt can you rebase and respond to murch's review comments?
This behavior predates the PR.
InputIsMine()checks whether the spent output belongs to the wallet. Being anyone-can-spend does not automatically imply ownership:Added a P2A case with its parent stored in the wallet, checking
InputIsMine() == false,NONEfor P2A alone, andPARTIALalongside a wallet-owned input.Added the rationale to the commit message.
This internal helper appends entries for one wallet transaction to the caller's result container.
The public RPC names remain unchanged.
I meant that we cannot determine the wallet’s contribution to individual outputs or the fee.
This does not imply zero credit: wallet-owned outputs are still reported as receives.
Clarified the comment.
Added the rationale to the commit message: receives preserve each output’s details; the send records wallet inputs used. Added tests where all outputs belong to the wallet, before and after confirmation.
On master, the code uses opposite fee formulas:
CachedTxGetAmounts(): wallet input value − total output value.gettransaction: total output value − wallet input value.For transactions funded entirely by the wallet, these represent the same fee with opposite signs.
The new helper uses the first convention and tells all three history RPCs whether the wallet’s fee share is known.
Changing the sign is an implementation choice arising from that consolidation, rather than a requirement of mixed-input accounting itself.
Regarding the question above:
accounting.debitsums the full value of the wallet’s spent inputs.accounting.creditsums the wallet-owned outputs, including change.accounting.credit - accounting.debitalready includes the fee.gettransactionadds the known fee back so amount excludes it, and reports fee separately as negative.Added a code comment explaining why the fee is added back.
Taken, thanks.
Updated the help text. With mixed inputs, we report one send entry for all wallet inputs, regardless of who owns the outputs.
If every non-wallet input is known to have zero value, we use master’s existing per-output format: a separate send entry for each non-change output.
Clarified in both RPC descriptions that the wallet cannot determine how much of each output or the fee was paid from its inputs.
The wallet may not have the parent transaction needed to check a non-wallet input’s value. Clarified the wording.
Applied the same clarification as above here.
Clarified that the fee is reported when all inputs belong to the wallet, or when the transaction has mixed inputs and the wallet can verify that every non-wallet input has zero value. Otherwise, the fee field is omitted.
Clarified the RPC descriptions and removed the remaining “unattributed” wording from the help text. Thanks!
Updated the comment to say that the wallet contributes the total input value. Thanks!
Changed to “reported more accurately”. Thanks!
Applied your suggestion. Thanks!
Yes, it makes sense. The node knows these values during validation, and block undo data contains them. To verify that every non-wallet input has zero value, the wallet currently uses only parent transactions stored in the wallet. If a parent is missing, it cannot verify that input’s value. Learning and retaining those values could be a follow-up improvement.
Updated the release note to say “the wallet can verify”.
Added “to itself”, as suggested. Thanks!
Applied your suggestion. Thanks!
Done. Thanks.
Done. Thanks.
The P2A case is covered now. If the wallet can verify that all non-wallet inputs have zero value, we use master’s existing per-output format, including the fee.
There’s a test for this before and after confirmation.
@sedited Rebased and all comments addressed.
🐙 This pull request conflicts with the target branch and needs rebase.
Concept ACK.
I agree it is better to omit information than to show information that is wrong.
I think the issue is that the history RPCs show two different things in the same list: the UTXO history and the balance history (how much the wallet balance changed, and whether we paid someone). This is hard because they are different paradigms: for simple transactions it works well, but for complex ones (like the ones this PR aims to fix) it breaks.
Using the net change as the amount was already discussed earlier in this thread. What I would suggest discussing is keeping it but splitting both views inside the entry: a single entry per mixed transaction whose
amountis the net change (credit - debit), and a subfield with the wallet UTXOs the transaction spent and created, so no per output information is lost. Something like this (only to illustrate the idea, not a concrete proposal for the field names or layout):For reference, I asked an LLM (Claude Opus) to look at how other wallets handle transactions with foreign inputs: BDK, Electrum, Electron Cash, BlueWallet, Sparrow, Wasabi, Dojo, CLN, LND and the Core GUI. All of them use the net change as the amount of the transaction, and those that cannot compute the fee (BDK, Electrum, Sparrow, Wasabi) leave it out, as this PR does.
I reviewed this PR as part of the Spanish PR Review Club and wanted to share my view. I know the output format has already been discussed at length, so if that is decided and the PR is now at the code review stage, feel free to ignore this suggestion.
ACK
66763e7068I think this is the rigth approach so history RPC never show information the wallet cannot actually know. This way the wallet will be more honest and less confusing when showing the histroy through RPCs and the user will be able to see when the wallet do not have enough information instead of seeing wrong data.
I tested the code in regtest and everything seems to work the way it is supposed to. I just left a comment about a possible small optimitation.
In
a625026843I think here we could avoid callingCachedTxGetHistoryAccountingsince we already do that inCachedTxGetAmounts. For instance, we could modifyCachedTxGetAmountsto return theaccountingstruct. Sth like this:🟠 Minor ·
listrawtransactionsstill promises fee-exclusive mixed-input amountsFor mixed inputs with an unknown wallet fee share,
listrawtransactionsnow returns the wallet's net change without afee, but its help and release note still promise a fee-exclusive amount.Location:
src/wallet/rpc/transactions.cpp:451(head).🔵 Suggestion · Mixed-input history changes have no compatibility path
Although the old attribution was incorrect, removing
voutandfeeand changing send amounts can break existing RPC clients without the grace-period option recommended by the RPC guidelines.Location:
src/wallet/rpc/transactions.cpp:363(head).🔵 Suggestion ·
include_changehelp omits the aggregate mixed-input exceptionConservative mixed-input history now includes change as
receiveeven withinclude_change=false, but the argument help does not explain this exception.Location:
src/wallet/receive.cpp:242(head).🔵 Suggestion · The sum-to-net guarantee overlooks block-conflicted transactions
The new sum-to-net guarantee overlooks the existing receive-depth filter: block-conflicted conservative mixed-input transactions retain the aggregate send but omit wallet credits from their entries.
Location:
src/wallet/rpc/transactions.cpp:562(head).Review coverage was incomplete.
Reviewed:
e9b990c4ff21· Review report · Previous reportspermalink
@arejula27 Thanks for the review and the suggestion! I like the idea of showing the net change alongside the wallet’s spent and created outputs.
This PR already has quite a bit of complexity, so I’d prefer to explore that format in a follow-up. That would give the interface and compatibility questions their own discussion while keeping this PR focused on fixing the incorrect accounting.
Would you be interested in opening a draft PR on top of this one? I’d concept ACK that direction and be happy to help review it.
Thanks. Done. Added you as co-author.
Thanks! Yes, I'd be happy to open a draft PR on top of this one, i will try to do it this week :D
For another follow-up (or in that one but i think it fit betters on its own) I'd also like to propose moving the classification logic into the wallet so the GUI can share it. Today
TransactionRecord::decomposeTransactionredoes the same split, so the two implementations can diverge. Exposing the result through interfaces::WalletTx would let the RPCs and the GUI use the same logic. What do you think?Thanks! Looking forward to the draft.
I agree that sharing the classification with the GUI would be useful, and I’d support keeping that as its own follow-up.
There’s already a starting point in this PR:
CachedTxGetHistoryAccountingcomputes input ownership, debit, credit, and an optional attributable fee in the wallet. Exposing those facts throughinterfaces::WalletTxcould let the GUI use the same accounting rules as the RPCs, while leaving presentation decisions with each caller.One useful test case would be a transaction where we spend 1 BTC and the only foreign input is known to be worth 0 BTC. That foreign input adds no money, so all the funds still come from our wallet. This PR recognizes that and can report the outputs and fee normally.
The GUI on master currently puts this transaction into its generic “Other” handling because one input isn’t ours. Sharing the wallet’s accounting result would let it recognize that all the funds still came from our wallet.
I’d concept ACK that direction too, and would be happy to help review both drafts.
🐙 This pull request conflicts with the target branch and needs rebase.
Rebased