From 3faf6e7540e9925b536701c9644e6622b8d25b19 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Sat, 9 May 2020 17:33:59 +0900 Subject: [PATCH 01/46] Add payjoin proposal --- bip-xxxx.mediawiki | 335 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 335 insertions(+) create mode 100644 bip-xxxx.mediawiki diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki new file mode 100644 index 00000000..c4202a7b --- /dev/null +++ b/bip-xxxx.mediawiki @@ -0,0 +1,335 @@ +
+  BIP: ?
+  Layer: Applications
+  Title: A Simple Payjoin Proposal
+  Author: Nicolas Dorier 
+  Comments-Summary: No comments yet.
+  Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-X
+  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. +* It was requiring at least one input to be contributed by the receiver. +* 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 an https (or http if it is a Tor hidden service) link to the 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 MUST NOT accept a url representing an unencrypted or unauthenticated connection. + +===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 +|- +|leaking-data +|Key path information or GlobalXPubs should not be included in the original PSBT. +|- +|psbt-not-finalized +|The original PSBT must be finalized. +|- +|unavailable +|The payjoin endpoint is not available for now. +|- +|out-of-utxos +|The receiver does not have any UTXO to contribute in a payjoin proposal. +|- +|not-enough-money +|The receiver added some inputs but could not bump the fee of the payjoin proposal. +|- +|insane-psbt +|Some consistency check on the PSBT failed. +|- +|version-unsupported +|This version of payjoin is not supported. +|- +|need-utxo-information +|The witness UTXO or non witness UTXO is missing +|- +|invalid-transaction +|The original transaction is invalid for payjoin +|} + +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 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 out-of-utxos. + +*: 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. +* 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 the homogenous, check that the receiver's contributed inputs match those. +* Check that the sender's outputs have not been modified (but potentially shuffled), except for paying increased fee +* If sender specified feebumpindex= (see later), the fee should have been subtracted from the output at the same index in the original PSBT. +* Check that the sent amount in the payjoin proposal is less than or equal to the sent amount of the original transaction. + +If the sent amount in the payjoin proposal is above the amount sent in the original PSBT +* Check that the additional paid amount has been add paid to the fee. +* Check that the estimated fee rate of the payjoin proposal is not more than the fee rate of the original PSBT. (fee estimation is hard, so we should allow ~2 satoshi per inputs as margin of error) +* If maxfeebumpcontribution= was specified, check the additional paid amount is less than or equal to this amount. +* If maxfeebumpcontribution= was not specified, the sender's software should ask an interactive confirmation to the user. + +The sender must be careful to only sign the inputs that were present in the original PSBT and nothing else. + +Note: +* The sender should allow the payment output to be modified by the receiver (The receiver may substitute a P2WPKH payment to P2SH payment to increase privacy) +* The sender must allow the receiver to add outputs. +* The sender must 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. + +===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"
+}
+
+ +* feebumpindex=, the preferred output from which to increase the fee for the added inputs. (default: -1) + +If the feebumpindex is out of bounds or pointing to the payment ouptut meant for the receiver, the receiver should ignore the parameter. + +* maxfeebumpcontribution=, an integer defining the maximum amount in satoshis that the sender is willing to contribute towards fees for the additional inputs. maxfeebumpcontribution must be ignored if set to less than zero. (default: -1) + +Note that if maxfeebumpcontribution is too low, the sender should create a transaction with RBF disabled, as the original transaction could replace the payjoin transaction. + +==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 fees are low, the original transaction is already 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 1 satoshi per virtual byte. + +===Preventing mempool replacement=== + +A safe way to implement payjoin, is for both the sender and receiver to try broadcasting the original transaction at some fixed interval period regardless of the state of the payjoin. + +If the receiver was not properly adding fees to the payjoin transaction, the original transaction would end up replacing the payjoin transaction in the mempool. + +===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. + +===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 payment output substitution above. + +* 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](Payjoin-spec.md#spare-change-donation) situation, we randomly round the amount in the output added by the receiver to the payjoin transaction. + +==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/junderw/payjoin-client-js|JavaScript sender implementation]]. + +==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. From c33f0759d63093329c4443df1d1b627ba1ae7f08 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Sun, 17 May 2020 19:55:45 +0900 Subject: [PATCH 02/46] Clarify sender's payjoin proposal checklist --- bip-xxxx.mediawiki | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index c4202a7b..9e449317 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -173,9 +173,9 @@ The sender should check the payjoin proposal before signing it to prevent a mali * 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 the homogenous, check that the receiver's contributed inputs match those. -* Check that the sender's outputs have not been modified (but potentially shuffled), except for paying increased fee +* Check that the sender's own outputs have not been modified, except for paying increased fee, or by simple shuffling. * If sender specified feebumpindex= (see later), the fee should have been subtracted from the output at the same index in the original PSBT. -* Check that the sent amount in the payjoin proposal is less than or equal to the sent amount of the original transaction. +* Check that the sent amount in the payjoin proposal is less than or equal to the sent amount of the original transaction. (Defined as the sum of the inputs' value to be signed minus the sender's ouput change) If the sent amount in the payjoin proposal is above the amount sent in the original PSBT * Check that the additional paid amount has been add paid to the fee. From 24dd275445329aba230542099bf49e36c4a2d785 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Sun, 17 May 2020 19:58:17 +0900 Subject: [PATCH 03/46] Rename to additionalfeeoutputindex and maxadditionalfeecontribution --- bip-xxxx.mediawiki | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index 9e449317..5f316d34 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -174,14 +174,14 @@ The sender should check the payjoin proposal before signing it to prevent a mali * Check that the sender's inputs' sequence numbers are unchanged. * If the sender's inputs' sequence numbers the homogenous, check that the receiver's contributed inputs match those. * Check that the sender's own outputs have not been modified, except for paying increased fee, or by simple shuffling. -* If sender specified feebumpindex= (see later), the fee should have been subtracted from the output at the same index in the original PSBT. +* If sender specified additionalfeeoutputindex= (see later), the fee should have been subtracted from the output at the same index in the original PSBT. * Check that the sent amount in the payjoin proposal is less than or equal to the sent amount of the original transaction. (Defined as the sum of the inputs' value to be signed minus the sender's ouput change) If the sent amount in the payjoin proposal is above the amount sent in the original PSBT * Check that the additional paid amount has been add paid to the fee. * Check that the estimated fee rate of the payjoin proposal is not more than the fee rate of the original PSBT. (fee estimation is hard, so we should allow ~2 satoshi per inputs as margin of error) -* If maxfeebumpcontribution= was specified, check the additional paid amount is less than or equal to this amount. -* If maxfeebumpcontribution= was not specified, the sender's software should ask an interactive confirmation to the user. +* If maxadditionalfeecontribution= was specified, check the additional paid amount is less than or equal to this amount. +* If maxadditionalfeecontribution= was not specified, the sender's software should ask an interactive confirmation to the user. The sender must be careful to only sign the inputs that were present in the original PSBT and nothing else. @@ -212,13 +212,13 @@ If the receiver does not support the version of the sender, they should send an } -* feebumpindex=, the preferred output from which to increase the fee for the added inputs. (default: -1) +* additionalfeeoutputindex=, the preferred output from which to increase the fee for the added inputs. (default: -1) -If the feebumpindex is out of bounds or pointing to the payment ouptut meant for the receiver, the receiver should ignore the parameter. +If the additionalfeeoutputindex is out of bounds or pointing to the payment ouptut meant for the receiver, the receiver should ignore the parameter. -* maxfeebumpcontribution=, an integer defining the maximum amount in satoshis that the sender is willing to contribute towards fees for the additional inputs. maxfeebumpcontribution must be ignored if set to less than zero. (default: -1) +* maxadditionalfeecontribution=, 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. (default: -1) -Note that if maxfeebumpcontribution is too low, the sender should create a transaction with RBF disabled, as the original transaction could replace the payjoin transaction. +Note that if maxadditionalfeecontribution is too low, the sender should create a transaction with RBF disabled, as the original transaction could replace the payjoin transaction. ==Rationale== From 088cf9bf9117330458535e84bb36ebf298974037 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Sun, 17 May 2020 20:01:48 +0900 Subject: [PATCH 04/46] Clarify fake rounded amount added by the receiver --- bip-xxxx.mediawiki | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index 5f316d34..83aae19e 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -292,7 +292,7 @@ See payment output substitution above. 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](Payjoin-spec.md#spare-change-donation) situation, we randomly round the amount in the output added by the receiver to the payjoin transaction. +For this reason, during a [spare change](Payjoin-spec.md#spare-change-donation) situation, the receiver may add an output with a rounded amount randomly. ==Attack vectors== From 233c0946674c7818a65695344bd823fd8da989a7 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Sun, 17 May 2020 21:49:43 +0900 Subject: [PATCH 05/46] Add minFeeRate optional parameter --- bip-xxxx.mediawiki | 3 +++ 1 file changed, 3 insertions(+) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index 83aae19e..440f6998 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -175,6 +175,7 @@ The sender should check the payjoin proposal before signing it to prevent a mali * If the sender's inputs' sequence numbers the homogenous, check that the receiver's contributed inputs match those. * Check that the sender's own outputs have not been modified, except for paying increased fee, or by simple shuffling. * If sender specified additionalfeeoutputindex= (see later), the fee should have been subtracted from the output at the same index in the original PSBT. +* If minfeerate was specified, check that the estimated fee rate of the payjoin proposal is not less than this value. * Check that the sent amount in the payjoin proposal is less than or equal to the sent amount of the original transaction. (Defined as the sum of the inputs' value to be signed minus the sender's ouput change) If the sent amount in the payjoin proposal is above the amount sent in the original PSBT @@ -220,6 +221,8 @@ If the additionalfeeoutputindex is out of bounds or pointing to the Note that if maxadditionalfeecontribution is too low, the sender should create a transaction with RBF disabled, as the original transaction could replace the payjoin transaction. +* 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: From 3836ef65342ff44628a70ddf859e428a69753c5e Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Mon, 18 May 2020 18:43:32 +0900 Subject: [PATCH 06/46] Reword sentence --- bip-xxxx.mediawiki | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index 440f6998..e3a32885 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -172,7 +172,7 @@ The sender should check the payjoin proposal before signing it to prevent a mali * 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 the homogenous, check that the receiver's contributed inputs match those. +* If the sender's inputs' sequence numbers are all the same, check that the receiver's contributed inputs match those. * Check that the sender's own outputs have not been modified, except for paying increased fee, or by simple shuffling. * If sender specified additionalfeeoutputindex= (see later), the fee should have been subtracted from the output at the same index in the original PSBT. * If minfeerate was specified, check that the estimated fee rate of the payjoin proposal is not less than this value. From dd9193fd1d370194ffed58d231b7aa75d72e3273 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Tue, 19 May 2020 04:50:46 +0900 Subject: [PATCH 07/46] Remove out-of-utxo --- bip-xxxx.mediawiki | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index e3a32885..7ec90c8b 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -125,9 +125,6 @@ The well-known error codes are: |unavailable |The payjoin endpoint is not available for now. |- -|out-of-utxos -|The receiver does not have any UTXO to contribute in a payjoin proposal. -|- |not-enough-money |The receiver added some inputs but could not bump the fee of the payjoin proposal. |- @@ -158,7 +155,7 @@ 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 out-of-utxos. +* 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. From 5a337c6fc6104fc31eff0ecbb654e9580af4f907 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Tue, 19 May 2020 18:59:57 +0900 Subject: [PATCH 08/46] Make sure the receiver is not free riding on sender's back --- bip-xxxx.mediawiki | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index 7ec90c8b..341e6e16 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -156,6 +156,7 @@ 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. +* maxadditionalfeecontribution= and minfeerate= should be ignored in the [[#spare-change|spare change]] case. *: Interactive receivers are not required to validate the original PSBT because they are not exposed to probing attacks. @@ -180,6 +181,7 @@ If the sent amount in the payjoin proposal is above the amount sent in the origi * Check that the estimated fee rate of the payjoin proposal is not more than the fee rate of the original PSBT. (fee estimation is hard, so we should allow ~2 satoshi per inputs as margin of error) * If maxadditionalfeecontribution= was specified, check the additional paid amount is less than or equal to this amount. * If maxadditionalfeecontribution= was not specified, the sender's software should ask an interactive confirmation to the user. +* maxadditionalfeecontribution= and minfeerate= should be ignored in the [[#spare-change|spare change]] case. The sender must be careful to only sign the inputs that were present in the original PSBT and nothing else. @@ -192,6 +194,9 @@ Note: 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 change in the output list. + ===Optional parameters=== When the payjoin sender posts the original PSBT to the receiver, he can optionally specify the following HTTP query string parameters: @@ -213,13 +218,17 @@ If the receiver does not support the version of the sender, they should send an * additionalfeeoutputindex=, the preferred output from which to increase the fee for the added inputs. (default: -1) If the additionalfeeoutputindex is out of bounds or pointing to the payment ouptut meant for the receiver, the receiver should ignore the parameter. +Should be ignored in the [[#spare-change|spare change]] case. * maxadditionalfeecontribution=, 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. (default: -1) Note that if maxadditionalfeecontribution is too low, the sender should create a transaction with RBF disabled, as the original transaction could replace the payjoin transaction. +Should be ignored in the [[#spare-change|spare change]] case. * 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. +Should be ignored in the [[#spare-change|spare change]] case. + ==Rationale== There is several consequences of our proposal: @@ -256,7 +265,7 @@ However, non-interactive receivers (like a payment processor) need to verify the 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=== +===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]]. @@ -266,7 +275,7 @@ 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=== +===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. @@ -286,13 +295,13 @@ This is now however a broken assumption, as the payjoin receiver has the freedom 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 payment output substitution above. +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](Payjoin-spec.md#spare-change-donation) situation, the receiver may add an output with a rounded amount randomly. +For this reason, during a [[#spare-change|spare change]] case, the receiver may add an output with a rounded amount randomly. ==Attack vectors== From 3659671a224dff4a3fc9247daf1ca65e35b4522a Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Tue, 19 May 2020 19:14:51 +0900 Subject: [PATCH 09/46] Relaxing authenticated endpoint --- bip-xxxx.mediawiki | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index 341e6e16..b1fb4bdf 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -65,7 +65,7 @@ Other than that, our proposal is very similar. 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 an https (or http if it is a Tor hidden service) link to the payjoin endpoint. +* 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. @@ -96,7 +96,9 @@ The payjoin proposal PSBT is sent in the HTTP response body, base64 serialized w 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 MUST NOT accept a url representing an unencrypted or unauthenticated connection. +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. + +Unauthenticated transport is authorized, but [[#output-substitution|Output substitution]] should be disallowed in this case. ===Receiver's well known errors=== @@ -280,6 +282,8 @@ On top of this the receiver can poison analysis by randomly faking a round amoun 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. +Note that this MUST NOT be authorized over an unauthenticated payjoin endpoint such as http on clearnet, as a man-in-the-middle attacker could substitute with his own address. + ===Impacted heuristics=== Our proposal of payjoin is breaking the following blockchain heuristics: From 1251d29854c37194e5c5ad8ff5029a50196aa22e Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Wed, 20 May 2020 06:11:58 +0900 Subject: [PATCH 10/46] Discourage unsecured endpoint --- bip-xxxx.mediawiki | 4 ---- 1 file changed, 4 deletions(-) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index b1fb4bdf..31ecaa5e 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -98,8 +98,6 @@ To ensure compatibility with web-wallets and browser-based-tools, all responses 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. -Unauthenticated transport is authorized, but [[#output-substitution|Output substitution]] should be disallowed in this case. - ===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. @@ -282,8 +280,6 @@ On top of this the receiver can poison analysis by randomly faking a round amoun 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. -Note that this MUST NOT be authorized over an unauthenticated payjoin endpoint such as http on clearnet, as a man-in-the-middle attacker could substitute with his own address. - ===Impacted heuristics=== Our proposal of payjoin is breaking the following blockchain heuristics: From 900d221a858d5581dce151c0dfe429716f00d3be Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Sun, 24 May 2020 02:35:19 +0900 Subject: [PATCH 11/46] Fix typo --- bip-xxxx.mediawiki | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index 31ecaa5e..05a4beac 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -217,7 +217,7 @@ If the receiver does not support the version of the sender, they should send an * additionalfeeoutputindex=, the preferred output from which to increase the fee for the added inputs. (default: -1) -If the additionalfeeoutputindex is out of bounds or pointing to the payment ouptut meant for the receiver, the receiver should ignore the parameter. +If the additionalfeeoutputindex is out of bounds or pointing to the payment output meant for the receiver, the receiver should ignore the parameter. Should be ignored in the [[#spare-change|spare change]] case. * maxadditionalfeecontribution=, 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. (default: -1) From 387d5e1b12eaf06f4d454e1e53e3465c25a9fa53 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Sun, 24 May 2020 02:37:26 +0900 Subject: [PATCH 12/46] Reformulate --- bip-xxxx.mediawiki | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index 05a4beac..fb14013e 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -195,7 +195,7 @@ Our method of checking the fee allows the receiver and the sender to batch payme 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 change in the output list. +* 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=== From 633f94d0056dd3aec8ed89343fcfa37f8905e117 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Thu, 28 May 2020 08:39:49 +0900 Subject: [PATCH 13/46] This BIP replace 79 --- bip-xxxx.mediawiki | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index fb14013e..7334e30c 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -3,6 +3,7 @@ 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-X Status: Draft @@ -52,7 +53,6 @@ Another implementation proposal has been written: [[https://github.com/bitcoin/b 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. -* It was requiring at least one input to be contributed by the receiver. * 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. From f62ceee781ae80ca704effb15dc35ab1eebade1a Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Thu, 28 May 2020 13:30:34 +0900 Subject: [PATCH 14/46] Remove uneeded error message, add more details on the original/proposal PSBT requirements --- bip-xxxx.mediawiki | 38 +++++++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index 7334e30c..58dcd977 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -98,6 +98,26 @@ To ensure compatibility with web-wallets and browser-based-tools, all responses 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 including 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. +* Only finalize the inputs added by the receiver. +* Have all the `witnessUTXO` or `nonWitnessUTXO` information filled in. +* Keep all the outputs unrelated to the payment. + +The payjoin proposal MAY: +* Add inputs. +* Add outputs. +* Modify payment's output. + ===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. @@ -116,29 +136,17 @@ The well-known error codes are: !Error code !Meaning |- -|leaking-data -|Key path information or GlobalXPubs should not be included in the original PSBT. -|- -|psbt-not-finalized -|The original PSBT must be finalized. -|- |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. |- -|insane-psbt -|Some consistency check on the PSBT failed. -|- |version-unsupported |This version of payjoin is not supported. |- -|need-utxo-information -|The witness UTXO or non witness UTXO is missing -|- -|invalid-transaction -|The original transaction is invalid for payjoin +|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. @@ -147,7 +155,7 @@ However, it is important that error codes that are not well-known and that the m 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 error codes into the sender's software. +It is advised to hard code the description of the wellknown error codes into the sender's software. ===Receiver's original PSBT checklist=== From 434e8c279dffc1da626172985605d3f167223b63 Mon Sep 17 00:00:00 2001 From: Nicolas Dorier Date: Thu, 28 May 2020 13:45:08 +0900 Subject: [PATCH 15/46] Update bip-xxxx.mediawiki Co-authored-by: yahiheb <52379387+yahiheb@users.noreply.github.com> --- bip-xxxx.mediawiki | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index 58dcd977..c325e98f 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -101,7 +101,7 @@ The sender must ensure that the url refers to a scheme or protocol using authent The original PSBT MUST: * Have all the `witnessUTXO` or `nonWitnessUTXO` information filled in. * Be finalized. -* Not including fields unneeded for the receiver such as global xpubs or keypath information. +* Not include fields unneeded for the receiver such as global xpubs or keypath information. * Be broadcastable. The original PSBT MAY: From 5db1b99504958a808b96692fca872474bf2ecfda Mon Sep 17 00:00:00 2001 From: Nicolas Dorier Date: Thu, 28 May 2020 13:45:21 +0900 Subject: [PATCH 16/46] Update bip-xxxx.mediawiki Co-authored-by: yahiheb <52379387+yahiheb@users.noreply.github.com> --- bip-xxxx.mediawiki | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index c325e98f..30fda119 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -155,7 +155,7 @@ However, it is important that error codes that are not well-known and that the m 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 wellknown error codes into the sender's software. +It is advised to hard code the description of the well known error codes into the sender's software. ===Receiver's original PSBT checklist=== From 3bede60b705ebeaf140b26b1b2dcf20cf78d625e Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Tue, 2 Jun 2020 11:41:41 +0900 Subject: [PATCH 17/46] Update Javascript sender implementation link --- bip-xxxx.mediawiki | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index 30fda119..be5ed260 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -344,7 +344,7 @@ With payjoin, the maximum amount of money that can be lost is equal to two payme * [[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/junderw/payjoin-client-js|JavaScript sender implementation]]. +* [[https://github.com/bitcoinjs/payjoin-client|JavaScript sender implementation]]. ==Special thanks== From 8ce60865178b46f0d420dde5c5bc373cc17a22da Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Tue, 2 Jun 2020 11:46:04 +0900 Subject: [PATCH 18/46] Add Backward compatibility section --- bip-xxxx.mediawiki | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/bip-xxxx.mediawiki b/bip-xxxx.mediawiki index be5ed260..c9d2d085 100644 --- a/bip-xxxx.mediawiki +++ b/bip-xxxx.mediawiki @@ -346,6 +346,12 @@ With payjoin, the maximum amount of money that can be lost is equal to two payme * [[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. From 73a4d7c4baa71355e145158156d41238722f58a1 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Tue, 16 Jun 2020 12:37:42 +0900 Subject: [PATCH 19/46] Rename to BIP78 --- README.mediawiki | 8 ++++++++ bip-xxxx.mediawiki => bip-0078.mediawiki | 4 ++-- 2 files changed, 10 insertions(+), 2 deletions(-) rename bip-xxxx.mediawiki => bip-0078.mediawiki (99%) diff --git a/README.mediawiki b/README.mediawiki index b488b10e..ad6a4b00 100644 --- a/README.mediawiki +++ b/README.mediawiki @@ -386,6 +386,14 @@ Those proposing changes should consider that ultimately consent may rest with th | Standard | Final |- style="background-color: #ffffcf" +| [[bip-0078.mediawiki|79]] +| Applications +| Bustapay :: A Simple Payjoin Proposal +| Nicolas Dorier +| Informational +| Proposed +|- +|- style="background-color: #ffffcf" | [[bip-0079.mediawiki|79]] | Applications | Bustapay :: a practical coinjoin protocol diff --git a/bip-xxxx.mediawiki b/bip-0078.mediawiki similarity index 99% rename from bip-xxxx.mediawiki rename to bip-0078.mediawiki index c9d2d085..2b29f165 100644 --- a/bip-xxxx.mediawiki +++ b/bip-0078.mediawiki @@ -1,11 +1,11 @@
-  BIP: ?
+  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-X
+  Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0078
   Status: Draft
   Type: Standards Track
   Created: 2019-05-01

From d13c78467191ffe9beb24823ce7dd7e12ec63199 Mon Sep 17 00:00:00 2001
From: "nicolas.dorier" 
Date: Tue, 16 Jun 2020 13:39:27 +0900
Subject: [PATCH 20/46] Remove parts refering to RBF, add recommendations for
 maxadditionalfeecontribution

---
 bip-0078.mediawiki | 24 +++++++++++-------------
 1 file changed, 11 insertions(+), 13 deletions(-)

diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki
index 2b29f165..d4d6b5ac 100644
--- a/bip-0078.mediawiki
+++ b/bip-0078.mediawiki
@@ -164,7 +164,6 @@ 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.
-* maxadditionalfeecontribution= and minfeerate= should be ignored in the [[#spare-change|spare change]] case.
 
 *: Interactive receivers are not required to validate the original PSBT because they are not exposed to probing attacks.
 
@@ -223,20 +222,16 @@ If the receiver does not support the version of the sender, they should send an
 }
 
-* additionalfeeoutputindex=, the preferred output from which to increase the fee for the added inputs. (default: -1) +* 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. -Should be ignored in the [[#spare-change|spare change]] case. -* maxadditionalfeecontribution=, 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. (default: -1) +* 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 if maxadditionalfeecontribution is too low, the sender should create a transaction with RBF disabled, as the original transaction could replace the payjoin transaction. -Should be ignored in the [[#spare-change|spare change]] case. +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. * 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. -Should be ignored in the [[#spare-change|spare change]] case. - ==Rationale== There is several consequences of our proposal: @@ -248,13 +243,12 @@ There is several consequences of our proposal: ===Respecting the minimum relay fee policy=== To be properly relayed, a Bitcoin transaction needs to pay at least 1 satoshi per virtual byte. -When fees are low, the original transaction is already 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 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=. -===Preventing mempool replacement=== +The recommended value maxadditionalfeecontribution= is `minFeeRate * vsize(1 input)`. -A safe way to implement payjoin, is for both the sender and receiver to try broadcasting the original transaction at some fixed interval period regardless of the state of the payjoin. - -If the receiver was not properly adding fees to the payjoin transaction, the original transaction would end up replacing the payjoin transaction in the mempool. +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=== @@ -262,6 +256,10 @@ 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 `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. ===Receiver does not need to be a full node=== From 631d8e65cd01bdcb8d6e0b93c4c36fd039d5744b Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Tue, 16 Jun 2020 14:17:36 +0900 Subject: [PATCH 21/46] Simplifies sender recommendation --- bip-0078.mediawiki | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index d4d6b5ac..5e2489e4 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -99,7 +99,7 @@ To ensure compatibility with web-wallets and browser-based-tools, all responses 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. +* 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. @@ -110,7 +110,7 @@ The original PSBT MAY: The payjoin proposal MUST: * Use all the inputs from the original PSBT. * Only finalize the inputs added by the receiver. -* Have all the `witnessUTXO` or `nonWitnessUTXO` information filled in. +* Have all the witnessUTXO or nonWitnessUTXO information filled in. * Keep all the outputs unrelated to the payment. The payjoin proposal MAY: @@ -172,30 +172,27 @@ The receiver needs to do some check on the original PSBT before proceeding: 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. +* 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. -* Check that the sender's own outputs have not been modified, except for paying increased fee, or by simple shuffling. -* If sender specified additionalfeeoutputindex= (see later), the fee should have been subtracted from the output at the same index in the original PSBT. * If minfeerate was specified, check that the estimated fee rate of the payjoin proposal is not less than this value. -* Check that the sent amount in the payjoin proposal is less than or equal to the sent amount of the original transaction. (Defined as the sum of the inputs' value to be signed minus the sender's ouput change) +* 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 the sent amount in the payjoin proposal is above the amount sent in the original PSBT -* Check that the additional paid amount has been add paid to the fee. -* Check that the estimated fee rate of the payjoin proposal is not more than the fee rate of the original PSBT. (fee estimation is hard, so we should allow ~2 satoshi per inputs as margin of error) -* If maxadditionalfeecontribution= was specified, check the additional paid amount is less than or equal to this amount. -* If maxadditionalfeecontribution= was not specified, the sender's software should ask an interactive confirmation to the user. -* maxadditionalfeecontribution= and minfeerate= should be ignored in the [[#spare-change|spare change]] case. +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 should allow the payment output to be modified by the receiver (The receiver may substitute a P2WPKH payment to P2SH payment to increase privacy) -* The sender must allow the receiver to add outputs. -* The sender must allow the receiver to not add any input. Useful for the receiver to change the paymout output scriptPubKey type. +* 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. @@ -229,6 +226,7 @@ If the additionalfeeoutputindex is out of bounds or pointing to the * 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. @@ -246,7 +244,7 @@ To be properly relayed, a Bitcoin transaction needs to pay at least 1 satoshi pe 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)`. +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. @@ -258,7 +256,7 @@ If the payjoin transaction's fee was not increased by the added size, then those 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 `minFeeRate * vsize(1 input)`. +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=== @@ -348,7 +346,7 @@ With payjoin, the maximum amount of money that can be lost is equal to two payme 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. +Senders not supporting payjoin will just ignore the pj variable and thus, will proceed to normal payment. ==Special thanks== From 287e3c2346db931614da31182d485e0a9d07abbe Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Tue, 16 Jun 2020 14:18:19 +0900 Subject: [PATCH 22/46] Fix README --- README.mediawiki | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.mediawiki b/README.mediawiki index ad6a4b00..82baca2f 100644 --- a/README.mediawiki +++ b/README.mediawiki @@ -386,9 +386,9 @@ Those proposing changes should consider that ultimately consent may rest with th | Standard | Final |- style="background-color: #ffffcf" -| [[bip-0078.mediawiki|79]] +| [[bip-0078.mediawiki|78]] | Applications -| Bustapay :: A Simple Payjoin Proposal +| A Simple Payjoin Proposal | Nicolas Dorier | Informational | Proposed From 801cc71114d2c7630f0b58122efb9facb390f4f0 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Tue, 16 Jun 2020 14:25:52 +0900 Subject: [PATCH 23/46] Update PSBT invariants --- bip-0078.mediawiki | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index 5e2489e4..e2e1f27d 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -109,14 +109,15 @@ The original PSBT MAY: The payjoin proposal MUST: * Use all the inputs from the original PSBT. -* Only finalize the inputs added by the receiver. -* Have all the witnessUTXO or nonWitnessUTXO information filled in. -* Keep all the outputs unrelated to the payment. +* 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 inputs. -* Add outputs. -* Modify payment's output. +* 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=== From d72e27535ed7ec3d70c14897519cef779bd93408 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Wed, 17 Jun 2020 15:06:28 +0900 Subject: [PATCH 24/46] [MoveOnly] Move optional parameters at the beginning --- bip-0078.mediawiki | 58 +++++++++++++++++++++++----------------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index e2e1f27d..392949f6 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -119,6 +119,35 @@ The payjoin proposal MAY: 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. +===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. + ===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. @@ -202,35 +231,6 @@ 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: From a07fef579775cd80ae310b91d0277a976b4ef83b Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Wed, 17 Jun 2020 16:04:49 +0900 Subject: [PATCH 25/46] Add fee output section --- bip-0078.mediawiki | 50 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index 392949f6..74ab76c8 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -119,7 +119,7 @@ The payjoin proposal MAY: 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. -===Optional parameters=== +===Optional parameters=== When the payjoin sender posts the original PSBT to the receiver, he can optionally specify the following HTTP query string parameters: @@ -139,9 +139,9 @@ If the receiver does not support the version of the sender, they should send an * 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. +If the additionalfeeoutputindex is out of bounds or pointing to the payment output meant for the receiver, the receiver should ignore the parameter. See [[#fee-output|fee output]] for more information. -* 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. +* 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. See [[#fee-output|fee output]] for more information. 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. @@ -187,6 +187,44 @@ 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. +===Fee output=== + +In some situation, the sender might want to pay some additional fee in the payjoin proposal. +If such is the case, the sender must use both [[#optional-params|optional parameters]] additionalfeeoutputindex= and maxadditionalfeecontribution= to indicate which output and how much the receiver can substract fee. + +There is several cases where a fee output is useful: + +* The sender's original transaction's fee rate is at the minimum accepted by the network, aka minimum relay transaction fee rate, which is typically 1 satoshi per vbyte. + +In such case, the receiver will need to increase the fee of the transaction after adding his own inputs to not drop below the minimum relay transaction fee rate. + +* The sender's wallet software is using round fee rate. + +If the sender's fee rate is always round, then a blockchain analyst can easily spot the transactions of the sender involving payjoin by checking if, when removing a single input to the suspected payjoin transaction, the resulting fee rate is round. +To prevent this, the sender can agree to pay more more fee so the receiver make sure that the payjoin transaction fee is also round. + +* The sender's transaction is time sensitive. + +When a sender pick a specific fee rate, the sender expects the transaction to be confirmed after a specific amount of time. But if the receiver adds an input without bumping the fee of the transaction, the payjoin transaction fee rate will be lower, and thus, longer to confirm. + +Our recommendation for maxadditionalfeecontribution= is originalPSBTFeeRate * vsize(sender_input_type). + +{| class="wikitable" +!sender_input_type +!vsize(sender_input_type) +|- +|P2WPKH +|68 +|- +|P2PKH +|148 +|- +|P2SH-P2WPKH +|91 +|} + + + ===Receiver's original PSBT checklist=== The receiver needs to do some check on the original PSBT before proceeding: @@ -216,7 +254,7 @@ The sender should check the payjoin proposal before signing it to prevent a mali 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 actual contribution is less or equals to originalPSBTFeeRate * vsize(sender_input_type) * (count(original_psbt_inputs) - count(payjoin_proposal_inputs)). (This make sure the contribution only pays for additional inputs, see [[#fee-output|Fee output]] section) The sender must be careful to only sign the inputs that were present in the original PSBT and nothing else. @@ -245,7 +283,7 @@ To be properly relayed, a Bitcoin transaction needs to pay at least 1 satoshi pe 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). +See the [[#fee-output|Fee output]] section for more information. We also recommend the sender to set minfeerate=, as the sender's node policy might be different from the receiver's policy. @@ -257,7 +295,7 @@ If the payjoin transaction's fee was not increased by the added size, then those 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). +The recommended value maxadditionalfeecontribution= is explained in the [[#fee-output|Fee output]] section. 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=== From f36ca8f43d51a71b6f5528baa65091e75433ed44 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Wed, 17 Jun 2020 16:15:53 +0900 Subject: [PATCH 26/46] Update recommendation for receiver and sender --- bip-0078.mediawiki | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index 74ab76c8..5c06c2fd 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -232,8 +232,9 @@ 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. +* Make sure that the inputs included in the original transaction has never been seen before. (Prevent [[#probing-attack|probing attacks]].) -*: Interactive receivers are not required to validate the original PSBT because they are not exposed to probing attacks. +*: Interactive receivers are not required to validate the original PSBT because they are not exposed to [[#probing-attack|probing attacks]]. ===Sender's payjoin proposal checklist=== @@ -266,9 +267,6 @@ Note: 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. - ==Rationale== There is several consequences of our proposal: @@ -348,7 +346,7 @@ For this reason, during a [[#spare-change|spare change]] case, the receiver may ==Attack vectors== -===On the receiver side: UTXO probing attack=== +===On the receiver side: UTXO probing attack=== When the receiver creates a payjoin proposal, they expose one or more inputs belonging to them. From 3fc7032ec33724eb9a79939358db6729fd3d87c2 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Wed, 17 Jun 2020 16:20:38 +0900 Subject: [PATCH 27/46] Fix some formatting --- bip-0078.mediawiki | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index 5c06c2fd..621e0d92 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -249,13 +249,13 @@ The sender should check the payjoin proposal before signing it to prevent a mali * 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. +** 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(sender_input_type) * (count(original_psbt_inputs) - count(payjoin_proposal_inputs)). (This make sure the contribution only pays for additional inputs, see [[#fee-output|Fee output]] section) +If a [[#fee-output|fee ouptut]] exists, 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. +* Make sure the contribution are only paying fee: The actual contribution is less or equals to the difference of absolute fee between the payjoin proposal and the original PSBT. +* Make sure the contribution are only paying for fee incurred by additional inputs: actual contribution is less or equals to originalPSBTFeeRate * vsize(sender_input_type) * (count(original_psbt_inputs) - count(payjoin_proposal_inputs)). (see [[#fee-output|Fee output]] section) The sender must be careful to only sign the inputs that were present in the original PSBT and nothing else. From ea7562fc9055227adb129ba0144556e3be050d77 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Wed, 17 Jun 2020 21:51:09 +0900 Subject: [PATCH 28/46] Fix old error code --- bip-0078.mediawiki | 42 ++++++++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index 621e0d92..ddde6139 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -230,7 +230,7 @@ Our recommendation for maxadditionalfeecontribution= is origi 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 included inputs in the original PSBT owned by the receiver, the receiver must either return error original-psbt-rejected 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. * Make sure that the inputs included in the original transaction has never been seen before. (Prevent [[#probing-attack|probing attacks]].) @@ -240,22 +240,32 @@ The receiver needs to do some check on the original PSBT before proceeding: 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. +* Verify that the transaction version, and the 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|fee ouptut]] exists, 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. -* Make sure the contribution are only paying fee: The actual contribution is less or equals to the difference of absolute fee between the payjoin proposal and the original PSBT. -* Make sure the contribution are only paying for fee incurred by additional inputs: actual contribution is less or equals to originalPSBTFeeRate * vsize(sender_input_type) * (count(original_psbt_inputs) - count(payjoin_proposal_inputs)). (see [[#fee-output|Fee output]] section) +* For each inputs in the proposal: +** Verify that no keypaths is in the PSBT input +** Verify that no partial signature has been filled +** If it is one of the sender's input +*** Verify that input's sequence is unchanged. +*** Verify the PSBT input is not finalized +*** Verify that non_witness_utxo and witness_utxo are not specified. +** If it is one of the receiver's input +*** Verify the PSBT input is finalized +*** Verify that non_witness_utxo or witness_utxo are filled in. +** Verify that the payjoin proposal did not introduced mixed input's sequence. +** Verify that the payjoin proposal did not introduced mixed input's type. +** Verify that all of sender's inputs from the original PSBT are in the proposal. +* For each outputs in the proposal: +** Verify that no keypaths is in the PSBT output +** If it is one of the sender's output +*** If that's the [[#fee-output|fee ouptut]]: +**** The amount that was substracted from the output's value is less or equal to maxadditionalfeecontribution. Let's call this amount actual contribution. +**** Make sure the actual contribution is only paying fee: The actual contribution is less or equals to the difference of absolute fee between the payjoin proposal and the original PSBT. +**** Make sure the actual contribution is only paying for fee incurred by additional inputs: actual contribution is less or equals to originalPSBTFeeRate * vsize(sender_input_type) * (count(original_psbt_inputs) - count(payjoin_proposal_inputs)). (see [[#fee-output|Fee output]] section) +*** If it is not the fee output: +**** Make sure the output's value did not changed. +** Verify that all sender's outputs (ie, all outputs except the output actually paid to the receiver) from the original PSBT are in the proposal. +* Once the proposal is signed, if minfeerate was specified, check that the fee rate of the payjoin transaction is not less than this value. The sender must be careful to only sign the inputs that were present in the original PSBT and nothing else. From 3485af708ce5a485d30cd8f60efe0004e9b4566c Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Wed, 17 Jun 2020 22:26:03 +0900 Subject: [PATCH 29/46] Add reference implementation --- bip-0078.mediawiki | 232 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 232 insertions(+) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index ddde6139..70adf1c0 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -381,6 +381,238 @@ Without payjoin, the maximum amount of money that could be lost by a compromised With payjoin, the maximum amount of money that can be lost is equal to two payments. +==Reference sender's implementation== + +Here is pseudo code of a sender implementation. +RequestPayjoin takes the bip21 URI of the payment, the wallet and the signedPSBT. + +The signedPSBT represents a PSBT which has been fully signed, but not yet finalized. +We then prepare originalPSBT from the signedPSBT via the CreateOriginalPSBT function and get back the proposal. + +While we verify the proposal, we also import into it informations about our own inputs and outputs from the signedPSBT. +At the end of this RequestPayjoin, the proposal is verified and ready to be signed. + +We logged the different PSBT involved, and show the result in our [[#test-vectors|test vectors]]. +
+public async Task RequestPayjoin(
+    BIP21Uri bip21,
+    Wallet wallet,
+    PSBT signedPSBT,
+    PayjoinClientParameters optionalParameters)
+{
+    Log("signed PSBT" + signedPSBT);
+    var endpoint = bip21.ExtractPayjointEndpoint();
+    if (signedPSBT.IsAllFinalized())
+        throw new InvalidOperationException("The original PSBT should not be finalized.");
+    ScriptPubKeyType inputScriptType = wallet.ScriptPubKeyType();
+    PSBTOutput feePSBTOutput = null;
+    if (optionalParameters.AdditionalFeeOutputIndex != null && optionalParameters.MaxAdditionalFeeContribution != null)
+        feePSBTOutput = signedPSBT.Outputs[optionalParameters.AdditionalFeeOutputIndex];
+    decimal originalFee = signedPSBT.GetFee();
+    PSBT originalPSBT = CreateOriginalPSBT(signedPSBT);
+    Transaction originalGlobalTx = signedPSBT.GetGlobalTransaction();
+    TxOut feeOutput = feePSBTOutput == null ? null : originalGlobalTx.Outputs[feePSBTOutput.Index];
+    var ourInputs = new Queue<(TxIn OriginalTxIn, PSBTInput SignedPSBTInput)>();
+    for (int i = 0; i < originalGlobalTx.Inputs.Count; i++)
+    {
+        ourInputs.Enqueue((originalGlobalTx.Inputs[i], signedPSBT.Inputs[i]));
+    }
+    var ourOutputs = new Queue<(TxOut OriginalTxOut, PSBTOutput SignedPSBTOutput)>();
+    for (int i = 0; i < originalGlobalTx.Outputs.Count; i++)
+    {
+        if (signedPSBT.Outputs[i].ScriptPubKey != bip21.Address.ScriptPubKey)
+            ourOutputs.Enqueue((originalGlobalTx.Outputs[i], signedPSBT.Outputs[i]));
+    }
+    endpoint = ApplyOptionalParameters(endpoint, optionalParameters);
+    Log("original PSBT" + originalPSBT);
+    PSBT proposal = await SendOriginalTransaction(endpoint, originalPSBT, cancellationToken);
+    Log("payjoin proposal" + proposal);
+    // Checking that the PSBT of the receiver is clean
+    if (proposal.GlobalXPubs.Any())
+    {
+        throw new PayjoinSenderException("GlobalXPubs should not be included in the receiver's PSBT");
+    }
+    ////////////
+
+    if (proposal.CheckSanity() is List errors && errors.Count > 0)
+        throw new PayjoinSenderException($"The proposal PSBT is not insance ({errors[0]})");
+
+    var proposalGlobalTx = proposal.GetGlobalTransaction();
+    // Verify that the transaction version, and nLockTime are unchanged.
+    if (proposalGlobalTx.Version != originalGlobalTx.Version)
+        throw new PayjoinSenderException($"The proposal PSBT changed the transaction version");
+    if (proposalGlobalTx.LockTime != originalGlobalTx.LockTime)
+        throw new PayjoinSenderException($"The proposal PSBT changed the nLocktime");
+
+    HashSet sequences = new HashSet();
+    // For each inputs in the proposal:
+    foreach (PSBTInput proposedPSBTInput in proposal.Inputs)
+    {
+        if (proposedPSBTInput.HDKeyPaths.Count != 0)
+            throw new PayjoinSenderException("The receiver added keypaths to an input");
+        if (proposedPSBTInput.PartialSigs.Count != 0)
+            throw new PayjoinSenderException("The receiver added partial signatures to an input");
+        PSBTInput proposedTxIn = proposalGlobalTx.Inputs.FindIndexedInput(proposedPSBTInput.PrevOut).TxIn;
+        bool isOurInput = ourInputs.Count > 0 && ourInputs.Peek().OriginalTxIn.PrevOut == proposedPSBTInput.PrevOut;
+        // If it is one of our input
+        if (isOurInput)
+        {
+            OutPoint inputPrevout = ourPrevouts.Dequeue();
+            TxIn originalTxin = originalGlobalTx.Inputs.FromOutpoint(inputPrevout);
+            PSBTInput originalPSBTInput = originalPSBT.Inputs.FromOutpoint(inputPrevout);
+            // Verify that sequence is unchanged.
+            if (input.OriginalTxIn.Sequence != proposedTxIn.Sequence)
+                throw new PayjoinSenderException("The proposedTxIn modified the sequence of one of our inputs")
+            // Verify the PSBT input is not finalized
+            if (proposedPSBTInput.IsFinalized())
+                throw new PayjoinSenderException("The receiver finalized one of our inputs");
+            // Verify that non_witness_utxo and witness_utxo are not specified.
+            if (proposedPSBTInput.NonWitnessUtxo != null || proposedPSBTInput.WitnessUtxo != null)
+                throw new PayjoinSenderException("The receiver added non_witness_utxo or witness_utxo to one of our inputs");
+            sequences.Add(proposedTxIn.Sequence);
+            
+            // Fill up the info from the original PSBT input so we can sign and get fees.
+            proposedPSBTInput.NonWitnessUtxo = input.SignedPSBTInput.NonWitnessUtxo;
+            proposedPSBTInput.WitnessUtxo = input.SignedPSBTInput.WitnessUtxo;
+            // We fill up information we had on the signed PSBT, so we can sign it.
+            foreach (var hdKey in input.SignedPSBTInput.HDKeyPaths)
+            proposedPSBTInput.HDKeyPaths.Add(hdKey.Key, hdKey.Value);
+            proposedPSBTInput.RedeemScript = signedPSBTInput.RedeemScript;
+            proposedPSBTInput.RedeemScript = input.SignedPSBTInput.RedeemScript;
+        }
+        else
+        {
+            // Verify the PSBT input is finalized
+            if (!proposedPSBTInput.IsFinalized())
+                throw new PayjoinSenderException("The receiver did not finalized one of their input");
+            // Verify that non_witness_utxo or witness_utxo are filled in.
+            if (proposedPSBTInput.NonWitnessUtxo == null && proposedPSBTInput.WitnessUtxo == null)
+                throw new PayjoinSenderException("The receiver did not specify non_witness_utxo or witness_utxo for one of their inputs");
+            sequences.Add(proposedTxIn.Sequence);
+            // Verify that the payjoin proposal did not introduced mixed input's type.
+            if (inputScriptType != proposedPSBTInput.GetInputScriptPubKeyType())
+                throw new PayjoinSenderException("Mixed input type detected in the proposal");
+        }
+    }
+
+    // Verify that all of sender's inputs from the original PSBT are in the proposal.
+    if (ourInputs.Count != 0)
+        throw new PayjoinSenderException("Some of our inputs are not included in the proposal");
+
+    // Verify that the payjoin proposal did not introduced mixed input's sequence.
+    if (sequences.Count != 1)
+        throw new PayjoinSenderException("Mixed sequence detected in the proposal");
+
+    // For each outputs in the proposal:
+    foreach (PSBTOutput proposedPSBTOutput in proposal.Outputs)
+    {
+        // Verify that no keypaths is in the PSBT output
+        if (proposedPSBTOutput.HDKeyPaths.Count != 0)
+            throw new PayjoinSenderException("The receiver added keypaths to an output");
+        bool isOurOutput = ourOutputs.Count > 0 && ourOutputs.Peek().OriginalTxOut.ScriptPubKey == proposedPSBTOutput.ScriptPubKey;
+        if (isOurOutput)
+        {
+            var output = ourOutputs.Dequeue();
+            if (output.OriginalTxOut == feeOutput)
+            {
+                var actualContribution = feeOutput.Value - proposedPSBTOutput.Value;
+                // The amount that was substracted from the output's value is less or equal to maxadditionalfeecontribution
+                if (actualContribution > optionalParameters.MaxAdditionalFeeContribution)
+                    throw new PayjoinSenderException("The actual contribution is more than maxadditionalfeecontribution");
+                decimal newFee = proposal.GetFee();
+                decimal additionalFee = newFee - originalFee;
+                // Make sure the actual contribution is only paying fee
+                if (actualContribution > additionalFee)
+                    throw new PayjoinSenderException("The actual contribution is not only paying fee");
+                // Make sure the actual contribution is only paying for fee incurred by additional inputs
+                int additionalInputsCount = proposalGlobalTx.Inputs.Count - originalGlobalTx.Inputs.Count;
+                if (actualContribution > originalFeeRate * GetVirtualSize(inputScriptType) * additionalInputsCount)
+                    throw new PayjoinSenderException("The actual contribution is not only paying for additional inputs");
+            }
+            else
+            {
+                if (output.OriginalTxOut.Value != proposedPSBTOutput.Value)
+                    throw new PayjoinSenderException("The receiver changed one of our outputs");
+            }
+            // We fill up information we had on the signed PSBT, so we can sign it.
+            foreach (var hdKey in output.SignedPSBTOutput.HDKeyPaths)
+                proposedPSBTOutput.HDKeyPaths.Add(hdKey.Key, hdKey.Value);
+            proposedPSBTOutput.RedeemScript = output.SignedPSBTOutput.RedeemScript;
+        }
+    }
+    // Verify that all of sender's outputs from the original PSBT are in the proposal.
+    if (ourOutputs.Count != 0)
+        throw new PayjoinSenderException("Some of our outputs are not included in the proposal");
+
+    // After signing this proposal, we should check if minfeerate is respected.
+    Log("payjoin proposal filled with sender's information" + proposal);
+    return proposal;
+}
+
+int GetVirtualSize(ScriptPubKeyType? scriptPubKeyType)
+{
+    switch (scriptPubKeyType)
+    {
+        case ScriptPubKeyType.Legacy:
+            return 148;
+        case ScriptPubKeyType.Segwit:
+            return 68;
+        case ScriptPubKeyType.SegwitP2SH:
+            return 91;
+        default:
+            return 110;
+    }
+}
+
+// Finalized the signedPSBT and remove confidential information
+PSBT CreateOriginalPSBT(PSBT signedPSBT)
+{
+    var original = signedPSBT.Clone();
+    original = original.Finalize();
+    foreach (var input in original.Inputs)
+    {
+        input.HDKeyPaths.Clear();
+        input.PartialSigs.Clear();
+        input.Unknown.Clear();
+    }
+    foreach (var output in original.Outputs)
+    {
+        output.Unknown.Clear();
+        output.HDKeyPaths.Clear();
+    }
+    original.GlobalXPubs.Clear();
+    return original;
+}
+
+ +==Test vectors== + +A successful exchange with: + +{| class="wikitable" +!InputScriptType +!Orginal PSBT Fee rate +!maxadditionalfeecontribution +!additionalfeeoutputindex +|- +|P2SH-P2WSH +|2 sat/vbyte +|0.00000182 +|0 +|} + +signed PSBT +
cHNidP8BAHMCAAAAAY8nutGgJdyYGXWiBEb45Hoe9lWGbkxh/6bNiOJdCDuDAAAAAAD+////AtyVuAUAAAAAF6kUHehJ8GnSdBUOOv6ujXLrWmsJRDCHgIQeAAAAAAAXqRR3QJbbz0hnQ8IvQ0fptGn+votneofTAAAAAAEBIKgb1wUAAAAAF6kU3k4ekGHKWRNbA1rV5tR5kEVDVNCHAQQWABTHikVyU1WCjVZYB03VJg1fy2mFMCICAxWawBqg1YdUxLTYt9NJ7R7fzws2K09rVRBnI6KFj4UWRzBEAiB8Q+A6dep+Rz92vhy26lT0AjZn4PRLi8Bf9qoB/CMk0wIgP/Rj2PWZ3gEjUkTlhDRNAQ0gXwTO7t9n+V14pZ6oljUBIgYDFZrAGqDVh1TEtNi300ntHt/PCzYrT2tVEGcjooWPhRYYSFzWUDEAAIABAACAAAAAgAEAAAAAAAAAAAEAFgAURvYaK7pzgo7lhbSl/DeUan2MxRQiAgLKC8FYHmmul/HrXLUcMDCjfuRg/dhEkG8CO26cEC6vfBhIXNZQMQAAgAEAAIAAAACAAQAAAAEAAAAAAA==
+ +original PSBT +
cHNidP8BAHMCAAAAAY8nutGgJdyYGXWiBEb45Hoe9lWGbkxh/6bNiOJdCDuDAAAAAAD+////AtyVuAUAAAAAF6kUHehJ8GnSdBUOOv6ujXLrWmsJRDCHgIQeAAAAAAAXqRR3QJbbz0hnQ8IvQ0fptGn+votneofTAAAAAAEBIKgb1wUAAAAAF6kU3k4ekGHKWRNbA1rV5tR5kEVDVNCHAQcXFgAUx4pFclNVgo1WWAdN1SYNX8tphTABCGsCRzBEAiB8Q+A6dep+Rz92vhy26lT0AjZn4PRLi8Bf9qoB/CMk0wIgP/Rj2PWZ3gEjUkTlhDRNAQ0gXwTO7t9n+V14pZ6oljUBIQMVmsAaoNWHVMS02LfTSe0e388LNitPa1UQZyOihY+FFgABABYAFEb2Giu6c4KO5YW0pfw3lGp9jMUUAAA=
+ +payjoin proposal +
cHNidP8BAJwCAAAAAo8nutGgJdyYGXWiBEb45Hoe9lWGbkxh/6bNiOJdCDuDAAAAAAD+////jye60aAl3JgZdaIERvjkeh72VYZuTGH/ps2I4l0IO4MBAAAAAP7///8CJpW4BQAAAAAXqRQd6EnwadJ0FQ46/q6NcutaawlEMIcACT0AAAAAABepFHdAltvPSGdDwi9DR+m0af6+i2d6h9MAAAAAAAEBIICEHgAAAAAAF6kUyPLL+cphRyyI5GTUazV0hF2R2NWHAQcXFgAUX4BmVeWSTJIEwtUb5TlPS/ntohABCGsCRzBEAiBnu3tA3yWlT0WBClsXXS9j69Bt+waCs9JcjWtNjtv7VgIge2VYAaBeLPDB6HGFlpqOENXMldsJezF9Gs5amvDQRDQBIQJl1jz1tBt8hNx2owTm+4Du4isx0pmdKNMNIjjaMHFfrQAAAA==
+ +payjoin proposal filled with sender's information +
cHNidP8BAJwCAAAAAo8nutGgJdyYGXWiBEb45Hoe9lWGbkxh/6bNiOJdCDuDAAAAAAD+////jye60aAl3JgZdaIERvjkeh72VYZuTGH/ps2I4l0IO4MBAAAAAP7///8CJpW4BQAAAAAXqRQd6EnwadJ0FQ46/q6NcutaawlEMIcACT0AAAAAABepFHdAltvPSGdDwi9DR+m0af6+i2d6h9MAAAAAAQEgqBvXBQAAAAAXqRTeTh6QYcpZE1sDWtXm1HmQRUNU0IcBBBYAFMeKRXJTVYKNVlgHTdUmDV/LaYUwIgYDFZrAGqDVh1TEtNi300ntHt/PCzYrT2tVEGcjooWPhRYYSFzWUDEAAIABAACAAAAAgAEAAAAAAAAAAAEBIICEHgAAAAAAF6kUyPLL+cphRyyI5GTUazV0hF2R2NWHAQcXFgAUX4BmVeWSTJIEwtUb5TlPS/ntohABCGsCRzBEAiBnu3tA3yWlT0WBClsXXS9j69Bt+waCs9JcjWtNjtv7VgIge2VYAaBeLPDB6HGFlpqOENXMldsJezF9Gs5amvDQRDQBIQJl1jz1tBt8hNx2owTm+4Du4isx0pmdKNMNIjjaMHFfrQABABYAFEb2Giu6c4KO5YW0pfw3lGp9jMUUIgICygvBWB5prpfx61y1HDAwo37kYP3YRJBvAjtunBAur3wYSFzWUDEAAIABAACAAAAAgAEAAAABAAAAAAA=
+ ==Implementations== * [[https://github.com/BlueWallet/BlueWallet|BlueWallet]] is in the process of implementing the protocol. From 63aa576facc816bd78e41b41411c15bfca5c895e Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Thu, 18 Jun 2020 09:59:44 +0900 Subject: [PATCH 30/46] Update from RHavar remarks --- bip-0078.mediawiki | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index 70adf1c0..3b9820a6 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -52,7 +52,6 @@ Another implementation proposal has been written: [[https://github.com/bitcoin/b 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. @@ -232,7 +231,9 @@ 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 original-psbt-rejected 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. -* Make sure that the inputs included in the original transaction has never been seen before. (Prevent [[#probing-attack|probing attacks]].) +* Make sure that the inputs included in the original transaction have never been seen before. +** This prevent [[#probing-attack|probing attacks]]. +** This prevent reentrant payjoin, where a sender attempts to use payjoin transaction as a new original transaction for a new payjoin. *: Interactive receivers are not required to validate the original PSBT because they are not exposed to [[#probing-attack|probing attacks]]. @@ -377,7 +378,7 @@ The sender's software wallet can verify that the payjoin proposal is legitimate 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). +Without payjoin, the maximum amount of money that could be lost by a compromised software is equal to one payment (via [[#output-substitution|payment output substitution]]). With payjoin, the maximum amount of money that can be lost is equal to two payments. From a2a085cdb4590a5219292522e5295903d5157e99 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Thu, 18 Jun 2020 10:11:20 +0900 Subject: [PATCH 31/46] Add disableoutputsubstitution= optional parameter --- bip-0078.mediawiki | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index 3b9820a6..6a008584 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -147,6 +147,8 @@ This fee contribution can't be used to pay for anything else than additional inp * 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. +* disableoutputsubstitution=, a boolean indicating if the sender forbids the receiver to modify his own output, see [[#output-substitution|payment output substitution]]. (default to false) + ===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. @@ -271,7 +273,7 @@ The sender should check the payjoin proposal before signing it to prevent a mali 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 must allow the receiver to add/remove or modify his own outputs (Except is explicitely disabled via the optional parameter disableoutputsubstitution=) * 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. @@ -421,7 +423,8 @@ public async Task RequestPayjoin( var ourOutputs = new Queue<(TxOut OriginalTxOut, PSBTOutput SignedPSBTOutput)>(); for (int i = 0; i < originalGlobalTx.Outputs.Count; i++) { - if (signedPSBT.Outputs[i].ScriptPubKey != bip21.Address.ScriptPubKey) + if (optionalParameters.DisableOutputSubstitution || + signedPSBT.Outputs[i].ScriptPubKey != bip21.Address.ScriptPubKey) ourOutputs.Enqueue((originalGlobalTx.Outputs[i], signedPSBT.Outputs[i])); } endpoint = ApplyOptionalParameters(endpoint, optionalParameters); From a3fbc6c6203ef7ded879626ee2fcb689195a7ec1 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Thu, 18 Jun 2020 11:04:59 +0900 Subject: [PATCH 32/46] Do not crash reference implementation if there is no address in the bip21 --- bip-0078.mediawiki | 1 + 1 file changed, 1 insertion(+) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index 6a008584..bf75ddfa 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -424,6 +424,7 @@ public async Task RequestPayjoin( for (int i = 0; i < originalGlobalTx.Outputs.Count; i++) { if (optionalParameters.DisableOutputSubstitution || + bip21.Address == null || signedPSBT.Outputs[i].ScriptPubKey != bip21.Address.ScriptPubKey) ourOutputs.Enqueue((originalGlobalTx.Outputs[i], signedPSBT.Outputs[i])); } From 7803bf8335780ae2fdcc256e4edd81bb9681089d Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Fri, 19 Jun 2020 13:16:16 +0900 Subject: [PATCH 33/46] Reformat the check list for sender --- bip-0078.mediawiki | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index bf75ddfa..d43249f1 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -260,13 +260,14 @@ The sender should check the payjoin proposal before signing it to prevent a mali ** Verify that all of sender's inputs from the original PSBT are in the proposal. * For each outputs in the proposal: ** Verify that no keypaths is in the PSBT output -** If it is one of the sender's output -*** If that's the [[#fee-output|fee ouptut]]: -**** The amount that was substracted from the output's value is less or equal to maxadditionalfeecontribution. Let's call this amount actual contribution. -**** Make sure the actual contribution is only paying fee: The actual contribution is less or equals to the difference of absolute fee between the payjoin proposal and the original PSBT. -**** Make sure the actual contribution is only paying for fee incurred by additional inputs: actual contribution is less or equals to originalPSBTFeeRate * vsize(sender_input_type) * (count(original_psbt_inputs) - count(payjoin_proposal_inputs)). (see [[#fee-output|Fee output]] section) -*** If it is not the fee output: -**** Make sure the output's value did not changed. +** If the output is the [[#fee-output|fee ouptut]]: +*** The amount that was substracted from the output's value is less or equal to maxadditionalfeecontribution. Let's call this amount actual contribution. +*** Make sure the actual contribution is only paying fee: The actual contribution is less or equals to the difference of absolute fee between the payjoin proposal and the original PSBT. +*** Make sure the actual contribution is only paying for fee incurred by additional inputs: actual contribution is less or equals to originalPSBTFeeRate * vsize(sender_input_type) * (count(original_psbt_inputs) - count(payjoin_proposal_inputs)). (see [[#fee-output|Fee output]] section) +** If the output is the payment output and disableoutputsubstitution= is falseminfeerate
was specified, check that the fee rate of the payjoin transaction is not less than this value. From 3a16c24f5e87614ac42173927297f0d013fdc0f2 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Fri, 19 Jun 2020 13:23:37 +0900 Subject: [PATCH 34/46] Additional note for HW --- bip-0078.mediawiki | 1 + 1 file changed, 1 insertion(+) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index d43249f1..2acee5d2 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -382,6 +382,7 @@ The sender's software wallet can verify that the payjoin proposal is legitimate 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 [[#output-substitution|payment output substitution]]). +Note that the sender can opt out payment output substitution my using the optional parameter disableoutputsubstitution=true. With payjoin, the maximum amount of money that can be lost is equal to two payments. From 93c655a1495b61afb9de30970db9353872145e42 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Fri, 19 Jun 2020 13:24:14 +0900 Subject: [PATCH 35/46] Fix typo --- bip-0078.mediawiki | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index 2acee5d2..d070178d 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -442,7 +442,7 @@ public async Task RequestPayjoin( //////////// if (proposal.CheckSanity() is List errors && errors.Count > 0) - throw new PayjoinSenderException($"The proposal PSBT is not insance ({errors[0]})"); + throw new PayjoinSenderException($"The proposal PSBT is not sane ({errors[0]})"); var proposalGlobalTx = proposal.GetGlobalTransaction(); // Verify that the transaction version, and nLockTime are unchanged. @@ -571,7 +571,7 @@ int GetVirtualSize(ScriptPubKeyType? scriptPubKeyType) } } -// Finalized the signedPSBT and remove confidential information +// Finalize the signedPSBT and remove confidential information PSBT CreateOriginalPSBT(PSBT signedPSBT) { var original = signedPSBT.Clone(); From 6d4b491b31554b78d3c662489ca3ee746ec94651 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Fri, 19 Jun 2020 14:26:51 +0900 Subject: [PATCH 36/46] Simplify sender's implementation, fix typos --- bip-0078.mediawiki | 50 +++++++++++++++++++++++++++------------------- 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index d070178d..f2fd04d7 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -260,7 +260,7 @@ The sender should check the payjoin proposal before signing it to prevent a mali ** Verify that all of sender's inputs from the original PSBT are in the proposal. * For each outputs in the proposal: ** Verify that no keypaths is in the PSBT output -** If the output is the [[#fee-output|fee ouptut]]: +** If the output is the [[#fee-output|fee output]]: *** The amount that was substracted from the output's value is less or equal to maxadditionalfeecontribution. Let's call this amount actual contribution. *** Make sure the actual contribution is only paying fee: The actual contribution is less or equals to the difference of absolute fee between the payjoin proposal and the original PSBT. *** Make sure the actual contribution is only paying for fee incurred by additional inputs: actual contribution is less or equals to originalPSBTFeeRate * vsize(sender_input_type) * (count(original_psbt_inputs) - count(payjoin_proposal_inputs)). (see [[#fee-output|Fee output]] section) @@ -274,8 +274,8 @@ The sender should check the payjoin proposal before signing it to prevent a mali 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 (Except is explicitely disabled via the optional parameter disableoutputsubstitution=) -* The sender should allow the receiver to not add any input. Useful for the receiver to change the paymout output scriptPubKey type. +* The sender must allow the receiver to add/remove or modify the receiver's own outputs (Except if explicitly disabled via the optional parameter disableoutputsubstitution=) +* The sender should allow the receiver to not add any inputs. This is 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. @@ -413,22 +413,20 @@ public async Task RequestPayjoin( PSBTOutput feePSBTOutput = null; if (optionalParameters.AdditionalFeeOutputIndex != null && optionalParameters.MaxAdditionalFeeContribution != null) feePSBTOutput = signedPSBT.Outputs[optionalParameters.AdditionalFeeOutputIndex]; + Script paymentScriptPubKey = bip21.Address == null ? null : bip21.Address.ScriptPubKey; decimal originalFee = signedPSBT.GetFee(); PSBT originalPSBT = CreateOriginalPSBT(signedPSBT); Transaction originalGlobalTx = signedPSBT.GetGlobalTransaction(); TxOut feeOutput = feePSBTOutput == null ? null : originalGlobalTx.Outputs[feePSBTOutput.Index]; - var ourInputs = new Queue<(TxIn OriginalTxIn, PSBTInput SignedPSBTInput)>(); + var originalInputs = new Queue<(TxIn OriginalTxIn, PSBTInput SignedPSBTInput)>(); for (int i = 0; i < originalGlobalTx.Inputs.Count; i++) { - ourInputs.Enqueue((originalGlobalTx.Inputs[i], signedPSBT.Inputs[i])); + originalInputs.Enqueue((originalGlobalTx.Inputs[i], signedPSBT.Inputs[i])); } - var ourOutputs = new Queue<(TxOut OriginalTxOut, PSBTOutput SignedPSBTOutput)>(); + var originalOutputs = new Queue<(TxOut OriginalTxOut, PSBTOutput SignedPSBTOutput)>(); for (int i = 0; i < originalGlobalTx.Outputs.Count; i++) { - if (optionalParameters.DisableOutputSubstitution || - bip21.Address == null || - signedPSBT.Outputs[i].ScriptPubKey != bip21.Address.ScriptPubKey) - ourOutputs.Enqueue((originalGlobalTx.Outputs[i], signedPSBT.Outputs[i])); + originalOutputs.Enqueue((originalGlobalTx.Outputs[i], signedPSBT.Outputs[i])); } endpoint = ApplyOptionalParameters(endpoint, optionalParameters); Log("original PSBT" + originalPSBT); @@ -460,7 +458,7 @@ public async Task RequestPayjoin( if (proposedPSBTInput.PartialSigs.Count != 0) throw new PayjoinSenderException("The receiver added partial signatures to an input"); PSBTInput proposedTxIn = proposalGlobalTx.Inputs.FindIndexedInput(proposedPSBTInput.PrevOut).TxIn; - bool isOurInput = ourInputs.Count > 0 && ourInputs.Peek().OriginalTxIn.PrevOut == proposedPSBTInput.PrevOut; + bool isOurInput = originalInputs.Count > 0 && originalInputs.Peek().OriginalTxIn.PrevOut == proposedPSBTInput.PrevOut; // If it is one of our input if (isOurInput) { @@ -496,17 +494,17 @@ public async Task RequestPayjoin( if (proposedPSBTInput.NonWitnessUtxo == null && proposedPSBTInput.WitnessUtxo == null) throw new PayjoinSenderException("The receiver did not specify non_witness_utxo or witness_utxo for one of their inputs"); sequences.Add(proposedTxIn.Sequence); - // Verify that the payjoin proposal did not introduced mixed input's type. + // Verify that the payjoin proposal did not introduced mixed inputs' type. if (inputScriptType != proposedPSBTInput.GetInputScriptPubKeyType()) throw new PayjoinSenderException("Mixed input type detected in the proposal"); } } // Verify that all of sender's inputs from the original PSBT are in the proposal. - if (ourInputs.Count != 0) + if (originalInputs.Count != 0) throw new PayjoinSenderException("Some of our inputs are not included in the proposal"); - // Verify that the payjoin proposal did not introduced mixed input's sequence. + // Verify that the payjoin proposal did not introduced mixed inputs' sequence. if (sequences.Count != 1) throw new PayjoinSenderException("Mixed sequence detected in the proposal"); @@ -516,10 +514,10 @@ public async Task RequestPayjoin( // Verify that no keypaths is in the PSBT output if (proposedPSBTOutput.HDKeyPaths.Count != 0) throw new PayjoinSenderException("The receiver added keypaths to an output"); - bool isOurOutput = ourOutputs.Count > 0 && ourOutputs.Peek().OriginalTxOut.ScriptPubKey == proposedPSBTOutput.ScriptPubKey; - if (isOurOutput) + bool isOriginalOutput = originalOutputs.Count > 0 && originalOutputs.Peek().OriginalTxOut.ScriptPubKey == proposedPSBTOutput.ScriptPubKey; + if (isOriginalOutput) { - var output = ourOutputs.Dequeue(); + var originalOutput = originalOutputs.Dequeue(); if (output.OriginalTxOut == feeOutput) { var actualContribution = feeOutput.Value - proposedPSBTOutput.Value; @@ -536,9 +534,13 @@ public async Task RequestPayjoin( if (actualContribution > originalFeeRate * GetVirtualSize(inputScriptType) * additionalInputsCount) throw new PayjoinSenderException("The actual contribution is not only paying for additional inputs"); } + else if (!optionalParameters.DisableOutputSubstitution && output.OriginalTxOut.ScriptPubKey == paymentScriptPubKey) + { + // That's the payment output, the receiver may have changed it. + } else { - if (output.OriginalTxOut.Value != proposedPSBTOutput.Value) + if (originalOutput.OriginalTxOut.Value != proposedPSBTOutput.Value) throw new PayjoinSenderException("The receiver changed one of our outputs"); } // We fill up information we had on the signed PSBT, so we can sign it. @@ -548,8 +550,16 @@ public async Task RequestPayjoin( } } // Verify that all of sender's outputs from the original PSBT are in the proposal. - if (ourOutputs.Count != 0) - throw new PayjoinSenderException("Some of our outputs are not included in the proposal"); + if (originalOutputs.Count != 0) + { + // The payment output may have been substituted + if (optionalParameters.DisableOutputSubstitution || + originalOutputs.Count != 1 || + originalOutputs.Dequeue().OriginalTxOut.ScriptPubKey != paymentScriptPubKey) + { + throw new PayjoinSenderException("Some of our outputs are not included in the proposal"); + } + } // After signing this proposal, we should check if minfeerate is respected. Log("payjoin proposal filled with sender's information" + proposal); From e2778babfb99ef011270fcda2e29ce076d383527 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Fri, 19 Jun 2020 14:31:19 +0900 Subject: [PATCH 37/46] additional comments --- bip-0078.mediawiki | 2 ++ 1 file changed, 2 insertions(+) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index f2fd04d7..d86a3238 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -406,6 +406,7 @@ public async Task RequestPayjoin( PayjoinClientParameters optionalParameters) { Log("signed PSBT" + signedPSBT); + // Extracting the pj link. var endpoint = bip21.ExtractPayjointEndpoint(); if (signedPSBT.IsAllFinalized()) throw new InvalidOperationException("The original PSBT should not be finalized."); @@ -428,6 +429,7 @@ public async Task RequestPayjoin( { originalOutputs.Enqueue((originalGlobalTx.Outputs[i], signedPSBT.Outputs[i])); } + // Add the client side query string parameters endpoint = ApplyOptionalParameters(endpoint, optionalParameters); Log("original PSBT" + originalPSBT); PSBT proposal = await SendOriginalTransaction(endpoint, originalPSBT, cancellationToken); From bd9740074338593c594394be365c3bed1b6cc3df Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Fri, 19 Jun 2020 14:47:47 +0900 Subject: [PATCH 38/46] Introduce pjos=0 --- bip-0078.mediawiki | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index d86a3238..25d36bfd 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -64,7 +64,7 @@ Other than that, our proposal is very similar. 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 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. @@ -118,6 +118,12 @@ The payjoin proposal MAY: 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. +===BIP21 payjoin parameters=== + +This proposal is defining the following new [[bip-021.mediawiki|BIP 21 URI]] parameters: +* pj=: Represents an http(s) endpoint which the sender can POST the original PSBT. +* pjos=0: Signal to the sender that they MUST disallow [[#output-substitution|payment output substitution]]. (See [[#unsecured-payjoin|Unsecured payjoin server]]) + ===Optional parameters=== When the payjoin sender posts the original PSBT to the receiver, he can optionally specify the following HTTP query string parameters: @@ -242,7 +248,8 @@ The receiver needs to do some check on the original PSBT before proceeding: ===Sender's payjoin proposal checklist=== The sender should check the payjoin proposal before signing it to prevent a malicious receiver from stealing money. - + +* If the receiver's BIP21 signalled pjos=0, disable payment output substitution. * Verify that the transaction version, and the nLockTime are unchanged. * Check that the sender's inputs' sequence numbers are unchanged. * For each inputs in the proposal: @@ -264,7 +271,7 @@ The sender should check the payjoin proposal before signing it to prevent a mali *** The amount that was substracted from the output's value is less or equal to maxadditionalfeecontribution. Let's call this amount actual contribution. *** Make sure the actual contribution is only paying fee: The actual contribution is less or equals to the difference of absolute fee between the payjoin proposal and the original PSBT. *** Make sure the actual contribution is only paying for fee incurred by additional inputs: actual contribution is less or equals to originalPSBTFeeRate * vsize(sender_input_type) * (count(original_psbt_inputs) - count(payjoin_proposal_inputs)). (see [[#fee-output|Fee output]] section) -** If the output is the payment output and disableoutputsubstitution= is falsedisableoutputsubstitution=) +* The sender must allow the receiver to add/remove or modify the receiver's own outputs (if [[#output-substitution|payment output substitution]], the payment's output should not be modified) * The sender should allow the receiver to not add any inputs. This is 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. @@ -335,6 +342,13 @@ On top of this the receiver can poison analysis by randomly faking a round amoun 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. +===Unsecured payjoin server=== + +A receiver might run the payment server (generating the BIP21 invoice) on a different server than the payjoin server, which could be less trusted than the payment server. + +In such case, the payment server can signal to the sender, via the BIP21 parameter pjos=0, that they MUST disallow [[#output-substitution|payment output substitution]]. +A compromised payjoin server could still the hot wallet outputs of the receiver, but would not be able to re-route payment to himself. + ===Impacted heuristics=== Our proposal of payjoin is breaking the following blockchain heuristics: @@ -382,7 +396,7 @@ The sender's software wallet can verify that the payjoin proposal is legitimate 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 [[#output-substitution|payment output substitution]]). -Note that the sender can opt out payment output substitution my using the optional parameter disableoutputsubstitution=true. +Note that the sender can disallow [[#output-substitution|payment output substitution]] by using the optional parameter disableoutputsubstitution=true. With payjoin, the maximum amount of money that can be lost is equal to two payments. @@ -412,6 +426,11 @@ public async Task RequestPayjoin( throw new InvalidOperationException("The original PSBT should not be finalized."); ScriptPubKeyType inputScriptType = wallet.ScriptPubKeyType(); PSBTOutput feePSBTOutput = null; + + bool allowOutputSubstitution = !optionalParameters.DisableOutputSubstitution; + if (bip21.Parameters.Contains("pjos") && bip21.Parameters["pjos"] == "0") + allowOutputSubstitution = false; + if (optionalParameters.AdditionalFeeOutputIndex != null && optionalParameters.MaxAdditionalFeeContribution != null) feePSBTOutput = signedPSBT.Outputs[optionalParameters.AdditionalFeeOutputIndex]; Script paymentScriptPubKey = bip21.Address == null ? null : bip21.Address.ScriptPubKey; @@ -536,7 +555,7 @@ public async Task RequestPayjoin( if (actualContribution > originalFeeRate * GetVirtualSize(inputScriptType) * additionalInputsCount) throw new PayjoinSenderException("The actual contribution is not only paying for additional inputs"); } - else if (!optionalParameters.DisableOutputSubstitution && output.OriginalTxOut.ScriptPubKey == paymentScriptPubKey) + else if (allowOutputSubstitution && output.OriginalTxOut.ScriptPubKey == paymentScriptPubKey) { // That's the payment output, the receiver may have changed it. } @@ -555,7 +574,7 @@ public async Task RequestPayjoin( if (originalOutputs.Count != 0) { // The payment output may have been substituted - if (optionalParameters.DisableOutputSubstitution || + if (!allowOutputSubstitution || originalOutputs.Count != 1 || originalOutputs.Dequeue().OriginalTxOut.ScriptPubKey != paymentScriptPubKey) { From 549107933cfa1c3081fca241f500b02c0ee3b353 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Fri, 19 Jun 2020 15:19:22 +0900 Subject: [PATCH 39/46] Allow outputs to be increased --- bip-0078.mediawiki | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index 25d36bfd..3bb8fc32 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -271,10 +271,10 @@ The sender should check the payjoin proposal before signing it to prevent a mali *** The amount that was substracted from the output's value is less or equal to maxadditionalfeecontribution. Let's call this amount actual contribution. *** Make sure the actual contribution is only paying fee: The actual contribution is less or equals to the difference of absolute fee between the payjoin proposal and the original PSBT. *** Make sure the actual contribution is only paying for fee incurred by additional inputs: actual contribution is less or equals to originalPSBTFeeRate * vsize(sender_input_type) * (count(original_psbt_inputs) - count(payjoin_proposal_inputs)). (see [[#fee-output|Fee output]] section) -** If the output is the payment output and payment output substitution is disabled. +** If the output is the payment output and payment output substitution is allowed. *** Do not make any check ** Else -*** Make sure the output's value did not changed. +*** Make sure the output's value did not decreased. ** Verify that all sender's outputs (ie, all outputs except the output actually paid to the receiver) from the original PSBT are in the proposal. * Once the proposal is signed, if minfeerate was specified, check that the fee rate of the payjoin transaction is not less than this value. @@ -561,8 +561,8 @@ public async Task RequestPayjoin( } else { - if (originalOutput.OriginalTxOut.Value != proposedPSBTOutput.Value) - throw new PayjoinSenderException("The receiver changed one of our outputs"); + if (originalOutput.OriginalTxOut.Value > proposedPSBTOutput.Value) + throw new PayjoinSenderException("The receiver decreased the value of one of the outputs"); } // We fill up information we had on the signed PSBT, so we can sign it. foreach (var hdKey in output.SignedPSBTOutput.HDKeyPaths) From c449c019f6112cfb2acf16d812429e9df0f147e8 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Fri, 19 Jun 2020 16:06:19 +0900 Subject: [PATCH 40/46] Do not allow decrease in absolute fee --- bip-0078.mediawiki | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index 3bb8fc32..d67ab088 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -117,6 +117,7 @@ The payjoin proposal MAY: 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. +* Decrease the absolute fee of the original transaction. ===BIP21 payjoin parameters=== @@ -249,6 +250,7 @@ The receiver needs to do some check on the original PSBT before proceeding: The sender should check the payjoin proposal before signing it to prevent a malicious receiver from stealing money. +* Verify that the absolute fee of the payjoin proposal is equals or higher than the original PSBT. * If the receiver's BIP21 signalled pjos=0, disable payment output substitution. * Verify that the transaction version, and the nLockTime are unchanged. * Check that the sender's inputs' sequence numbers are unchanged. @@ -529,6 +531,10 @@ public async Task RequestPayjoin( if (sequences.Count != 1) throw new PayjoinSenderException("Mixed sequence detected in the proposal"); + decimal newFee = proposal.GetFee(); + decimal additionalFee = newFee - originalFee; + if (additionalFee < 0) + throw new PayjoinSenderException("The receiver decreased absolute fee"); // For each outputs in the proposal: foreach (PSBTOutput proposedPSBTOutput in proposal.Outputs) { @@ -545,8 +551,6 @@ public async Task RequestPayjoin( // The amount that was substracted from the output's value is less or equal to maxadditionalfeecontribution if (actualContribution > optionalParameters.MaxAdditionalFeeContribution) throw new PayjoinSenderException("The actual contribution is more than maxadditionalfeecontribution"); - decimal newFee = proposal.GetFee(); - decimal additionalFee = newFee - originalFee; // Make sure the actual contribution is only paying fee if (actualContribution > additionalFee) throw new PayjoinSenderException("The actual contribution is not only paying fee"); From feac3d0035b32dcc8d66d415fe959c533b38d228 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Fri, 19 Jun 2020 16:12:29 +0900 Subject: [PATCH 41/46] Update special thanks --- bip-0078.mediawiki | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index d67ab088..6b69b1ed 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -671,5 +671,5 @@ Senders not supporting payjoin will just ignore the pj variable and ==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. +Special thanks to Kukks for developing the initial support to BTCPay Server, to junderw, AdamISZ, lukechilds, ncoelho, nopara73, lontivero, yahiheb, SomberNight, andrewkozlik, instagibbs, RHavar for all the feedback we received since our first implementation. +Thanks again 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. From 5e4cc6d8129a94c653187c38c0bb4a1122722a60 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Mon, 22 Jun 2020 10:56:22 +0900 Subject: [PATCH 42/46] Fix grammar, additional note on ability to increase output of the receiver --- bip-0078.mediawiki | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index 6b69b1ed..d1a14ff0 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -154,7 +154,7 @@ This fee contribution can't be used to pay for anything else than additional inp * 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. -* disableoutputsubstitution=, a boolean indicating if the sender forbids the receiver to modify his own output, see [[#output-substitution|payment output substitution]]. (default to false) +* disableoutputsubstitution=, a boolean indicating if the sender forbids the receiver to substitute the receiver's output, see [[#output-substitution|payment output substitution]]. (default to false) ===Receiver's well known errors=== @@ -270,20 +270,20 @@ The sender should check the payjoin proposal before signing it to prevent a mali * For each outputs in the proposal: ** Verify that no keypaths is in the PSBT output ** If the output is the [[#fee-output|fee output]]: -*** The amount that was substracted from the output's value is less or equal to maxadditionalfeecontribution. Let's call this amount actual contribution. -*** Make sure the actual contribution is only paying fee: The actual contribution is less or equals to the difference of absolute fee between the payjoin proposal and the original PSBT. -*** Make sure the actual contribution is only paying for fee incurred by additional inputs: actual contribution is less or equals to originalPSBTFeeRate * vsize(sender_input_type) * (count(original_psbt_inputs) - count(payjoin_proposal_inputs)). (see [[#fee-output|Fee output]] section) +*** The amount that was substracted from the output's value is less than or equal to maxadditionalfeecontribution. Let's call this amount actual contribution. +*** Make sure the actual contribution is only paying fee: The actual contribution is less than or equals to the difference of absolute fee between the payjoin proposal and the original PSBT. +*** Make sure the actual contribution is only paying for fee incurred by additional inputs: actual contribution is less than or equals to originalPSBTFeeRate * vsize(sender_input_type) * (count(original_psbt_inputs) - count(payjoin_proposal_inputs)). (see [[#fee-output|Fee output]] section) ** If the output is the payment output and payment output substitution is allowed. *** Do not make any check ** Else -*** Make sure the output's value did not decreased. +*** Make sure the output's value did not decrease. ** Verify that all sender's outputs (ie, all outputs except the output actually paid to the receiver) from the original PSBT are in the proposal. * Once the proposal is signed, if minfeerate was specified, check that the fee rate of the payjoin transaction is not less than this value. 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 the receiver's own outputs (if [[#output-substitution|payment output substitution]], the payment's output should not be modified) +* The sender must allow the receiver to add/remove or modify the receiver's own outputs. (if payment output substitution is disabled, the receiver's outputs must not be removed or decreased in value) * The sender should allow the receiver to not add any inputs. This is 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. @@ -341,7 +341,9 @@ On top of this the receiver can poison analysis by randomly faking a round amoun ===Payment output substitution=== -The receiver is free to change the output paying to himself. +Unless disallowed by sender explicitely via `disableoutputsubstitution=true` or by the BIP21 url via query parameter the `pjos=0`, the receiver is free to decrease the amount, remove, or change the scriptPubKey output paying to himself. +Note that if payment output substitution is disallowed, the reveiver can still increase the amount of the output. (See [[#reference-impl|the reference implementation]]) + 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. ===Unsecured payjoin server=== @@ -402,7 +404,7 @@ Note that the sender can disallow [[#output-substitution|payment output substitu With payjoin, the maximum amount of money that can be lost is equal to two payments. -==Reference sender's implementation== +==Reference sender's implementation== Here is pseudo code of a sender implementation. RequestPayjoin takes the bip21 URI of the payment, the wallet and the signedPSBT. @@ -548,7 +550,7 @@ public async Task RequestPayjoin( if (output.OriginalTxOut == feeOutput) { var actualContribution = feeOutput.Value - proposedPSBTOutput.Value; - // The amount that was substracted from the output's value is less or equal to maxadditionalfeecontribution + // The amount that was substracted from the output's value is less than or equal to maxadditionalfeecontribution if (actualContribution > optionalParameters.MaxAdditionalFeeContribution) throw new PayjoinSenderException("The actual contribution is more than maxadditionalfeecontribution"); // Make sure the actual contribution is only paying fee From e6418e5a769d7635824f2ad1bcfe4c720be897c2 Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Mon, 22 Jun 2020 10:58:08 +0900 Subject: [PATCH 43/46] Fix missing word --- bip-0078.mediawiki | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index d1a14ff0..90aa94fc 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -351,7 +351,7 @@ For example, if the sender's scriptPubKey type is P2WPKH while the receiver's pa A receiver might run the payment server (generating the BIP21 invoice) on a different server than the payjoin server, which could be less trusted than the payment server. In such case, the payment server can signal to the sender, via the BIP21 parameter pjos=0, that they MUST disallow [[#output-substitution|payment output substitution]]. -A compromised payjoin server could still the hot wallet outputs of the receiver, but would not be able to re-route payment to himself. +A compromised payjoin server could steal the hot wallet outputs of the receiver, but would not be able to re-route payment to himself. ===Impacted heuristics=== From b0be77f99eee679ebffe0552d75a4ddca3a6d62e Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Mon, 22 Jun 2020 11:06:57 +0900 Subject: [PATCH 44/46] Removing non-sense paragraph --- bip-0078.mediawiki | 2 -- 1 file changed, 2 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index 90aa94fc..5048d4a2 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -366,8 +366,6 @@ Because payjoin is mixing the inputs of the sender and receiver, this heuristic 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 From a76f5e433591a415fd9d6b5ab8c26e0ec37cc6df Mon Sep 17 00:00:00 2001 From: "nicolas.dorier" Date: Tue, 23 Jun 2020 17:46:18 +0900 Subject: [PATCH 45/46] Clarify test vector --- bip-0078.mediawiki | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki index 5048d4a2..7d0b9bb1 100644 --- a/bip-0078.mediawiki +++ b/bip-0078.mediawiki @@ -421,7 +421,7 @@ public async Task RequestPayjoin( PSBT signedPSBT, PayjoinClientParameters optionalParameters) { - Log("signed PSBT" + signedPSBT); + Log("Unfinalized signed PSBT" + signedPSBT); // Extracting the pj link. var endpoint = bip21.ExtractPayjointEndpoint(); if (signedPSBT.IsAllFinalized()) @@ -643,10 +643,10 @@ A successful exchange with: |0 |} -signed PSBT +Unfinalized signed PSBT
cHNidP8BAHMCAAAAAY8nutGgJdyYGXWiBEb45Hoe9lWGbkxh/6bNiOJdCDuDAAAAAAD+////AtyVuAUAAAAAF6kUHehJ8GnSdBUOOv6ujXLrWmsJRDCHgIQeAAAAAAAXqRR3QJbbz0hnQ8IvQ0fptGn+votneofTAAAAAAEBIKgb1wUAAAAAF6kU3k4ekGHKWRNbA1rV5tR5kEVDVNCHAQQWABTHikVyU1WCjVZYB03VJg1fy2mFMCICAxWawBqg1YdUxLTYt9NJ7R7fzws2K09rVRBnI6KFj4UWRzBEAiB8Q+A6dep+Rz92vhy26lT0AjZn4PRLi8Bf9qoB/CMk0wIgP/Rj2PWZ3gEjUkTlhDRNAQ0gXwTO7t9n+V14pZ6oljUBIgYDFZrAGqDVh1TEtNi300ntHt/PCzYrT2tVEGcjooWPhRYYSFzWUDEAAIABAACAAAAAgAEAAAAAAAAAAAEAFgAURvYaK7pzgo7lhbSl/DeUan2MxRQiAgLKC8FYHmmul/HrXLUcMDCjfuRg/dhEkG8CO26cEC6vfBhIXNZQMQAAgAEAAIAAAACAAQAAAAEAAAAAAA==
-original PSBT +Original PSBT
cHNidP8BAHMCAAAAAY8nutGgJdyYGXWiBEb45Hoe9lWGbkxh/6bNiOJdCDuDAAAAAAD+////AtyVuAUAAAAAF6kUHehJ8GnSdBUOOv6ujXLrWmsJRDCHgIQeAAAAAAAXqRR3QJbbz0hnQ8IvQ0fptGn+votneofTAAAAAAEBIKgb1wUAAAAAF6kU3k4ekGHKWRNbA1rV5tR5kEVDVNCHAQcXFgAUx4pFclNVgo1WWAdN1SYNX8tphTABCGsCRzBEAiB8Q+A6dep+Rz92vhy26lT0AjZn4PRLi8Bf9qoB/CMk0wIgP/Rj2PWZ3gEjUkTlhDRNAQ0gXwTO7t9n+V14pZ6oljUBIQMVmsAaoNWHVMS02LfTSe0e388LNitPa1UQZyOihY+FFgABABYAFEb2Giu6c4KO5YW0pfw3lGp9jMUUAAA=
payjoin proposal From d168a754f115a31c557468b150083260057aafed Mon Sep 17 00:00:00 2001 From: Luke Dashjr Date: Thu, 25 Jun 2020 05:14:58 +0000 Subject: [PATCH 46/46] Fix README for BIP 78 --- README.mediawiki | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/README.mediawiki b/README.mediawiki index 82baca2f..3a471c48 100644 --- a/README.mediawiki +++ b/README.mediawiki @@ -385,14 +385,13 @@ Those proposing changes should consider that ultimately consent may rest with th | Justin Newton, Matt David, Aaron Voisine, James MacWhyte | Standard | Final -|- style="background-color: #ffffcf" +|- | [[bip-0078.mediawiki|78]] | Applications | A Simple Payjoin Proposal | Nicolas Dorier -| Informational -| Proposed -|- +| Standard +| Draft |- style="background-color: #ffffcf" | [[bip-0079.mediawiki|79]] | Applications