From d8db3d76081662a55f34c6fed681b9daf5f6a0bd Mon Sep 17 00:00:00 2001
From: "nicolas.dorier" <nicolas.dorier@gmail.com>
Date: Tue, 31 Aug 2021 15:43:22 +0900
Subject: [BIP78] Fix client implementation when there is output substitution

---
 bip-0078.mediawiki | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

(limited to 'bip-0078.mediawiki')

diff --git a/bip-0078.mediawiki b/bip-0078.mediawiki
index 7d0b9bb..4226be5 100644
--- a/bip-0078.mediawiki
+++ b/bip-0078.mediawiki
@@ -541,10 +541,16 @@ public async Task<PSBT> 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 isOriginalOutput = originalOutputs.Count > 0 && originalOutputs.Peek().OriginalTxOut.ScriptPubKey == proposedPSBTOutput.ScriptPubKey;
-        if (isOriginalOutput)
+        if (originalOutputs.Count == 0)
+                continue;
+        var originalOutput = originalOutputs.Peek();
+        bool isOriginalOutput = originalOutput.OriginalTxOut.ScriptPubKey == proposedPSBTOutput.ScriptPubKey;
+        bool substitutedOutput = !isOriginalOutput &&
+                                allowOutputSubstitution &&
+                                originalOutput.OriginalTxOut.ScriptPubKey == paymentScriptPubKey;
+        if (isOriginalOutput || substitutedOutput)
         {
-            var originalOutput = originalOutputs.Dequeue();
+            originalOutputs.Dequeue();
             if (output.OriginalTxOut == feeOutput)
             {
                 var actualContribution = feeOutput.Value - proposedPSBTOutput.Value;
-- 
cgit v1.2.3

