BIP: 78
  Layer: Applications
  Title: A Simple Payjoin Proposal
  Author: Nicolas Dorier 
  Replaces: 79
  Comments-Summary: No comments yet.
  Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0078
  Status: Draft
  Type: Standards Track
  Created: 2019-05-01
  License: BSD-2-Clause
==Introduction== ===Abstract=== This document proposes a protocol for two parties to negotiate a coinjoin transaction during a payment between them. ===Copyright=== This BIP is licensed under the 2-clause BSD license. ===Motivation=== When two parties (later referred to as sender and receiver) want to transact, most of the time, the sender creates a transaction spending their own Unspent Transaction Outputs (UTXOs), signs it and broadcasts it on the network. This simple model gave birth to several heuristics impacting the privacy of the parties and of the network as a whole. * Common input ownership heuristic: In most transactions, all the inputs belong to the same party. * Change identification from scriptPubKey type: If all inputs are spending UTXOs of a certain scriptPubKey type, then the change output is likely to have the same scriptPubKey type, too. * Change identification from round amount: If an output in the transaction has a round amount, it is likely an output belonging to the receiver. We will designate these three heuristics as common-input, change-scriptpubkey, change-round-amount. The problems we aim to solve are: * For the receiver, there is a missed opportunity to consolidate their own UTXOs or making payment in the sender's transaction. * For the sender, there are privacy leaks regarding their wallet that happen when someone applies the heuristics detailed above to their transaction. Our proposal gives an opportunity for the receiver to consolidate their UTXOs while also batching their own payments, without creating a new transaction. (Saving fees in the process) For the sender, it allows them to invalidate the three heuristics above. With the receiver's involvement, the heuristics can even be poisoned. (ie, using the heuristics to intentionally mislead blockchain analysis) Note that the existence of this proposal is also improving the privacy of parties who are not using it by making the three heuristics unreliable to the network as a whole. === Relation to BIP79 (Bustapay) === Another implementation proposal has been written: [[https://github.com/bitcoin/bips/blob/master/bip-0079.mediawiki|BIP79 Bustapay]]. We decided to deviate from it for several reasons: * It was not using PSBT, so if the receiver wanted to bump the fee, they would need the full UTXO set. * The receiver was responsible to pay the additional fee, not the sender. * Inability to change the payment output to match scriptPubKey type. * Lack of basic versioning negotiation if the protocol evolves. * No standardization of error condition for proper feedback to the sender. Other than that, our proposal is very similar. ==Specification== ===Protocol=== In a payjoin payment, the following steps happen: * The receiver of the payment, presents a [[bip-021.mediawiki|BIP 21 URI]] to the sender with a parameter pj describing a payjoin endpoint. * The sender creates a signed, finalized PSBT with witness UTXO or previous transactions of the inputs. We call this PSBT the original. * The receiver replies back with a signed PSBT containing his own signed inputs/outputs and those of the sender. We call this PSBT Payjoin proposal. * The sender verifies the proposal, re-signs his inputs and broadcasts the transaction to the Bitcoin network. We call this transaction Payjoin transaction.
+----------+                        +--------+         +-----------------+
| Receiver |                        | Sender |         | Bitcoin Network |
+----+-----+                        +---+----+         +-------+---------+
     |       +-----------------+        |                      |
     +-------+ BIP21 with ?pj= +------->+                      |
     |       +-----------------+        |                      |
     |                                  |                      |
     |        +---------------+         |                      |
     +<-------+ Original PSBT +---------+                      |
     |        +---------------+         |                      |
     |                                  |                      |
     |       +------------------+       |                      |
     |       | Payjoin Proposal |       |                      |
     +-------+      PSBT        +------>+                      |
     |       +------------------+       |                      |
     |                                  |   +--------------+   |
     |                                  |---+ Payjoin      |   |
     |                                  |   | transaction  +-->+
     |                                  |   +--------------+   |
     +                                  +                      +
The original PSBT is sent in the HTTP POST request body, base64 serialized, with text/plain in the Content-Type HTTP header and Content-Length set correctly. The payjoin proposal PSBT is sent in the HTTP response body, base64 serialized with HTTP code 200. To ensure compatibility with web-wallets and browser-based-tools, all responses (including errors) must contain the HTTP header Access-Control-Allow-Origin: *. The sender must ensure that the url refers to a scheme or protocol using authenticated encryption, for example TLS with certificate validation, or a .onion link to a hidden service whose public key identifier has already been communicated via a TLS connection. Senders SHOULD NOT accept a url representing an unencrypted or unauthenticated connection. The original PSBT MUST: * Have all the witnessUTXO or nonWitnessUTXO information filled in. * Be finalized. * Not include fields unneeded for the receiver such as global xpubs or keypath information. * Be broadcastable. The original PSBT MAY: * Have outputs unrelated to the payment for batching purpose. The payjoin proposal MUST: * Use all the inputs from the original PSBT. * Use all the outputs which do not belongs to the receiver from the original PSBT. * Only finalize the inputs added by the receiver. (Referred later as additional inputs) * Only fill the witnessUTXO or nonWitnessUTXO for the additional inputs. The payjoin proposal MAY: * Add, remove or modify the outputs belonging to the receiver. The payjoin proposal MUST NOT: * Shuffle the order of inputs or outputs, the additional outputs or additional inputs must be inserted at a random index. ===Receiver's well known errors=== If for some reason the receiver is unable to create a payjoin proposal, it will reply with a HTTP code different than 200. The receiver is not constrained to specific set of errors, some are specified in this proposal. The errors have the following format:
{
    "errorCode": "leaking-data",
    "message": "Key path information or GlobalXPubs should not be included in the original PSBT."
}
The well-known error codes are: {| class="wikitable" !Error code !Meaning |- |unavailable |The payjoin endpoint is not available for now. |- |not-enough-money |The receiver added some inputs but could not bump the fee of the payjoin proposal. |- |version-unsupported |This version of payjoin is not supported. |- |original-psbt-rejected |The receiver rejected the original PSBT. |} The receiver is allowed to return implementation specific errors which may assist the sender to diagnose any issue. However, it is important that error codes that are not well-known and that the message do not appear on the sender's software user interface. Such error codes or messages could be used maliciously to phish a non technical user. Instead those errors or messages can only appear in debug logs. It is advised to hard code the description of the well known error codes into the sender's software. ===Receiver's original PSBT checklist=== The receiver needs to do some check on the original PSBT before proceeding: * Non-interactive receivers (like a payment processor) need to check that the original PSBT is broadcastable. * * If the sender included inputs in the original PSBT owned by the receiver, the receiver must either return error invalid-transaction or make sure they do not sign those inputs in the payjoin proposal. * If the sender's inputs are all from the same scriptPubKey type, the receiver must match the same type. If the receiver can't match the type, they must return error unavailable. *: Interactive receivers are not required to validate the original PSBT because they are not exposed to probing attacks. ===Sender's payjoin proposal checklist=== The sender should check the payjoin proposal before signing it to prevent a malicious receiver from stealing money. * Check that all the spent outpoints in the original PSBT still exist in the coinjoin PSBT. * Check that all the spent outpoints in the original PSBT do not have any partial signature and are not finalized. * If the sender is not using inputs with mixed types, check that the receiver inputs type match the inputs type of the sender. (ie. both using P2SH-P2WPKH or both using P2WPKH) * Check that any inputs added by the receiver are finalized. * Check that the transaction version, and nLockTime are unchanged. * Check that the sender's inputs' sequence numbers are unchanged. * If the sender's inputs' sequence numbers are all the same, check that the receiver's contributed inputs match those. * If minfeerate was specified, check that the estimated fee rate of the payjoin proposal is not less than this value. * Check that outputs from the original PSBT has not been modified except if: * The output can contribute to fee (see below) * The output does not belong to the sender. If a fee output exists, (ie, maxadditionalfeecontribution= and additionalfeeoutputindex= have been set by the sender), the sender must checks: * The amount that was substracted from the output's value is less or equal to maxadditionalfeecontribution. Let's call this amount actual contribution. * The actual contribution is less or equals to the difference of absolute fee between the payjoin proposal and the original PSBT. (This make sure the contribution actually goes to fee) * The actual contribution is less or equals to originalPSBTFeeRate * vsize(count(original_psbt_inputs) - count(payjoin_proposal_inputs)). (This make sure the contributiion only pays for additional inputs) The sender must be careful to only sign the inputs that were present in the original PSBT and nothing else. Note: * The sender must allow the receiver to add/remove or modify his own outputs * The sender should allow the receiver to not add any input. Useful for the receiver to change the paymout output scriptPubKey type. * If no input have been added, the sender's wallet implementation should accept the payjoin proposal, but not mark the transaction as an actual payjoin in the user interface. Our method of checking the fee allows the receiver and the sender to batch payments in the payjoin transaction. It also allows the receiver to pay the fee for batching adding his own outputs. On top of those check, it is recommended, but not required for the sender to check that: * If the sender is making a payjoin with a change (ie, not in the [[#spare-change|spare change]] case), make sure the receiver is paying for any batched output. ===Optional parameters=== When the payjoin sender posts the original PSBT to the receiver, he can optionally specify the following HTTP query string parameters: * v=, the version number of the payjoin protocol that the sender is using. The current version is 1. This can be used in the future so the receiver can reject a payjoin if the sender is using a version which is not supported via an error HTTP 400, version-unsupported. If not specified, the receiver will assume the sender is v=1. If the receiver does not support the version of the sender, they should send an error with the list of supported versions:
{
    "errorCode": "version-unsupported",
    "supported" : [ 2, 3, 4 ],
    "message": "The version is not supported anymore"
}
* additionalfeeoutputindex=, if the sender is willing to pay for increased fee, this indicate output can have its value substracted to pay for it. If the additionalfeeoutputindex is out of bounds or pointing to the payment output meant for the receiver, the receiver should ignore the parameter. * maxadditionalfeecontribution=, if the sender is willing to pay for increased fee, an integer defining the maximum amount in satoshis that the sender is willing to contribute towards fees for the additional inputs. maxadditionalfeecontribution must be ignored if set to less than zero. Note that both maxadditionalfeecontribution= and additionalfeeoutputindex= must be specified and valid for the receiver to be allowed to decrease an output belonging to the sender. This fee contribution can't be used to pay for anything else than additional input's weight. * minfeerate=, a decimal in satoshi per vbyte that the sender can use to constraint the receiver to not drop the minimum fee rate too much. ==Rationale== There is several consequences of our proposal: * The receiver can bump the fee of the original transaction. * The receiver can modify the outputs of the original PSBT. * The sender must provide the UTXO information (Witness or previous transaction) in the PSBT. ===Respecting the minimum relay fee policy=== To be properly relayed, a Bitcoin transaction needs to pay at least 1 satoshi per virtual byte. When blocks are not full, the original transaction might already at the minimum relay fee rate (currently 1 satoshi per virtual byte), so if the receiver adds their own input, they need to make sure the fee is increased such that the rate does not drop below the minimum relay fee rate. In such case, the sender must set both maxadditionalfeecontribution= and additionalfeeoutputindex=. The recommended value maxadditionalfeecontribution= is minFeeRate * vsize(1 input). We also recommend the sender to set minfeerate=, as the sender's node policy might be different from the receiver's policy. ===Defeating heuristics based on the fee calculation=== Most wallets are creating a round fee rate (like 2 sat/b). If the payjoin transaction's fee was not increased by the added size, then those payjoin transactions could easily be identifiable on the blockchain. Not only would those transactions stand out by not having a round fee (like 1.87 sat/b), but any suspicion of payjoin could be confirmed by checking if removing one input would create a round fee rate. In such case, the sender must set both maxadditionalfeecontribution= and additionalfeeoutputindex=. The recommended value maxadditionalfeecontribution= is feerate * vsize(1 input). We also recommend the sender to set minfeerate=, as the sender's node policy might be different from the receiver's policy. ===Receiver does not need to be a full node=== Because the receiver needs to bump the fee to keep the same fee rate as the original PSBT, it needs the input's UTXO information to know what is the original fee rate. Without PSBT, light wallets like Wasabi Wallet would not be able to receive a payjoin transaction. The validation (policy and consensus) of the original transaction is optional: a receiver without a full node can decide to create the payjoin transaction and automatically broadcast the original transaction after a timeout of 1 minute, and only verify that it has been propagated in the network. However, non-interactive receivers (like a payment processor) need to verify the transaction to prevent UTXO probing attacks. This is not a concern for interactive receivers like Wasabi Wallet, because those receivers can just limit the number of original PSBT proposals of a specific address to one. With such wallets, the attacker has no way to generate new deposit addresses to probe the UTXOs. ===Spare change donation=== Small change inside wallets are detrimental to privacy. Mixers like Wasabi wallet, because of its protocol, eventually generate such [[https://docs.wasabiwallet.io/using-wasabi/ChangeCoins.html#first-round-coinjoin-change|small change]]. A common way to protect your privacy is to donate those spare changes, to deposit them in an exchange or on your favorite merchant's store account. Those kind of transactions can easily be spotted on the blockchain: There is only one output. However, if you donate via payjoin, it will look like a normal transaction. On top of this the receiver can poison analysis by randomly faking a round amount of satoshi for the additional output. ===Payment output substitution=== The receiver is free to change the output paying to himself. For example, if the sender's scriptPubKey type is P2WPKH while the receiver's payment output in the original PSBT is P2SH, then the receiver can substitute the payment output to be P2WPKH to match the sender's scriptPubKey type. ===Impacted heuristics=== Our proposal of payjoin is breaking the following blockchain heuristics: * Common inputs heuristics. Because payjoin is mixing the inputs of the sender and receiver, this heuristic becomes unreliable. * Change identification from scriptPubKey type heuristics When Alice pays Bob, if Alice is using P2SH but Bob's deposit address is P2WPKH, the heuristic would assume that the P2SH output is the change address of Alice. This is now however a broken assumption, as the payjoin receiver has the freedom to mislead analytics by purposefully changing the invoice's address in the payjoin transaction. Alternatively, if the original address of Bob is P2WPKH and Alice's address is also P2WPKH, Bob can change the receiving address in the payjoin to P2SH. The heuristic would wrongfully identify the payjoin's receiving address as the change address of the transaction. See [[#output-substitution|payment output substitution]]. * Change identification from round change amount If Alice pays Bob, she might be tempted to pay him a round amount, like 1.23000000 BTC. When this happens, blockchain analysis often identifies the output without the round amount as the change of the transaction. For this reason, during a [[#spare-change|spare change]] case, the receiver may add an output with a rounded amount randomly. ==Attack vectors== ===On the receiver side: UTXO probing attack=== When the receiver creates a payjoin proposal, they expose one or more inputs belonging to them. An attacker could create multiple original transactions in order to learn the UTXOs of the receiver, while not broadcasting the payjoin proposal. While we cannot prevent this type of attack entirely, we implemented the following mitigations: * When the receiver detects an original transaction being broadcast, or if the receiver detects that the original transaction has been double spent, then they will reuse the UTXO that was exposed for the next payjoin. * While the exposed UTXO will be reused in priority to not leak other UTXOs, there is no strong guarantee about it. This prevents the attacker from detecting with certainty the next payjoin of the merchant to another peer. Note that probing attacks are only a problem for automated payment systems such as BTCPay Server. End-user wallets with payjoin capabilities are not affected, as the attacker can't create multiple invoices to force the receiver to expose their UTXOs. ===On the sender side: Double payment risk for hardware wallets=== For a successful payjoin to happen, the sender needs to sign two transactions double spending each other: The original transaction and the payjoin proposal. The sender's software wallet can verify that the payjoin proposal is legitimate by the sender's checklist. However, a hardware wallet can't verify that this is indeed the case. This means that the security guarantee of the hardware wallet is decreased. If the sender's software is compromised, the hardware wallet would sign two valid transactions, thus sending two payments. Without payjoin, the maximum amount of money that could be lost by a compromised software is equal to one payment (via address substitution). With payjoin, the maximum amount of money that can be lost is equal to two payments. ==Implementations== * [[https://github.com/BlueWallet/BlueWallet|BlueWallet]] is in the process of implementing the protocol. * [[https://github.com/btcpayserver/btcpayserver|BTCPay Server]] has implemented sender and receiver side of this protocol. * [[https://github.com/zkSNACKs/WalletWasabi/|Wasabi Wallet]] has merged sender's support. * [[https://github.com/JoinMarket-Org/joinmarket-clientserver|Join Market]] is in the process of implementing the protocol. * [[https://github.com/bitcoinjs/payjoin-client|JavaScript sender implementation]]. ==Backward compatibility== The receivers are advertising payjoin capabilities through [[https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki|BIP21's URI Scheme]]. Senders not supporting payjoin will just ignore the pj variable and thus, will proceed to normal payment. ==Special thanks== Special thanks to Kukks for developing the initial support to BTCPay Server, to junderw, AdamISZ, lukechilds, ncoelho, nopara73, lontivero, yahiheb for all the feedback we received since our first implementation. Thanks also to RHavar who wrote the [[https://github.com/bitcoin/bips/blob/master/bip-0079.mediawiki|BIP79 Bustapay]] proposal, this gave a good starting point for our proposal.