Commit Graph

82 Commits (620ac569f7db4b19c3dc761619e7a4d0ab0841dd)

Author SHA1 Message Date
Daniel Karzel c0070f8fa7
Move files from `protocol` to appropriate module
Some network and application specific code does not belong in the protocol module and was moved.
Eventloop, recovery and the outside behaviour were moved to the respective application module because they are application specific.

The `swap_setup` was moved into the network module because upon change both sides will have to be changed and should thus stay close together.
3 years ago
Daniel Karzel 818147a629
`swap_setup` instead of `spot_price` and `execution_setup`
Having `spot_price` and `execution_setup` as separate protocols did not bring any advantages, but was problematic because we had to ensure that `execution_setup` would be triggered after `spot_price`. Because of this dependency it is better to combine the protocols into one.

Combining the protocols also allows a refactoring to get rid of the `libp2p-async-await` dependency.

Alice always listens for the `swap_setup` protocol. When Bob opens a substream on that protocol the spot price is communicated, and then all execution setup messages (swap-id and signature exchange).
3 years ago
Daniel Karzel fb9fb21c2b
CLI log statements to be more JSON friendly
Values to be logged as fields.
Upon starting a swap we print the swap-id as well.
3 years ago
Philipp Hoenisch dc8dd5af28
Add relative and absolute max transaction fee. 3 years ago
Philipp Hoenisch dc6ab0fa52
Ensure that constant weights do not go out of sync with code. 3 years ago
Philipp Hoenisch 9e8b788aa9
Rename weight constants. 3 years ago
Philipp Hoenisch ee90c228b4
Dynamically calculate fees using electrum's estimate_fee.
Electrum has an estimate-fee feature which takes as input the block you want a tx to be included.
The result is a recommendation of BTC/vbyte.
Using this recommendation and the knowledge about the size of our transactions we compute an appropriate fee.
The size of the transactions were taken from real transactions as published on bitcoin testnet.
Note: in reality these sizes might fluctuate a bit but not for much.
3 years ago
Philipp Hoenisch 38540b4de5
Dynamically chose fee for TxCancel.
Bob chooses the fee for TxCancel because he is the one that cares.
3 years ago
Philipp Hoenisch 1012e39527
Dynamically chose fee for TxRefund and TxPunish.
Alice chooses the fee for TxPunish because she is the one that cares.
Bob chooses the fee for TxRefund because he is the one that cares.

Note must be taken here because if the fee is too low (e.g. < min tx fee) then she might not be able to publish TxRedeem at all.
3 years ago
Thomas Eizinger e266fb07ef
Don't stutter 3 years ago
Thomas Eizinger 6d06db3259
Use macro-based JSON-RPC client 3 years ago
bors[bot] 19766b9759
Merge #405
405: Concurrent swaps with same peer r=da-kami a=da-kami

Fixes #367 

- [x] Concurrent swaps with same peer

Not sure how much more time I should invest into this. We could just merge the current state and then do improvements on top...?

Improvements:

- [x] Think `// TODO: Remove unnecessary swap-id check` through and remove it
- [x] Add concurrent swap test, multiple swaps with same Bob
- [ ] Save swap messages without matching swap in execution in the database
- [ ] Assert the balances in the new concurrent swap tests
- [ ] ~~Add concurrent swap test, multiple swaps with different Bobs~~
- [ ] ~~Send swap-id in separate message, not on top of `Message0`~~

Co-authored-by: Daniel Karzel <daniel@comit.network>
3 years ago
Daniel Karzel c976358c37
Multiple swaps with the same peer
- Swap-id is exchanged during execution setup. CLI (Bob) sends the swap-id to be used in his first message.
- Transfer poof and encryption signature messages include the swap-id so it can be properly associated with the correct swap.
- ASB: Encryption signatures are associated with swaps by swap-id, not peer-id.
- ASB: Transfer proofs are still associated to peer-ids (because they have to be sent to the respective peer), but the ASB can buffer multiple
- CLI: Incoming transfer proofs are checked for matching swap-id. If a transfer proof with a different swap-id than the current executing swap is received it will be ignored. We can change this to saving into the database.

Includes concurrent swap tests with the same Bob.

