Commit Graph

241 Commits

Author SHA1 Message Date
Byron Hambly
796863359f
upgrade secp256kfun (#1466)
* ci: add cargo check on rust stable

* refactor: upgrade secp256kfun and fix resulting issues

* build(deps): update sigma_fun and ecdsa_fun to a52142cf7f

 #1520
 #1521

* chore: fix clippy issue

* update to 91112f80b24

* bump to 294de1721add

* chore(deps): remove spectral

spectral fails to compile on rust stable 1.76 due to dep on deprecated
rustc-serialize

* secp256kfun: update to 7da9d277 and set rev in manifest

* update to 6fdc5d8

* switch to crates.io versions of ecdsa_fun and sigma_fun

* ci: update toolchain to 1.74 and fix draft action

* clippy fixes

---------

Co-authored-by: binarybaron <86064887+binarybaron@users.noreply.github.com>
2024-05-27 11:03:20 +02:00
yamabiiko
5ff46be279
RPC server for API Interface (#1276)
* saving: implementing internal api shared by cli and rpc server

* writing async rpc methods and using arc for shared struct references

* cleaning up, renamed Init to Context

* saving: cleaning up and initial work for tests

* Respond with bitcoin withdraw txid

* Print RPC server address

* Cleanup, formatting, add `get_seller`, `get_swap_start_date` RPC endpoints

* fixing tests in cli module

* uncommenting and fixing more tests

* split api module and propagate errors with rpc server

* moving methods to api and validating addresses for rpc

* add broadcast channel to handle shutdowns gracefully and prepare for RPC server test

* added files

* Update rpc.rs

* adding new unfinished RPC tests

* updating rpc-server tests

* fixing warnings

* fixing formatting and cargo clippy warnings

* fix missing import in test

* fix: add data_dir to config to make config command work

* set server listen address manually and return file locations in JSON on Config

* Add called api method and swap_id to tracing for context, reduced boilerplate

* Pass server_address properly to RpcServer

* Update Cargo.lock

* dprint fmt

* Add cancel_refund RPC endpoint

* Combine Cmd and Params

* Disallow concurrent swaps

* Use RwLock instead of Mutex to allow for parallel reads and add get_current_swap endpoint

* Return wallet descriptor to RPC API caller

* Append all cli logs to single log file

After careful consideration, I've concluded that it's not practical/possible to ensure that the previous behaviour (one log file per swap) is preserved due to limitations of the tracing-subscriber crate and a big in the built in JSON formatter

* Add get_swap_expired_timelock timelock, other small refactoring

- Add get_swap_expired_timelock endpoint to return expired timelock if one exists. Fails if bitcoin lock tx has not yet published or if swap is already finished.
- Rename current_epoch to expired_timelock to enforce consistent method names
- Add blocks left until current expired timelock expires (next timelock expires) to ExpiredTimelock struct
- Change .expect() to .unwrap() in rpc server method register because those will only fail if we register the same method twice which will never happen

* initiating swaps in a separate task and handling shutdown signals with broadcast queues

* Replace get_swap_start_date, get_seller, get_expired_timelock with one get_swap_info rpc method

* WIP: Struct for concurrent swaps manager

* Ensure correct tracing spans

* Add note regarding Request, Method structs

* Update request.rs

* Add tracing span attribute log_reference_id to logs caused by rpc call

* Sync bitcoin wallet before initial max_giveable call

* use Span::current() to pass down to tracing span to spawned tasks

* Remove unused shutdown channel

* Add `get_monero_recovery_info` RPC endpoint

- Add `get_monero_recovery_info` RPC endpoint
- format PrivateViewKey using Display

* Rename `Method::RawHistory` to `Method::GetRawStates`

* Wait for swap to be suspended after sending signal

* Remove notes

* Add tracing span attribute log_reference_id to logs caused by rpc call

* Sync bitcoin wallet before initial max_giveable call

* use Span::current() to pass down to tracing span to spawned tasks

* Remove unused shutdown channel

* Add `get_monero_recovery_info` RPC endpoint

- Add `get_monero_recovery_info` RPC endpoint
- format PrivateViewKey using Display

* Rename `Method::RawHistory` to `Method::GetRawStates`

* Wait for swap to be suspended after sending signal

* Return additonal info on GetSwapInfo

* Update wallet.rs

* fix compile issues for tests and use serial_test crate

* fix rpc tests, only check for RPC errors and not returned values

* Rename `get_raw_history` tp `get_raw_states`

* Fix typo in rpc server stopped tracing log

* Remove unnecessary success property on suspend_current_swap response

* fixing test_cli_arguments and other tests

* WIP: RPC server integration tests

* WIP: Integration tests for RPC server

* Update rpc tests

* fix compile and warnings in tests/rpc.rs

* test: fix assert

* clippy --fix

* remove otp file

* cargo clippy fixes

* move resume swap initialization code out of spawned task

* Use `in_current_span` to pass down tracing span to spawned tasks

* moving buy_xmr initialization code out of spawned tasks

* cargo fmt

* Moving swap initialization code inside tokio select block to handle swap lock release logic

* Remove unnecessary swap suspension listener from determine_btc_to_swap call in BuyXmr

* Spawn event loop before requesting quote

* Release swap lock after receiving shutdown signal

* Remove inner tokio::select in BuyXmr and Resume

* Improve debug text for swap resume

* Return error to API caller if bid quote request fails

* Print error if one occurs during process invoked by API call

* Return bid quote to API caller

* Use type safe query! macro for database retrieval of states

* Return tx_lock_fee to API caller on GetSwapInfo call

Update request.rs

* Allow API caller to retrieve last synced bitcoin balane and avoid costly sync

* Return restore height on MoneroRecovery command to API Caller

* Include entire error cause-chain in API response

* Add span to bitcoin wallet logs

* Log event loop connection properties as tracing fields

* Wait for background tasks to complete before exiting CLI

* clippy

* specify sqlx patch version explicitly

* remove mem::forget and replace with _guard

* ci: add rpc test job

* test: wrap rpc test in #[cfg(test)]

* add missing tokio::test attribute

* fix and merge rpc tests, parse uuuid and multiaddr from serde_json value

* default Tor socks port to 9050, Cargo fmt

* Update swap/sqlite_dev_setup.sh: add version

Co-authored-by: Byron Hambly <byron@hambly.dev>

* ci: free up space on ubuntu test job

* Update swap/src/bitcoin/wallet.rs

Co-authored-by: Byron Hambly <byron@hambly.dev>

* Update swap/src/bitcoin/wallet.rs

Co-authored-by: Byron Hambly <byron@hambly.dev>

* fmt

---------

Co-authored-by: binarybaron <86064887+binarybaron@users.noreply.github.com>
Co-authored-by: Byron Hambly <byron@hambly.dev>
2024-05-22 15:12:58 +02:00
Byron Hambly
00cfce57c7
chore: fix dprint config and run fmt 2023-03-15 14:19:57 +02:00
Byron Hambly
fb42ca13cc
chore: clippy fix 2022-10-19 15:02:46 +02:00
rishflab
da9d09aa5e Create Database trait
Use domain types in database API to prevent leaking of database types.
This trait will allow us to smoothly introduce the sqlite database.
2021-09-30 18:56:52 +10:00
rishflab
ce58b8b333 Handle errors when waiting for subscriptions
We were not thorough enough in PR #705 and there were some remaining
unhandled errors.

Co-authored-by: Daniel Karzel <daniel@comit.network>
2021-09-02 14:23:41 +10:00
Daniel Karzel
18faa786d6 Fail if something goes wrong when checking tx lock status
Probably a failure when interacting with the electrum node to get script
 status updates
2021-08-31 18:26:00 +10:00
Thomas Eizinger
8f50eb2f34
Utilize tracing's fields more 2021-07-07 16:02:02 +10:00
Thomas Eizinger
9119ce5cc4
Tidy up log messages across the codebase
1. Clearly separate the log messages from any fields that are
captured. The log message itself should be meaningful because it
depends on the underlying formatter, how/if the fields are displayed.
2. Some log messages had very little context, expand that.
3. Wording of errors was inconsistent, hopefully all errors should
now start with `Failed to ...`.
4. Some log messages were duplicated across multiple layers (like opening
the database).
5. Some log messages were split into two where one part is now an `error!`
and the 2nd part is an `info!` on what is happening next.
6. Where appropriate, punctuation has been removed to not interrupt
the reader's flow.
2021-07-07 16:02:00 +10:00
Thomas Eizinger
78480547d5
Don't import tracing's macros
Log statements end up getting changed constantly and having to clean
up imports after that is annoying, for example, if the last `info!`
in a file disappears, you end up with an unused import warning.

Fully qualifying tracing's macros prevents that and also communicates
clearly that we are using tracing and not log.
2021-07-07 16:01:33 +10:00
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.
2021-06-28 10:04:08 +10:00
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).
2021-06-28 10:04:07 +10:00
Daniel Karzel
529de8d5fd
ASB aborts if CLI does not lock BTC
Includes a new state that is used to await BTC lock tx finality. Upon starting the swap we initially only wait for the BTC lock tx to be seen in the mempool.
This is guarded by a short timeout (3 mins), because it is assumed that in the current setup (sport_price + execution_setup only triggered upon funds being available already) the lock transaction should be picked up almost instanly after the execution setup succeeded.
2021-06-23 17:54:42 +10:00
Daniel Karzel
c4c798ea20
Timeout on execution_setup for ASB
Similar to the CLI the ASB has to ensure that the execution_setup is executed within a certain time.
Without a timeout the price (returned by `spot_price` would be guaranteed with the CLI indefinitely.
2021-06-23 17:54:42 +10:00
Thomas Eizinger
b7064578ca
Reduce level of indentation of match statements 2021-06-21 11:46:24 +10:00
Thomas Eizinger
f1182f97c0
Simplify match statement
This code is unnecessarily complicated.
2021-06-21 11:31:24 +10:00
Thomas Eizinger
1ba186aa63
Make log message a proper statement
"Listening on" is only half a sentence.
2021-06-21 09:01:21 +10:00
bors[bot]
baf5a0896e
Merge #536
536: Switch to using stable Rust instead of nightly r=thomaseizinger a=thomaseizinger



Co-authored-by: Thomas Eizinger <thomas@eizinger.io>
2021-05-28 04:47:26 +00:00
Daniel Karzel
c9064d5a37
Add ping protocol to ensure connection is alive
Adds the ping behaviour to both ASB and CLI behaviour that periodically pings a connected party to ensure that the underlying network connection is still alive.
This fixes problems with long-running connections that become dead without a connection closure being reported back to the swarm.
2021-05-27 11:19:27 +10:00
Thomas Eizinger
8f9d612af2
Change to stable Rust 1.52
Fix clippy warnings that are new in this version.
2021-05-25 16:11:49 +10:00
Daniel Karzel
01af9a5676
Bitcoin transaction published state
This improves the error handling on the ASB.
Once the Bitcoin redeem transaction is seen in mempool, the state machine cannot transition to a cancel scenario anymore because at that point the CLI will have redeemed the Monero.
The additional state then waits for transaction finality.
2021-05-24 10:53:14 +10:00
Daniel Karzel
af60d3bb54
Network check upon spot price request 2021-05-20 13:03:29 +10:00
Philipp Hoenisch
316f95c65b
Always log whole causality chain for errors. 2021-05-11 15:27:53 +10:00
Philipp Hoenisch
c011e95062
Improve logging by adding details as fields instead of into the msg. 2021-05-11 15:27:53 +10:00
Philipp Hoenisch
1706b36800
Log exchange rate at each state. 2021-05-11 15:27:49 +10:00
Daniel Karzel
652aae9590
Introduce a minimum buy amount
Introduces a minimum buy Bitcoin amount similar to the maximum amount already present.
For the CLI the minimum amount is enforced by waiting until at least the minimum is available as max-giveable amount.
2021-05-11 12:03:02 +10:00
Daniel Karzel
6d3cf0af91
Include too low balance into Alice's error 2021-05-11 12:03:02 +10:00
Daniel Karzel
23d9637a4b
Work in review comments 2021-05-07 16:21:02 +10:00
Daniel Karzel
daa572e5bf
Move recovery commands in dedicated module
Less clutter in the folder structure.
2021-05-07 16:21:02 +10:00
Daniel Karzel
4deb96a3c5
ASB manual recovery commands
Adds `cancel`, `refund`, `punish`, `redeem` and `safely-abort` commands to the ASB that can be used to trigger the specific scenario for the swap by ID.
2021-05-07 16:19:11 +10:00
Daniel Karzel
89b3d07eba
Network protocol tests for spot_price behaviour
Each test spawns swarm for Alice and Bob that only contains the spot_price behaviours and uses a memory transport.
Tests cover happy path (i.e. expected price is returned) and error scenarios.
Implementation of `TestRate` on `LatestRate` allows testing rate fetch error and quote calculation error behaviour.

Thanks to @thomaseizinger for ramping up the test framework for comit-rs in the past!
2021-05-07 15:00:29 +10:00
Daniel Karzel
03a0dc73cd
Alice's spot_price Behaviour reports back Error
Instead of handling all errors on the inside spot_price errors are bubbled up (as `SwapRequestDeclined`).
This allows us to test both Alice's and Bob's behaviour for all scenarios.
2021-05-07 15:00:29 +10:00
Daniel Karzel
5aac76598d
Decouple ASB/CLI Errors from Error sent over wire
What goes over the wire should not be coupled to the errors being printed.
For the CLI and ASB we introduce a separate error enum that is used for logging.
When sending over the wire the errors are mapped to and from the `network::spot_price::Error`.

As part of Bob-specific spot_price code was moved from the network into bob.
Clearly separation of the network API from bob/alice.
2021-05-07 15:00:29 +10:00
Daniel Karzel
52f648e1de
Alice's spot price logic into dedicated behaviour
Move Alice's spot price logic into a dedicated network behaviour that handles all the logic.
The new behaviour encapsulates the complete state necessary for spot price request decision making.
The network behaviour cannot handle asynchronous calls, thus the balance is managed inside the spot price and has to updated regularly from the outside to ensure the spot price balance check has up to date data.
At the moment the balance is updated upon an incoming quote requests.

Code that is relevant for both ASB and CLI remains in the `network::spot_price` module (e.g. `network::spot_price::Error`).
2021-05-07 15:00:29 +10:00
Daniel Karzel
ea76ae5821
Return proper error to CLI for all expected scenarios
When a CLI requests a spot price have some errors that are expected, where we can provide a proper error message for the CLI:
- Balance of ASB too low
- Buy amount sent by CLI exceeds maximum buy amount accepted by ASB
- ASB is running in maintenance mode and does not accept incoming swap requests

All of these errors returns a proper error to the CLI and prints a warning in the ASB logs.
Any other unexpected error will result in closing the channel with the CLI and printing an error in the ASB logs.
2021-05-07 14:52:51 +10:00
Daniel Karzel
f6497778ed
Add resume-only mode for the ASB
Resume-only is a maintenance mode where no swaps are accepted but unfinished swaps are resumed.
This is achieve by ignoring incoming spot-price requests (that would lead to execution setup) in the event-loop.
2021-05-07 14:52:51 +10:00
Philipp Hoenisch
59a55dcbdd
Remove todo for cleanup note. 2021-05-07 10:24:41 +10:00
Philipp Hoenisch
68ae47edf4
Log error message. 2021-05-07 10:24:41 +10:00
Philipp Hoenisch
dc8dd5af28
Add relative and absolute max transaction fee. 2021-05-07 10:24:41 +10:00
Philipp Hoenisch
dc6ab0fa52
Ensure that constant weights do not go out of sync with code. 2021-05-07 10:24:41 +10:00
Philipp Hoenisch
77f6f11a7f
Pass address/fees into State0 instead of passing in the wallet. 2021-05-07 10:24:41 +10:00
Philipp Hoenisch
9e8b788aa9
Rename weight constants. 2021-05-07 10:24:41 +10:00
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.
2021-05-07 10:24:41 +10:00
Philipp Hoenisch
38540b4de5
Dynamically chose fee for TxCancel.
Bob chooses the fee for TxCancel because he is the one that cares.
2021-05-07 10:24:41 +10:00
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.
2021-05-07 10:24:41 +10:00
Philipp Hoenisch
d5c1b6693e
Dynamically chose fee for TxRedeem.
Alice chooses the fee for TxRedeem because she 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.
2021-05-07 10:24:41 +10:00
Daniel Karzel
3c2dfa830a
Peer check for incoming encrypted signatures
Alice validates that incoming encsig messages are coming from the peer-id that is associated with the swap.
Encsig message from a peer-id different to the one associated with the swap are ignored.
2021-04-29 18:24:45 +10:00
Thomas Eizinger
5b515d6fb2
Don't qualify with alice:: if we are within a module of Alice 2021-04-26 12:45:37 +10:00
Thomas Eizinger
6d06db3259
Use macro-based JSON-RPC client 2021-04-26 12:45:35 +10:00
dependabot[bot]
19483c5ead
Bump libp2p from 0.36.0 to 0.37.1
Bumps [libp2p](https://github.com/libp2p/rust-libp2p) from 0.36.0 to 0.37.1.
- [Release notes](https://github.com/libp2p/rust-libp2p/releases)
- [Changelog](https://github.com/libp2p/rust-libp2p/blob/master/CHANGELOG.md)
- [Commits](https://github.com/libp2p/rust-libp2p/compare/v0.36.0...v0.37.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-04-20 11:51:40 +10:00