Subject: Re: [bitcoin-dev] Detailed protocol design for routed multi-transaction CoinSwap appendium

From: Chris Belcher <[email-masked]>
Date: Sat, 3 Oct 2020 11:36:22 +0100

Hello list,

This email is an appendium or modification of the earlier CoinSwap
protocol published on this list. It is intended to fix the problems
found in review. (Original email quoted here too)

On 11/08/2020 13:05, Chris Belcher via bitcoin-dev wrote:
> I'm currently working on implementing CoinSwap (see my other email
> "Design for a CoinSwap implementation for massively improving Bitcoin
> privacy and fungibility").
> 
> CoinSwaps are special because they look just like regular bitcoin
> transactions, so they improve the privacy even for people who do not use
> them. Once CoinSwap is deployed, anyone attempting surveillance of
> bitcoin transactions will be forced to ask themselves the question: how
> do we know this transaction wasn't a CoinSwap?
> 
> This email contains a detailed design of the first protocol version. It
> makes use of the building blocks of multi-transaction CoinSwaps, routed
> CoinSwaps, liquidity market, private key handover, and fidelity bonds.
> It does not include PayJoin-with-CoinSwap, but that's in the plan to be
> added later.
> 
> == Routed CoinSwap ==
> 
> Diagram of CoinSwaps in the route:
> 
>     Alice ====> Bob ====> Charlie ====> Alice
> 
> Where (====>) means one CoinSwap. Alice gives coins to Bob, who gives
> coins to Charlie, who gives coins to Alice. Alice is the market taker
> and she starts with the hash preimage. She chooses the CoinSwap amount
> and chooses who the makers will be.
> 
> This design has one market taker and two market makers in its route, but
> it can easily be extended to any number of makers.
> 
> == Multiple transactions ==
> 
> Each single CoinSwap is made up of multiple transactions to avoid amount
> correlation
> 
>           (a0 BTC) --->     (b0 BTC) --->         (c0 BTC) --->
>     Alice (a1 BTC) ---> Bob (b1 BTC) ---> Charlie (c1 BTC) ---> Alice
>           (a2 BTC) --->     (b2 BTC) --->         (c2 BTC) --->
> 
> The arrow (--->) represent funding transactions. The money gets paid to
> a 2-of-2 multisig but after the CoinSwap protocol and private key
> handover is done they will be controlled by the next party in the route.
> 
> This example has 6 regular-sized transactions which use approximately
> the same amount of block space as a single JoinMarket coinjoin with 6
> parties (1 taker, 5 makers). Yet the privacy provided by this one
> CoinSwap would be far far greater. It would not have to be repeated in
> the way that Equal-Output CoinJoins must be.
> 
> == Direct connections to Alice ===
> 
> Only Alice, the taker, knows the entire route, Bob and Charlie just know
> their previous and next transactions. Bob and Charlie do not have direct
> connections with each other, only with Alice.
> 
> Diagram of Tor connections:
> 
>     Bob      Charlie
>      |       /
>      |      /
>      |     /
>       Alice
> 
> When Bob and Charlie communicate, they are actually sending and
> receiving messages via Alice who relays them to Charlie or Bob. This
> helps hide whether the previous or next counterparty in a CoinSwap route
> is a maker or taker.
> 
> This doesn't have security issues even in the final steps where private
> keys are handed over, because those private keys are always for 2-of-2
> multisig and so on their own are never enough to steal money.
> 
> 
> === Miner fees ===
> 
> Makers have no incentive to pay any miner fees. They only do
> transactions which earn them an income and are willing to wait a very
> long time for that to happen. By contrast takers want to create
> transactions far more urgently. In JoinMarket we coded a protocol where
> the maker could contribute to miner fees, but the market price offered
> of that trended towards zero. So the reality is that takers will pay all
> the miner fees. Also because makers don't know the taker's time
> preference they don't know how much they should pay in miner fees.
> 
> The taker will have to set limits on how large the maker's transactions
> are, otherwise makers could abuse this by having the taker consolidate
> maker's UTXOs for free.
> 
> == Funding transaction definitions ==
> 
> Funding transactions are those which pay into the 2-of-2 multisig addresses.
> 
> Definitions:
> I = initial coinswap amount sent by Alice = a0 + a1 + a2
> (WA, WB, WC) = Total value of UTXOs being spent by Alice, Bob, Charlie
>                respectively. Could be called "wallet Alice", "wallet
>                Bob", etc
> (B, C) = Coinswap fees paid by Alice and earned by Bob and Charlie.
> (M1, M2, M3) = Miner fees of the first, second, third, etc sets of
>                funding transactions. Alice will choose what these are
>                since she's paying.
> multisig(A+B) = A 2of2 multisig output with private keys held by A and B
> 
> The value in square parentheses refers to the bitcoin amount.
> 
> Alice funding txes
>   [WA btc] ---> multisig (Alice+Bob) [I btc]
>                 change [WA-M1-I btc]
> Bob funding txes
>   [WB btc] ---> multisig (Bob+Charlie) [I-M2-B btc]
>                 change [WB-I+B btc]
> Charlie funding txes
>   [WC btc] ---> multisig (Charlie+Alice) [(I-M2-B)-M3-C btc]
>                 change [WC-(I-M2-B)+C btc]
> 
> Here we've drawn these transactions as single transactions, but they are
> actually multiple transactions where the outputs add up some value (e.g.
> add up to I in Alice's transactions.)
> 
> === Table of balances before and after a successful CoinSwap ===
> 
> If a CoinSwap is successful then all the multisig outputs in the funding
> transactions will become controlled unilaterally by one party. We can
> calculate how the balances of each party change.
> 
> Party   | Before | After
> --------|--------|-------------------------------------------
> Alice   | WA     | WA-M1-I + (I-M2-B)-M3-C  = WA-M1-M2-M3-B-C
> Bob     | WB     | WB-I+B + I               = WB+B
> Charlie | WC     | WC-(I-M2-B)+C + I-M2-B   = WC+C
> 
> After a successful coinswap, we see Alice's balance goes down by the
> miner fees and the coinswap fees. Bob's and Charlie's balance goes up by
> their coinswap fees.
> 
> == Contract transaction definitions ==
> 
> Contract transactions are those which may spend from the 2-of-2 multisig
> outputs, they transfer the coins into a contract where the coins can be
> spent either by waiting for a timeout or providing a hash preimage
> value. Ideally contract transactions will never be broadcast but their
> existence keeps all parties honest.
> 
> M~ is miner fees, which we treat as a random variable, and ultimately
> set by whichever pre-signed RBF tx get mined. When we talk about _the_
> contract tx, we actually mean perhaps 20-30 transactions which only
> differ by the miner fee and have RBF enabled, so they can be broadcasted
> in sequence to get the contract transaction mined regardless of the
> demand for block space.
> 
> (Alice+timelock_A OR Bob+hash) = Is an output which can be spent
>                                  either with Alice's private key
>                                  after waiting for a relative
>                                  timelock_A, or by Bob's private key by
>                                  revealing a hash preimage value
> 
> Alice contract tx:
>     multisig (Alice+Bob) ---> (Alice+timelock_A OR Bob+hash)
>     [I btc]                   [I-M~ btc]
> Bob contract tx:
>     multisig (Bob+Charlie) ---> (Bob+timelock_B OR Charlie+hash)
>     [I-M2-B btc]                [I-M2-B-M~ btc]
> Charlie contract tx:
>     multisig (Charlie+Alice)  ---> (Charlie+timelock_C OR Alice+hash)
>     [(I-M2-B)-M3-C btc]            [(I-M2-B)-M3-C-M~ btc]
> 
> 
> === Table of balances before/after CoinSwap using contracts transactions ===
> 
> In this case the parties had to get their money back by broadcasting and
> mining the contract transactions and waiting for timeouts.
> 
> Party   | Before | After
> --------|--------|--------------------------------------------
> Alice   | WA     | WA-M1-I + I-M~                   = WA-M1-M~
> Bob     | WB     | WB-I+B + I-M2-B-M~               = WB-M2-M~
> Charlie | WC     | WC-(I-M2-B)+C + (I-M2-B)-M3-C-M~ = WC-M3-M~
> 
> In the timeout failure case, every party pays for their own miner fees.
> And nobody earns or spends any coinswap fees. So even for a market maker
> its possible for their wallet balance to go down sometimes, although as
> we shall see there are anti-DOS features which make this unlikely to
> happen often.
> 
> A possible attack by a malicious Alice is that she chooses M1 to be very
> low (e.g. 1 sat/vbyte) and sets M2 and M3 to be very high (e.g. 1000
> sat/vb) and then intentionally aborts, forcing the makers to lose much
> more money in miner fees than the attacker. The attack can be used to
> waste away Bob's and Charlie's coins on miner fees at little cost to the
> malicious taker Alice. So to defend against this attack Bob and Charlie
> must refuse to sign a contract transaction if the corresponding funding
> transaction pays miner fees greater than Alice's funding transaction.
> 
> 
> There can also be a failure case where each party gets their money using
> hash preimage values instead of timeouts. Note that each party has to
> sweep the output before the timeout expires, so that will cost an
> additional miner fee M~.
> 
> Party   | Before | After
> --------|--------|------------------------------------------------------
> Alice   | WA     | WA-M1-I + (I-M2-B)-M3-C-M~ - M~ = WA-M1-M2-M3-B-C-2M~
> Bob     | WB     | WB-I+B + I-M~ - M~              = WB+B-2M~
> Charlie | WC     | WC-(I-M2-B)+C + I-M2-B-M~ - M~  = WC+C-2M~
> 
> In this situation the makers Bob and Charlie earn their CoinSwap fees,
> but they pay an additional miner fee twice. Alice pays for all the
> funding transaction miner fees, and the CoinSwap fees, and two
> additional miner fees. And she had her privacy damaged because the
> entire world saw on the blockchain the contract script.
> 
> Using the timelock path is like a refund, everyone's coin just comes
> back to them. Using the preimage is like the CoinSwap transaction
> happened, with the coins being sent ahead one hop. Again note that if
> the preimage is used then coinswap fees are paid.
> 
> === Staggered timelocks ===
> 
> The timelocks are staggered so that if Alice uses the preimage to take
> coins then the right people will also learn the preimage and have enough
> time to be able to get their coins back too. Alice starts with knowledge
> of the hash preimage so she must have a longest timelock.
> 
> == EC tweak to reduce one round trip ==
> 
> When two parties are agreeing on a 2-of-2 multisig address, they need to
> agree on their public keys. We can avoid one round trip by using the EC
> tweak trick.
> 
> When Alice, the taker, downloads the entire offer book for the liquidity
> market, the offers will also contain a EC public key. Alice can tweak
> this to generate a brand new public key for which the maker knows the
> private key. This public key will be one of the keys in the 2-of-2
> multisig. This feature removes one round trip from the protocol.
> 
>     q = EC privkey generated by maker
>     Q = q.G = EC pubkey published by maker
> 
>     p = nonce generated by taker
>     P = p.G = nonce point calculated by taker
> 
>     R = Q + P = pubkey used in bitcoin transaction
>       = (q + p).G
> 
> Taker sends unsigned transaction which pays to multisig using pubkey Q,
> and also sends nonce p. The maker can use nonce p to calculate (q + p)
> which is the private key of pubkey R.
> 
> Taker doesnt know the privkey because they are unable to find q because
> of the ECDLP.
> 
> Any eavesdropper can see the nonce p and easily calculate the point R
> too but Tor communication is encrypted so this isnt a concern.
> 
> None of the makers in the route know each other's Q values, so Alice the
> taker will generate a nonce p on their behalf and send it over. I
> believe this cant be used for any kind of attack, because the signing
> maker will always check that the nonce results in the public key
> included in the transaction they're signing, and they'll never sign a
> transaction not in their interests.
> 
> 
> == Protocol ==
> 
> This section is the most important part of this document.
> 
> Definitions:
> fund = all funding txes (remember in this multi-tx protocol there can be
>        multiple txes which together make up the funding)
> A htlc = all htlc contract txes (fully signed) belonging to party A
> A unsign htcl = all unsigned htlc contract txes belonging to party A
>                 including the nonce point p used to calculate the
>                 maker's pubkey.
> p = nonce point p used in the tweak EC protocol for calculating the
>     maker's pubkey
> A htlc B/2 = Bob's signature for the 2of2 multisig of the Alice htlc
>              contract tx
> privA(A+B) = private key generated by Alice in the output
>              multisig (Alice+Bob)
> 
> 
>  | Alice           | Bob             | Charlie         |
>  |=================|=================|=================|
> 0. A unsign htlc ---->               |                 |
> 1.               <---- A htlc B/2    |                 |
> 2. ***** BROADCAST AND MINE ALICE FUNDING TXES ******  |
> 3. A fund+htlc+p ---->               |                 |
> 4.                 | B unsign htlc ---->               |
> 5.                 |               <---- B htlc C/2    |
> 6. ******* BROADCAST AND MINE BOB FUNDING TXES ******* |
> 7.                 | B fund+htlc+p ---->               |
> 8.               <---------------------- C unsign htlc |
> 9.    C htlc A/2 ---------------------->               |
> A. ***** BROADCAST AND MINE CHARLIE FUNDING TXES ***** |
> B.               <---------------------- C fund+htlc+p |
> C. hash preimage ---------------------->               |
> D. hash preimage ---->               |                 |
> E.    privA(A+B) ---->               |                 |
> F.                 |    privB(B+C) ---->               |
> G.               <---------------------- privC(C+A)    |
> 
> == Protocol notes ==
> 0-2 are the steps which setup Alice's funding tx and her contract tx for
>     possible refund
> 4-5 same as 0-2 but for Bob
> 8-9 same as 0-2 but for Charlie
> 3,7 is proof to the next party that the previous party has already
>     committed miner fees to getting a transaction mined, and therefore
>     this isnt a DOS attack. The step also reveals the fully-signed
>     contract transaction which the party can use to get their money back
>     with a preimage.
> C-G is revealing the hash preimage to all, and handing over the private
>     keys
> 
> 
> == Analysis of aborts ==
> 
> We will now discuss aborts, which happen when one party halts the
> protocol and doesnt continue. Perhaps they had a power cut, their
> internet broke, or they're a malicious attacker wanting to waste time
> and money. The other party may try to reestablish a connection for some
> time, but eventually must give up.
> 
> Number refers to the step number where the abort happened
> e.g. step 1 means that the party aborted instead of the action happening
> on protocol step 1.
> 
> The party name refers to what that party does
> e.g. Party1: aborts, Party2/Party3: does a thing in reaction
> 
> 0. Alice: aborts. Bob/Charlie: do nothing, they havent lost any time or
>    money
> 1. Bob: aborts. Alice: lost no time or money, try with another Bob.
>    Charlie: do nothing
> 2-3. same as 0.
> 4. Bob: aborts. Charlie: do nothing. Alice: broadcasts her contract tx
>    and waits for the timeout, loses time and money on miner fees, she'll
>    never coinswap with Bob's fidelity bond again.
> 5. Charlie: aborts. Alice/Bob: lose nothing, find another Charlie to
>    coinswap with.
> 6. same as 4.
> 7. similar to 4 but Alice MIGHT not blacklist Bob's fidelity bond,
>    because Bob will also have to broadcast his contract tx and will also
>    lose time and money.
> 8. Charlie: aborts. Bob: broadcast his contract transaction and wait for
>    the timeout to get his money back, also broadcast Alice's contract
>    transaction in retaliation. Alice: waits for the timeout on her htlc
>    tx that Bob broadcasted, will never do a coinswap with Charlie's
>    fidelity bond again.
> 9. Alice: aborts. Charlie: do nothing, no money or time lost. Bob:
>    broadcast bob contract tx and wait for timeout to get money back,
>    comforted by the knowledge that when Alice comes back online she'll
>    have to do the same thing and waste the same amount of time and
>    money.
> A-B. same as 8.
> C-E. Alice: aborts. Bob/Charlie: all broadcast their contract txes and
>      wait for the timeout to get their money back, or if Charlie knows
>      the preimage he uses it to get the money immediately, which Bob can
>      read from the blockchain and also use.
> F. Bob: aborts. Alice: broadcast Charlie htlc tx and use preimage to get
>    money immediately, Alice blacklists Bob's fidelity bond. Charlie:
>    broadcast Bob htlc and use preimage to get money immediately.
> G. Charlie: aborts. Alice: broadcast Charlie htlc and use preimage to
>    get money immediately, Alice blacklists Charlie's fidelity bond. Bob:
>    does nothing, already has his privkey.
> 
> ==== Retaliation as DOS-resistance ====
> 
> In some situations (e.g. step 8.) if one maker in the coinswap route is
> the victim of a DOS they will retaliate by DOSing the previous maker in
> the route. This may seem unnecessary and unfair (after all why waste
> even more time and block space) but is actually the best way to resist
> DOS because it produces a concrete cost every time a DOS happens.
> 
> 
> == Analysis of deviations ==
> 
> This section discusses what happens if one party deviates from the
> protocol by doing something else, for example broadcasting a htlc
> contract tx when they shouldnt have.
> 
> The party name refers to what that party does, followed by other party's
> reactions to it.
> e.g. Party1: does a thing, Party2/Party3: does a thing in reaction
> 
> If multiple deviations are possible in a step then they are numbered
> e.g. A1 A2 A2 etc
> 
> 
> 0-2. Alice/Bob/Charlie: nothing else is possible except following the
>      protocol or aborting
> 3. Alice: broadcasts one or more of the A htlc txes. Bob/Charlie/Dennis:
>    do nothing, they havent lost any time or money.
> 4-6. Bob/Charlie: nothing else is possible except following the protocol
>      or aborting.
> 7. Bob: broadcasts one or more of the B htlc txes, Alice: broadcasts all
>    her own A htlc txes and waits for the timeout to get her money back.
>    Charlie: do nothing
> 8. Charlie: nothing else is possible except following the protocol or
>    aborting.
> 9. Alice: broadcasts one or more of the A htlc txes. Bob: broadcasts all
>    his own A htlc txes and waits for the timeout.
> A. same as 8.
> B. Charlie: broadcasts one or more of the C htlc txes, Alice/Bob:
>    broadcasts all their own htlc txes and waits for the timeout to get
>    their money back.
> C-E1. Alice: broadcasts all of C htlc txes and uses her knowledge of the
>       preimage hash to take the money immediately. Charlie: broadcasts
>       all of B htlc txes and reading the hash value from the blockchain,
>       uses it to take the money from B htlc immediately. Bob: broadcasts
>       all of A htlc txes, and reading hash from the blockchain, uses it
>       to take the money from A htlc immediately.
> C-E2. Alice: broadcast her own A htlc txes, and after a timeout take the
>       money. Bob: broadcast his own B htlc txes and after the timeout
>       take their money. Charlie: broadcast his own C htlc txes and after
>       the timeout take their money.
> F1. Bob: broadcast one or more of A htcl txes and use the hash preimage
>     to get the money immediately. He already knows both privkeys of the
>     multisig so this is pointless and just damages privacy and wastes
>     miner fees. Alice: blacklist Bob's fidelity bond.
> F2. Bob: broadcast one or more of the C htlc txes. Charlie: use preimage
>     to get his money immediately. Bob's actions were pointless. Alice:
>     cant tell whether Bob or Charlie actually broadcasted, so blacklist
>     both fidelity bonds.
> G1. Charlie: broadcast one or more of B htcl txes and use the hash
>     preimage to get the money immediately. He already knows both
>     privkeys of the multisig so this is pointless and just damages
>     privacy and wastes miner fees. Alice: cant tell whether Bob or
>     Charlie actually broadcasted, so blacklist both fidelity bonds.
> G2. Charlie: broadcast one or more of the A htlc txes. Alice: broadcast
>     the remaining A htlc txes and use preimage to get her money
>     immediately. Charlies's actions were pointless. Alice: blacklist
>     Charlie's fidelity bond.
> 
> The multisig outputs of the funding transactions can stay unspent
> indefinitely. However the parties must always be watching the network
> and ready to respond with their own sweep using a preimage. This is
> because the other party still possesses a fully-signed contract tx. The
> parties respond in the same way as in steps C-E1, F2 and G2. Alice's
> reaction of blacklisting both fidelity bonds might not be the right way,
> because one maker could use it to get another one blacklisted (as well
> as themselves).
> 
> 
> == Conclusion ==
> 
> This document describes the first version of the protocol which
> implements multi-transaction Coinswap, routed Coinswap, fidelity bonds,
> a liquidity market and private key handover. I describe the protocol and
> also analyze aborts of the protocols and deviations from the protocol.
> 
> _______________________________________________
> bitcoin-dev mailing list
> [email-masked]
> https://lists.linuxfoundation.org/mailman/listinfo/bitcoin-dev
> 

== Miner fees ==
RBF is used on contract transactions as before, so each contract
transaction actually has many different versions each with a different
miner fee.

A possible vulnerability of using RBF is transaction pinning (see
https://bitcoinops.org/en/topics/transaction-pinning/). We solve this
issue by encumbering hashlock outputs with `1 OP_CSV`, so that it is not
possible to do CPFP on a contract transaction.

Another possible vulnerability (called post-coinswap-fee-burning) is
that after a successful CoinSwap, the party which no longer controls the
coins can still broadcast a high-fee RBF contract transaction in order
to burn coins to miner fees. This might be used by a malicious taker to
waste away the balance of a maker (the malicious taker might be another
maker who in the liquidity market is in competition with the victim
maker, and is using this exploit to attack their competitor).

=== Collateral payments ===
The post-coinswap-theft-attempt is an attack done after a CoinSwap is
finished. It works by the sender broadcasting their contract transaction
of the coins which no longer belong to him, they hope that the timeout
will expire and that they can sweep the coins. Their theft attempt is
very unlikely to actually succeed because of multiple redundant
watchtowers who will immediately spend the coins with the hashlock
branch, but the thief still might try because the attempt is essentially
riskless and costless.

Collateral payments are used to avoid this problem by making the theft
attempt not costless. (Although the cost is best kept very small,
corresponding to the risk of success being very low). (see
https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2020-September/018151.html)

Post-coinswap-theft-attempts are already not costless for the taker,
because broadcasting the contract transactions damages privacy, which
the taker by construction wants to improve and has actually already paid
for. Privacy is reduced either by revealing the contract on-chain or by
reducing anonymity sets by having the coins spent immediately or very
soon). Therefore takers dont require collateral payments in this
protocol and this allows a taker to fully-spend their entire wallet in
one set of CoinSwaps (i.e. a sweep transaction with no change).

Collateral payments also solve the vulnerability of
post-coinswap-fee-burning for maker-maker CoinSwaps, because the miner
fee is taken from the collateral input and single-sig change, and not
from the CoinSwap contract.

==== Post-CoinSwap-fee-burning for takers ====
Collateral payments stop the post-coinswap-fee-burning attack but only
for makers, as takers dont use collateral payments.

However takers are unique in the way that takers pay CoinSwap fees. So
for a taker to attack a maker via post-coinswap-fee-burning they first
need to pay CoinSwap fees. So we just have makers refuse to sign RBF
transactions paying a fee higher than the CoinSwap fee they earn. (Or
perhaps a constant factor, for example a maker imposes the condition
that the RBF miner fee can only be 5x or 10x the CoinSwap fee).

== Funding transaction definitions ==
Same as in the v1 design doc.

== Contract transaction definitions ==
In the v1 design each party in a CoinSwap possessed the _same_ contract
transaction. This is no longer the case, and each party might know
slightly different versions, perhaps differing by miner fees or whether
a collateral payment is used.

As before the value in square parentheses refers to bitcoin amount. The
value in the round parentheses refers to script.

Contract transactions have this notation based on who knows them:
    contract tx for the Alice-Bob multisig, known only to Alice
  = contract tx Alice-Bob/Alice
  = contract tx AB/A

=== Contract txes known by receiver ===
These are contract transactions known by the receiver of coins from the
multisig. They are pretty much the same as in v1, except with added `1
OP_CSV` to the hashlock (not included here for clarity).

Alice-Bob/Bob contract tx:
    multisig (Alice+Bob) ---> (Alice+timelock_A OR Bob+hash)
    [I btc]                   [I-M~ btc]

Bob-Charlie/Charlie contract tx:
    multisig (Bob+Charlie) ---> (Bob+timelock_B OR Charlie+hash)
    [I-M2-B btc]                [I-M2-B-M~ btc]

Charlie-Alice/Alice contract tx:
    multisig (Charlie+Alice) ---> (Charlie+timelock_C OR Alice+hash)
    [(I-M2-B)-M3-C btc]           [(I-M2-B)-M3-C-M~ btc]

=== Table of balances before and after a coinswap resolved with contract
txes known to recievers ===
If a CoinSwap is resolved with contract txes known to receivers, then
that means the parties had to get their money back by broadcasting and
mining the contract transactions, and spending the output using their
knowledge of the hash preimage. Each party has to spend the output
before the timeout expires, so that costs an additional miner fee M~.

Party   | Before | After
--------|--------|-------------------------------------------
Alice   | WA     | WA-M1-I + (I-M2-B)-M3-C-M~ - M~ = WA-M1-M2-M3-B-C-2M~
Bob     | WB     | WB-I+B + I-M~ - M~              = WB+B-2M~
Charlie | WC     | WC-(I-M2-B)+C + I-M2-B-M~ - M~  = WC+C-2M~

The makers earn their CoinSwap fees but pay an additional miner fee
twice, so they are incentivized to avoid this outcome compared to the
success case where they just earn their fees. Alice is incentivized to
avoid this outcome because she would pay for miner fees and coinswap
fees, and not get any privacy in return.

=== Contract txes known by the sender ===
The maker's contract transaction must include a collateral payment.

definitions:
    Jb, Jc = value of a maker's (Bob, Charlie) collateral input
    K = collateral amount, which a maker loses if he broadcasts his
contract tx but doesnt get the money using the hash preimage

Alice-Bob/Alice contract tx:
    multisig (Alice+Bob) ---> (Alice+timelock_A OR Bob+hash)
             [I btc]          [I-M~ btc]

Bob-Charlie/Bob contract tx:
    multisig  (Bob+Charlie) ---> (Bob+timelock_B OR Charlie+hash)
              [I-M2-B btc]       [I-M2-B+K btc]
    singlesig (Bob)              (Bob)
              [Jb btc]           [Jb-K-M~ btc]

Charlie-Alice/Charlie contract tx:
    multisig  (Charlie+Alice)     ---> (Charlie+timelockC OR Alice+hash)
              [(I-M2-B)-M3-C btc]      [(I-M2-B)-M3-C+K btc]
    singlesig (Charlie)                (Charlie)
              [Jc btc]                 [Jc-K-M~ btc]

=== Table of balances before and after a coinswap resolved with contract
txes known to senders ===
If a coinswap is resolved with contract txes known to senders, then that
means the parties had to get their money back by broadcasting and mining
the contract transactions, and spending the output by waiting for the
timeout.

Party   |Before | After
--------|-------|-------------------------------------------
Alice   | WA    |WA-M1-I + I-M~                            = WA-M1-M~
Bob     | WB+Jb |WB-I+B + I-M2-B+K + Jb-K-M~               = WB+Jb-M2-M~
Charlie | WC+Jc |WC-(I-M2-B)+C + (I-M2-B)-M3-C+K + Jc-K-M~ = WC+Jc-M3-M~

Everyone gets their money back and pays for their own miner fees. And
the CoinSwap didn't happen, which is crappy considering money was lost
in miner fees but part of the point of fidelity bonds is to stop this
happening too much.

=== Table of balances before and after a successful CoinSwap but with
one post-CoinSwap-theft-attempt ===
Here the CoinSwap has succeeded but one maker (Bob in this case) does a
post-coinswap-theft-attempt, which fails, because the next party
(Charlie) uses the hash preimage to spend the coins. Most coins can
remain unspent on-chain because of private-key-handover, but the
Bob-Charlie/Bob contract transaction was broadcast and mined.

Party   | Before | After
--------|--------|-------------------------------------------
Alice   | WA     | WA-M1-I + (I-M2-B)-M3-C  = WA-M1-M2-M3-B-C
Bob     | WB+Jb  | WB-I+B + Jb-K-M~ + I     = WB+Jb+B-K-M~
Charlie | WC     | WC-(I-M2-B)+C + I-M2-B+K = WC+C+K

As we see, Alice's outcome is the same as in the success case. Compared
to the success case, Bob loses K bitcoins and an extra miner fee while
Charlie gains K bitcoins.

Looking at these equations, I realize that the incentives against
post-coinswap-theft-attempt still work even if we set K = 0, because the
extra miner fee paid by Bob could be enough disincentive.

== Protocol ==
Definitions:
    A fund = Alice's funding tx
    AB/A us htlc = unsigned contract tx for the A-B multisig, where the
        fully-signed version is only meant to be known by A
    AB/A htlc B/2 = Bob's signature for contract tx for the A-B
        multisig, where the fully-signed version is only meant to be
        known by A
    p = nonce point p used in the tweak EC protocol for calculating the
        maker's pubkey, used to avoid one round trip
    privA(A+B) = private key generated by Alice in the A-B multisig

 | Alice           | Bob             | Charlie         |
 |=================|=================|=================|
0.  AB/A us htlc ---->               |                 |
1.               <---- AB/A htlc B/2 |                 |
2.    ***** BROADCAST AND MINE ALICE FUNDING TX *****  |
3.    A fund + p ---->               |                 |
4.               <---- AB/B us htlc  |                 |
5. AB/B htlc A/2 ---->               |                 |
6.                 |  BC/B us htlc ---->               |
7.                 |               <---- BC/B htlc C/2 |
8.    ***** BROADCAST AND MINE BOB FUNDING TX *****    |
9.                 |    B fund + p ---->               |
A.                 |               <---- BC/C us htlc  |
B.                 | BC/C htlc B/2 ---->               |
C.               <---------------------- CA/C us htlc  |
D. CA/C htlc A/2 ---------------------->               |
E.   ***** BROADCAST AND MINE CHARLIE FUNDING TX ***** |
F.               <---------------------- C fund + p    |
G.  CA/A us htlc ---------------------->               |
H.               <---------------------- CA/A htlc C/2 |
I. hash preimage ---------------------->               |
J. hash preimage ---->               |                 |
K.    privA(A+B) ---->               |                 |
L.                 |    privB(B+C) ---->               |
M.               <---------------------- privC(C+A)    |

=== Protocol notes ===
0-2. Alice sets up her funding tx and contract tx for possible refund
     with timeout
3.   Alice convinces Bob that their multisig is funded, and therefore
     this whole thing isnt a DOS
4-5. Bob obtains his contract tx for the A-B multisig
6-8. Same as 0-2 but for Bob
9.   Same as 3. but for Bob/Charlie
A-B. Same as 4-5 but for Charlie
C-E. Same as 0-2 and 6-8 but for Charlie
F.   Same as 3 and 9 but for Charlie/Alice
G-H. Same as 4-5 or A-B but for Alice
H.   After this step every party's coins are locked up in multisig, and
     they can all get the coins back after the timeout, or if they know
     the hash preimage they can get different coins immediately.
I-J. Reveal preimages to everyone, making the coins do an off-chain hop
     ahead by one step.
K-M. Reveal private keys to each other. The incentive to do this is to
     save on miner fees, and improve privacy.

=== Analysis of aborts ===
Aborts are when one party halts the protocol (i.e. they had a power cut,
or they are a DOS attacker). Here we analyze how the other parties react.

As in v1, the number refers to the step number where the abort happened.

0. Alice: aborts. Bob/Charlie: do nothing, they havent lost any time or
   money.
1. Bob: aborts. Alice: lost no time or money, try with another Bob.
   Charlie: do nothing
2-3. Same as 0.
4. Bob: aborts. Charlie: do nothing. Alice: broadcasts contract tx AB/A
   and waits for the timeout, loses time and money on miner fees, she'll
   never coinswap with Bob's fidelity bond again.
5. Same as 0.
6. Same as 4.
7. Charlie: aborts. Alice/Bob: lose nothing, find another Charlie to
   coinswap with.
8. Same as 4.
9. Similar to 4 but Alice MIGHT not blacklist Bob's fidelity bond,
   because Bob will also have to broadcast his contract tx BC/B and will
   also lose time and money. Alice could take Bob's collateral from
   transaction BC/B, but the value K is small and Alice must spend time
   and miner fees on her funding transaction, so this isn't a way to DOS
   for free.
A. Charlie: aborts. Bob: broadcast his contract tx BC/B and wait for the
   timeout to get his money back, also broadcast Alice's contract
   transaction AB/B in retaliation. Alice: waits for the timeout on her
   contract tx that Bob broadcasted, will never do a coinswap with
   Charlie's fidelity bond again.
B. Same as 9.
C. Same as A.
D. Alice: aborts. Charlie: do nothing, no money or time lost. Bob:
   broadcast BC/B contract tx and wait for timeout to get money back,
   comforted by the knowledge that when Alice comes back online she'll
   have to do the same thing and waste the same amount of time and
   money.
E. Same as A.
F. Similar to A. but Alice MIGHT not blacklist Charlie's fidelity bond,
   because Charlie will also have to broadcast his contract tx CA/C and
   will also lose time and money.
G. Alice: aborts. Bob/Charlie: all broadcast their contract txes and
   wait for the timeout to get their money back.
H. Same as F.
I-K. Similar to G, but if Charlie knows the hash preimage he can use his
     contract tx to get the money immediately instead of waiting for the
     timeout. Bob can read that preimage from the blockchain and use it
     to also get his money immediately.
L. Bob: aborts. Alice: hopefully get Charlie's privkey, but if not then
   broadcast CA/A and use preimage to get money immediately, and never
   coinswap with Bob's fidelity bond again. Charlie: broadcast BC/C and
   use preimage to get money immediately.
M. Charlie: aborts. Alice: broadcast CA/A and use preimage to get money
   immediately, and never coinswap with Charlie's fidelity bond again.
   Bob: do nothing, already has Alice's privkey.

== Analysis of deviations ==

Deviations are when one party does something other than what's in the
protocol, for example broadcasting a contract transaction when they
shouldnt have.

The party name refers to what that party does, followed by other party's
reactions to it.
e.g. Party1: does a thing, Party2/Party3: does a thing in reaction.

If multiple deviations are possible in a step then they are numbered.
e.g. 5(1) 5(2) 5(3)

0-2. Alice/Bob/Charlie: nothing else is possible except following the
protocol
     or aborting.
3. Alice: broadcasts one or more of the AB/A contract txes. Bob/Charlie:
   do nothing, they havent lost any time or money.
4. Bob/Charlie: nothing else is possible except following the protocol
   or aborting.
5. Same as 3.
6. Bob: broadcasts one or more of the AB/B contract txes. Alice:
   broadcasts the remaining contract txes and waits for the timeout to
   get her money back, and never coinswaps with Bob's fidelity bond
   again. Charlie: do nothing.
7. Charlie: nothing else is possible except following the protocol or
   aborting.
8. Same as 6.
9(1). Same as 6.
9(2). Bob: broadcast BC/B contract txes. Alice: broadcast her AB/A
      contract tx and wait for the timeout to get her money back, and
      never coinswaps with Bob's fidelity bond again. Charlie: do
      nothing.
A. Charlie: broadcast BC/C contract tx. Bob: wait for the timeout to get
   his money back, also broadcast Alice's contract transaction AB/B in
   retaliation. Alice: waits for the timeout on her contract tx that Bob
   broadcasted, will never do a coinswap with Charlie's fidelity bond
   again.
B. Same as 9(1). and 9(2).
C. Same as A.
D. Alice: broadcast AB/A contract tx. Bob: broadcast his own BC/B
   contract tx and wait for the timeout to get his money back. Charlie:
   do nothing
E. Same as A.
F. Charlie: broadcast CA/C contract tx. Alice: broadcast her AB/A
   contract tx and wait for the timeout to get her money back, never do
   a coinswap with Charlie's fidelity bond again. Bob: broadcast his
   BC/B contract tx and wait for the timeout to get his money back.
G. Same as D. except Charlie must also broadcast his CA/C contract tx
   and wait for the timeout.
H. Same as F.
I-K(1). Alice: broadcast AB/A contract txes. Bob: broadcast BC/B
        contract txes and wait for the timeout, or use the hash preimage
        if he knows it. Charlie: broadcast CA/A contract txes and wait
        for timeout, or use hash preimage if known.
I-K(2). Alice: broadcast CA/A contract txes. Bob: broadcast AB/B and
        wait for the timeout, or use the hash preimage if its known.
        Charlie: broadcast BC/C and wait for timeout, or use the hash
        preimage if known.
I-K(3). Alice: broadcast both AB/A and CA/A contract txes. Bob:
        broadcast BC/B contract tx and wait for the timeout, or use the
        hash preimage if its known. Charlie: broadcast BC/C if Bob
        hasn't broadcast his, and wait for the timeout, or use the hash
        preimage if known.
L. Similar to I-K(n), Bob can broadcast one or both the sets of contract
   txes he knows. The other parties broadcast the remaining ones and
   either use the timeout or hash preimage value. Alice bans Bob's
   fidelity bond.
M. Same as L. but Charlie broadcasting. Alice bans Charlie's fidelity
   bond.

Unlike the v1 protocol, each CoinSwap party knows a different version of
the contract transactions, so the taker Alice always knows which maker
broadcast a certain set of contract transactions, and so can always ban
the correct fidelity bond.

== Conclusion ==
This document modifies the earlier version 1 detailed protocol design
for multi-transaction CoinSwap. It has each CoinSwap party knowing a
slightly different version of the contract transactions. It also uses
collateral payments. These features are both used to fix attacks found
during review of the v1 protocol.