- One test that pauses and starts an additional swap after the transfer proof was received. Results in both swaps being redeemed after resuming the first swap.
- One test that pauses and starts an additional swap before the transfer proof is sent (just after BTC locked). Results in the second swap redeeming and the first swap being refunded (because the transfer proof on Bob's side is lost). Once we store transfer proofs that we receive during executing a different swap into the database both swaps should redeem.

Note that the monero harness was adapted to allow creating wallets with multiple outputs, which is needed for Alice.
3 years ago
Daniel Karzel 489696ee08
Swap-id as file name for generated Monero wallet
Instead of using the private view-key as wallet filename we use the swap-id, to be able to identify which wallet is associated with which swap.
3 years ago
Daniel Karzel 548f057726
Try to open wallet in case generate_from_keys fails 3 years ago
Thomas Eizinger 5d75f1adba
Remove import line in favor of FQ macro usage 3 years ago
Thomas Eizinger 4c2e254543
Don't log subscription
This object is very verbose and not meant to be logged.
3 years ago
Thomas Eizinger 01739eddb1
Introduce a more flexible transaction subscription system
Instead of watching for status changes directly on bitcoin::Wallet,
we return a Subscription object back to the caller. This subscription
object can be re-used multiple times.

Among other things, this now allows callers of `broadcast` to decide
on what to wait for given the returned Subscription object.

The new API is also more concise which allows us to remove some of
the functions on the actor states in favor of simple inline calls.

Co-authored-by: rishflab <rishflab@hotmail.com>
3 years ago
Thomas Eizinger c5827f84ca
Refactor recursive function to loop
This should get rid of the ever-growing stack size issue.
3 years ago
Thomas Eizinger fc175a3f53
De-couple state from Monero wallet 3 years ago
Thomas Eizinger cde3f0f74a
Remove connection handling from swap execution
The swap should not be concerned with connection handling. This is
the responsibility of the overall application.

All but the execution-setup NetworkBehaviour are `request-response`
behaviours. These have built-in functionality to automatically emit
a dial attempt in case we are not connected at the time we want to
send a message. We remove all of the manual dialling code from the
swap in favor of this behaviour.

Additionally, we make sure to establish a connection as soon as the
EventLoop gets started. In case we ever loose the connection to Alice,
we try to re-establish it.
3 years ago
Thomas Eizinger 16dfea035b
Simplify code within BobState::XmrLockProofReceived
To achieve this, we decompose `watch_for_locked_xmr` into two parts:

1. A non-self-consuming function to construct a `WatchRequest`
2. A state transition that can now consume `self` again because
it is only called once within the whole select! expression.

Ideally, we would move more logic onto this state transition (like
comparing the actual amounts and fail the transition if it is not
valid). Doing so would have an unfortunate side-effect: We would
always wait for the full confirmations before checking whether or
not we actually receive enough XMR.

This allows us to have state transitions that consume self.
3 years ago
Thomas Eizinger 338f4b82e5
Introduce dedicated bob::State6 for cancelling 3 years ago
Thomas Eizinger c32ef92cf5
Simplify code within BobState::EncSigSent 3 years ago
Thomas Eizinger 09e2d5b5d7
Simplify code within BobState::XmrLocked
By reducing the number of local variables, we can greatly simplify
this piece of code.
3 years ago
Thomas Eizinger b1affe3ecf
Insert latest state and call run_until only once
Instead of calling this function in all the branches, we can simply
make the whole match statement evaluate to the new state and perform
this functionality at the very end.
3 years ago
Thomas Eizinger 0d8962762a
Use early return to reduce one level of indentation 3 years ago
bors[bot] 113f2fa385
Merge #322
322: Refactor `ExecutionParams` and harmonize sync intervals of wallets r=thomaseizinger a=thomaseizinger



Co-authored-by: Thomas Eizinger <thomas@eizinger.io>
3 years ago
Thomas Eizinger 09c41f89c4
Rename ExecutionParams to EnvironmentConfig 3 years ago
Thomas Eizinger bc43ed6ebd
Pass execution params directly into wallet for initialization
This reduces the amount of parameters that we need to pass in.
3 years ago
rishflab 8675d88727 Don't wait for tx lock confirmed after broadcast
Bob does not care whether tx lock is confirmed. That is alice's problem.
This wait was introduced to remedy a bug in status_of_script() which was
 failing when called on a transaction with no confirmations.
3 years ago
Thomas Eizinger 273cf15631
Introduce `Watchable` abstraction for Bitcoin wallet
We have a repeated pattern where we construct one of our
Tx{Cancel,Redeem,Punish,Refund,Lock} transactions and wait until
the status of this transaction changes. We can make this more
ergonomic by creating and implementing a `Watchable` trait that
gives access to the TxId and relevant script for this transaction.
This allows us to remove a parameter from the `watch_until_status`
function.

Additionally, there is a 2nd pattern: "Completing" one of these
transaction and waiting until they are confirmed with the configured
number of blocks for finality. We can make this more ergonomic by
returning a future from `broadcast` that callers can await in case
they want to wait for the broadcasted transaction to reach finality.
3 years ago
Thomas Eizinger a0830f099f
Pass relevant execution params into wallet instead of via functions
The execution params don't change throughout the lifetime of the
program. They can be set in the wallet at the very beginning.
This simplifies the interface of the wallet functions.
3 years ago
rishflab e5c0158597
Greatly reduce load onto the Electrum backend
We achieve our optimizations in three ways:

1. Batching calls instead of making them individually.

To get access to the batch calls, we replace all our
calls to the HTTP interface with RPC calls.

2. Never directly make network calls based on function
calls on the wallet.

Instead, inquiring about the status of a script always
just returns information based on local data. With every
call, we check when we last refreshed the local data and
do so if the data is considered to be too old. This
interval is configurable.

3. Use electrum's notification feature to get updated
with the latest blockheight.

Co-authored-by: Thomas Eizinger <thomas@eizinger.io>
Co-authored-by: Rishab Sharma <rishflab@hotmail.com>
3 years ago
Thomas Eizinger c2329b19a2
Tell the user more about the monero lock transaction
First, we tell the user that we are now waiting for Alice to lock
the monero. Additionally, we tell them once we received the
transfer proof which will lead directly into the
"waiting for confirmations" function.
3 years ago
bors[bot] 20f2e56e2d
Merge #271
271: Bob can verify that the XMR lock tx was published r=da-kami a=da-kami

The Monero `txhash` log was removed. I feel the user should have the possibility to verify that the transaction was actually published so I added the tx-hash to the confirmation output. 

We could potentially print the tx-hash when receiving the transfer proof already, but that might not add much value compared to printing it with the confirmations. 

Additionally we should allow the user to at least know when the XMR can be expected in the user's wallet, otherwise the swap ends like this:

```
2021-03-04 13:49:19   INFO Monero lock tx received 5 out of 5 confirmations
```

This is just not very informative - yes, the final transaction is an implementation detail, but I don't think we should hide the transactions from the user. By printing the tx-hash for spending from the lock-tx into the user wallet we ensure the user knows that the XMR can now be expected in the user wallet. 

--- 

To add context, here the complete log (with debug enabled) **before** this change: 

```
2021-03-04 13:30:46  DEBUG Database and seed will be stored in /Users/dakami/Library/Application Support/xmr-btc-swap
2021-03-04 13:30:46  DEBUG Starting monero-wallet-rpc on port 56145
2021-03-04 13:30:51  DEBUG Requesting quote
2021-03-04 13:30:51   INFO Received quote: 1 XMR = 0.00433500 BTC
2021-03-04 13:30:51   INFO Still got 0.01018746 BTC left in wallet, swapping ...
2021-03-04 13:30:51   INFO Spot price for 0.00500000 BTC is 1.153402537485 XMR
2021-03-04 13:30:52  DEBUG Starting execution setup with 12D3KooWCdMKjesXMJz1SiZ7HgotrxuqhQJbP5sgBm2BwP1cqThi
2021-03-04 13:30:55   INFO Published Bitcoin 3a6690a962191529892318819fb20e7f1ac4625400e64ee734056a9b2a17ad8f transaction as lock
2021-03-04 13:41:13  DEBUG Received Transfer Proof from 12D3KooWCdMKjesXMJz1SiZ7HgotrxuqhQJbP5sgBm2BwP1cqThi
2021-03-04 13:42:11   INFO Monero lock tx received 1 out of 5 confirmations
2021-03-04 13:45:33   INFO Monero lock tx received 2 out of 5 confirmations
2021-03-04 13:47:49   INFO Monero lock tx received 3 out of 5 confirmations
2021-03-04 13:48:56   INFO Monero lock tx received 4 out of 5 confirmations
2021-03-04 13:49:19   INFO Monero lock tx received 5 out of 5 confirmations
2021-03-04 13:49:19  DEBUG Encrypted signature sent
2021-03-04 13:49:19  DEBUG Alice acknowledged encrypted signature
2021-03-04 13:49:19  DEBUG watching for tx: e5569d3f0bcccac95252dffaebe74ead0360c09b76bc762de890aaa0e51afbcf
2021-03-04 13:49:20  DEBUG Received protocol error "missing transaction" from Electrum, retrying...
2021-03-04 13:49:22  DEBUG Received protocol error "missing transaction" from Electrum, retrying...
```



Co-authored-by: Daniel Karzel <daniel@comit.network>
3 years ago
Daniel Karzel 47a31760c0 Bob can verify the Monero txs by tx-hash
Print tx-hashes for monero transactions to allow Bob to look the transaction up in block explorer.

The story of Bab:
Our famous actor Bob has a brother named Bab.
In school they were often mixed up, because their names were so similar.
Eventually Bab renamed himself into Barbara, but that was even more confusing for now he
carried a female name even though he was not female. Bob wanted to help his brother and told him he
could just go for Bub. But that did not solve anything. Fun fact: Bub is actually married to Alice.
3 years ago
Thomas Eizinger 6d9b21cb47
Change `imports_granularity` to module
This reduces the overall amount of LoC that imports take up in our
codebase by almost 100.
It also makes merge-conflicts less likely because there is less
grouping together of imports that may lead to layout changes which
in turn can cause merge conflicts.
3 years ago
bors[bot] d1363d130c
Merge #265
265: Replace quote with spot-price protocol r=thomaseizinger a=thomaseizinger

This is essentially functionally equivalent but includes some
cleanups by removing a layer of abstraction: `spot_price::Behaviour`
is now just a type-alias for a request-response behaviour.

Co-authored-by: Thomas Eizinger <thomas@eizinger.io>
3 years ago
Daniel Karzel 66c8401c95 Sweep all from generated wallet to user wallet
The default implementation for the command was removed because it does not
add additional value if we have a mandatory parameter anyway.
3 years ago
Thomas Eizinger 7042ed9441
Replace quote with spot-price protocol
This is essentially functionally equivalent but includes some
cleanups by removing a layer of abstraction: `spot_price::Behaviour`
is now just a type-alias for a request-response behaviour.
3 years ago
Thomas Eizinger 6b74761e34
Remove tracing context
The swap_cli can only do one swap at a time, no need for the swap ID span.
3 years ago
Thomas Eizinger bbbe5f7ae8
Demote / promote log messages to their appropriate level 3 years ago
Thomas Eizinger 7387884e6d
Move log messages to the appropriate abstraction layer
Log messages are ideally as close to the functionality they are talking about, otherwise we might end up repeating ourselves on several callsites or the log messages gets outdated if the behaviour changes.
3 years ago
Daniel Karzel 0945cee459 Remove traits in favour of public functions 3 years ago
Daniel Karzel 684cbe4d0b Remember monero wallet-height for Alice's refund scenario 3 years ago
Daniel Karzel fa04775188 Rename function explicit to cancellation to cancel
For transitioning to state4 we either go into a redeem or a cancellation scenario.
The function name state4 is misleading, because it is only used for cancellation scenarios.
3 years ago
Daniel Karzel 1404057dbe Remove misleading TODO
This TDOO is misleading, because - to our current knowledge - it is impossible for
Bob to retrieve the exact inclusion block-height of the lock transaction (send by Alice).
The wallet RPC is only capable of retrieving the inclusion block height of a transaction
through `get_payments` and `get_bulk_payments` which requires the `payment_id`.
The `payment_id` can be retrieved through `get_transfer_by_txid` which states
"Show information about a transfer to/from this address." - however the address that the
transfer goes to is not part of Bob's wallet yet! Thus, it is impossible for Bob to use
`get_transfer_by_txid` which in turn means Bob is unable to use `get_payments`.

The only possible way for Bob to know the exact inclusion block/height of the lock transaction
would be if Alice sends it over to Bob. But for that Alice would have to extract it she would have
to wait for confirmation - which she currently does not and might never do. Even if she does await
the first confirmation before sending the transfer proof the solution for retrieving the inclusion
block-height is not fleshed out on her side yet.
3 years ago
Daniel Karzel 9f1deb9fdc Wrap the Monero wallet client in a Mutex
In order to ensure that we can atomically generate_from_keys and then reload a wallet,
we have to wrap the client of the monero wallet RPC inside a mutex.
When introducing the Mutex I noticed that several inner RPC calls were leaking to the
swap crate monero wallet. As this is a violation of boundaries I introduced the traits
`GetAddress`, `WalletBlockHeight` and `Refresh`.

Note that the monero wallet could potentially know its own public view key and
public spend key. If we refactor the wallet to include this information upon wallet
creation we can also generate addresses using `monero::Address::standard`.
3 years ago
Daniel Karzel babd1d7b60
Wait for refund if insufficient Monero is locked up 3 years ago