From 6d9b21cb47061b0ded68f59180f0bd83eda1391b Mon Sep 17 00:00:00 2001 From: Thomas Eizinger Date: Thu, 4 Mar 2021 11:28:58 +1100 Subject: [PATCH] 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. --- rustfmt.toml | 2 +- swap/src/asb/amounts.rs | 3 +- swap/src/asb/command.rs | 3 +- swap/src/asb/config.rs | 11 ++--- swap/src/asb/kraken.rs | 3 +- swap/src/bin/asb.rs | 37 +++++++-------- swap/src/bin/swap_cli.rs | 31 +++++------- swap/src/bitcoin.rs | 41 ++++++++-------- swap/src/bitcoin/cancel.rs | 6 ++- swap/src/bitcoin/lock.rs | 3 +- swap/src/bitcoin/punish.rs | 3 +- swap/src/bitcoin/redeem.rs | 3 +- swap/src/bitcoin/refund.rs | 3 +- swap/src/bitcoin/wallet.rs | 42 ++++++++--------- swap/src/cli/command.rs | 9 ++-- swap/src/cli/config.rs | 9 ++-- swap/src/database.rs | 12 ++--- swap/src/database/alice.rs | 11 ++--- swap/src/database/bob.rs | 7 ++- swap/src/monero.rs | 29 +++++------- swap/src/monero/wallet.rs | 13 ++--- swap/src/monero/wallet_rpc.rs | 25 ++++------ swap/src/network/peer_tracker.rs | 19 +++----- swap/src/network/request_response.rs | 14 +++--- swap/src/network/spot_price.rs | 11 ++--- swap/src/network/transport.rs | 21 ++++----- swap/src/protocol.rs | 3 +- swap/src/protocol/alice.rs | 18 +++---- swap/src/protocol/alice/behaviour.rs | 30 ++++-------- .../src/protocol/alice/encrypted_signature.rs | 16 +++---- swap/src/protocol/alice/event_loop.rs | 33 +++++++------ swap/src/protocol/alice/execution_setup.rs | 15 ++---- swap/src/protocol/alice/state.rs | 21 ++++----- swap/src/protocol/alice/steps.rs | 32 +++++-------- swap/src/protocol/alice/swap.rs | 39 ++++++--------- swap/src/protocol/alice/transfer_proof.rs | 16 +++---- swap/src/protocol/bob.rs | 44 +++++++---------- swap/src/protocol/bob/cancel.rs | 8 ++-- swap/src/protocol/bob/encrypted_signature.rs | 10 ++-- swap/src/protocol/bob/event_loop.rs | 25 ++++------ swap/src/protocol/bob/execution_setup.rs | 12 ++--- swap/src/protocol/bob/refund.rs | 10 ++-- swap/src/protocol/bob/state.rs | 32 +++++-------- swap/src/protocol/bob/swap.rs | 17 ++++--- swap/src/protocol/bob/transfer_proof.rs | 16 +++---- swap/src/seed.rs | 15 +++--- swap/src/serde_peer_id.rs | 3 +- swap/src/trace.rs | 3 +- ...refunds_using_cancel_and_refund_command.rs | 6 ++- ...and_refund_command_timelock_not_expired.rs | 6 ++- ...fund_command_timelock_not_expired_force.rs | 6 ++- .../happy_path_restart_bob_before_comm.rs | 6 ++- swap/tests/testutils/bitcoind.rs | 6 +-- swap/tests/testutils/electrs.rs | 6 +-- swap/tests/testutils/mod.rs | 47 ++++++++++--------- 55 files changed, 389 insertions(+), 483 deletions(-) diff --git a/rustfmt.toml b/rustfmt.toml index 1ce52fc9..6e3e8004 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,7 +1,7 @@ edition = "2018" condense_wildcard_suffixes = true format_macro_matchers = true -imports_granularity = "Crate" +imports_granularity = "Module" use_field_init_shorthand = true format_code_in_doc_comments = true normalize_comments = true diff --git a/swap/src/asb/amounts.rs b/swap/src/asb/amounts.rs index 228672d9..3ca968c1 100644 --- a/swap/src/asb/amounts.rs +++ b/swap/src/asb/amounts.rs @@ -1,6 +1,7 @@ use crate::{bitcoin, monero}; use anyhow::{anyhow, Result}; -use rust_decimal::{prelude::ToPrimitive, Decimal}; +use rust_decimal::prelude::ToPrimitive; +use rust_decimal::Decimal; use std::fmt::{Debug, Display, Formatter}; /// Prices at which 1 XMR will be traded, in BTC (XMR/BTC pair) diff --git a/swap/src/asb/command.rs b/swap/src/asb/command.rs index 56ab2f64..f30d2a6b 100644 --- a/swap/src/asb/command.rs +++ b/swap/src/asb/command.rs @@ -1,5 +1,6 @@ use crate::bitcoin::Amount; -use bitcoin::{util::amount::ParseAmountError, Denomination}; +use bitcoin::util::amount::ParseAmountError; +use bitcoin::Denomination; use std::path::PathBuf; #[derive(structopt::StructOpt, Debug)] diff --git a/swap/src/asb/config.rs b/swap/src/asb/config.rs index b97e3c9a..2b411c21 100644 --- a/swap/src/asb/config.rs +++ b/swap/src/asb/config.rs @@ -1,14 +1,13 @@ use crate::fs::{default_data_dir, ensure_directory_exists}; use anyhow::{Context, Result}; use config::ConfigError; -use dialoguer::{theme::ColorfulTheme, Input}; +use dialoguer::theme::ColorfulTheme; +use dialoguer::Input; use libp2p::core::Multiaddr; use serde::{Deserialize, Serialize}; -use std::{ - ffi::OsStr, - fs, - path::{Path, PathBuf}, -}; +use std::ffi::OsStr; +use std::fs; +use std::path::{Path, PathBuf}; use tracing::info; use url::Url; diff --git a/swap/src/asb/kraken.rs b/swap/src/asb/kraken.rs index 27020597..f6188dcb 100644 --- a/swap/src/asb/kraken.rs +++ b/swap/src/asb/kraken.rs @@ -7,7 +7,8 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use std::convert::TryFrom; use tokio::sync::watch; -use tokio_tungstenite::tungstenite::{protocol::CloseFrame, Message}; +use tokio_tungstenite::tungstenite::protocol::CloseFrame; +use tokio_tungstenite::tungstenite::Message; use tracing::{error, trace}; use watch::Receiver; diff --git a/swap/src/bin/asb.rs b/swap/src/bin/asb.rs index 2e50c81a..8ffd3a93 100644 --- a/swap/src/bin/asb.rs +++ b/swap/src/bin/asb.rs @@ -13,30 +13,25 @@ #![allow(non_snake_case)] use anyhow::{Context, Result}; -use bdk::{descriptor::Segwitv0, keys::DerivableKey}; +use bdk::descriptor::Segwitv0; +use bdk::keys::DerivableKey; use prettytable::{row, Table}; -use std::{path::Path, sync::Arc}; +use std::path::Path; +use std::sync::Arc; use structopt::StructOpt; -use swap::{ - asb::{ - command::{Arguments, Command}, - config::{ - initial_setup, query_user_for_initial_testnet_config, read_config, Config, - ConfigNotInitialized, - }, - kraken, - }, - bitcoin, - database::Database, - execution_params, - execution_params::GetExecutionParams, - fs::default_config_path, - monero, - monero::Amount, - protocol::alice::EventLoop, - seed::Seed, - trace::init_tracing, +use swap::asb::command::{Arguments, Command}; +use swap::asb::config::{ + initial_setup, query_user_for_initial_testnet_config, read_config, Config, ConfigNotInitialized, }; +use swap::asb::kraken; +use swap::database::Database; +use swap::execution_params::GetExecutionParams; +use swap::fs::default_config_path; +use swap::monero::Amount; +use swap::protocol::alice::EventLoop; +use swap::seed::Seed; +use swap::trace::init_tracing; +use swap::{bitcoin, execution_params, monero}; use tracing::{info, warn}; use tracing_subscriber::filter::LevelFilter; diff --git a/swap/src/bin/swap_cli.rs b/swap/src/bin/swap_cli.rs index 01f23f05..b5e6be94 100644 --- a/swap/src/bin/swap_cli.rs +++ b/swap/src/bin/swap_cli.rs @@ -15,25 +15,20 @@ use anyhow::{bail, Context, Result}; use prettytable::{row, Table}; use reqwest::Url; -use std::{path::Path, sync::Arc, time::Duration}; +use std::path::Path; +use std::sync::Arc; +use std::time::Duration; use structopt::StructOpt; -use swap::{ - bitcoin, - bitcoin::{Amount, TxLock}, - cli::{ - command::{Arguments, Command}, - config::{read_config, Config}, - }, - database::Database, - execution_params, - execution_params::GetExecutionParams, - monero, - protocol::{ - bob, - bob::{cancel::CancelError, Builder, EventLoop}, - }, - seed::Seed, -}; +use swap::bitcoin::{Amount, TxLock}; +use swap::cli::command::{Arguments, Command}; +use swap::cli::config::{read_config, Config}; +use swap::database::Database; +use swap::execution_params::GetExecutionParams; +use swap::protocol::bob; +use swap::protocol::bob::cancel::CancelError; +use swap::protocol::bob::{Builder, EventLoop}; +use swap::seed::Seed; +use swap::{bitcoin, execution_params, monero}; use tracing::{debug, error, info, warn, Level}; use tracing_subscriber::FmtSubscriber; use uuid::Uuid; diff --git a/swap/src/bitcoin.rs b/swap/src/bitcoin.rs index 1e6c5494..386c0e57 100644 --- a/swap/src/bitcoin.rs +++ b/swap/src/bitcoin.rs @@ -7,30 +7,29 @@ mod redeem; mod refund; mod timelocks; -pub use crate::bitcoin::{ - cancel::{CancelTimelock, PunishTimelock, TxCancel}, - lock::TxLock, - punish::TxPunish, - redeem::TxRedeem, - refund::TxRefund, - timelocks::{BlockHeight, ExpiredTimelocks}, -}; -pub use ::bitcoin::{util::amount::Amount, Address, Network, Transaction, Txid}; -pub use ecdsa_fun::{adaptor::EncryptedSignature, fun::Scalar, Signature}; +pub use crate::bitcoin::cancel::{CancelTimelock, PunishTimelock, TxCancel}; +pub use crate::bitcoin::lock::TxLock; +pub use crate::bitcoin::punish::TxPunish; +pub use crate::bitcoin::redeem::TxRedeem; +pub use crate::bitcoin::refund::TxRefund; +pub use crate::bitcoin::timelocks::{BlockHeight, ExpiredTimelocks}; +pub use ::bitcoin::util::amount::Amount; +pub use ::bitcoin::{Address, Network, Transaction, Txid}; +pub use ecdsa_fun::adaptor::EncryptedSignature; +pub use ecdsa_fun::fun::Scalar; +pub use ecdsa_fun::Signature; pub use wallet::Wallet; -use ::bitcoin::{ - hashes::{hex::ToHex, Hash}, - secp256k1, SigHash, -}; +use ::bitcoin::hashes::hex::ToHex; +use ::bitcoin::hashes::Hash; +use ::bitcoin::{secp256k1, SigHash}; use anyhow::{anyhow, bail, Result}; -use ecdsa_fun::{ - adaptor::{Adaptor, HashTranscript}, - fun::Point, - nonce::Deterministic, - ECDSA, -}; -use miniscript::{descriptor::Wsh, Descriptor, Segwitv0}; +use ecdsa_fun::adaptor::{Adaptor, HashTranscript}; +use ecdsa_fun::fun::Point; +use ecdsa_fun::nonce::Deterministic; +use ecdsa_fun::ECDSA; +use miniscript::descriptor::Wsh; +use miniscript::{Descriptor, Segwitv0}; use rand::{CryptoRng, RngCore}; use serde::{Deserialize, Serialize}; use sha2::Sha256; diff --git a/swap/src/bitcoin/cancel.rs b/swap/src/bitcoin/cancel.rs index d2187d45..d94c91dd 100644 --- a/swap/src/bitcoin/cancel.rs +++ b/swap/src/bitcoin/cancel.rs @@ -2,12 +2,14 @@ use crate::bitcoin::{ build_shared_output_descriptor, Address, Amount, BlockHeight, PublicKey, Transaction, TxLock, TX_FEE, }; -use ::bitcoin::{util::bip143::SigHashCache, OutPoint, SigHash, SigHashType, TxIn, TxOut, Txid}; +use ::bitcoin::util::bip143::SigHashCache; +use ::bitcoin::{OutPoint, SigHash, SigHashType, TxIn, TxOut, Txid}; use anyhow::Result; use ecdsa_fun::Signature; use miniscript::{Descriptor, DescriptorTrait}; use serde::{Deserialize, Serialize}; -use std::{collections::HashMap, ops::Add}; +use std::collections::HashMap; +use std::ops::Add; /// Represent a timelock, expressed in relative block height as defined in /// [BIP68](https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki). diff --git a/swap/src/bitcoin/lock.rs b/swap/src/bitcoin/lock.rs index 486c23ca..f9ef3814 100644 --- a/swap/src/bitcoin/lock.rs +++ b/swap/src/bitcoin/lock.rs @@ -1,7 +1,8 @@ use crate::bitcoin::{ build_shared_output_descriptor, Address, Amount, PublicKey, Transaction, Wallet, TX_FEE, }; -use ::bitcoin::{util::psbt::PartiallySignedTransaction, OutPoint, TxIn, TxOut, Txid}; +use ::bitcoin::util::psbt::PartiallySignedTransaction; +use ::bitcoin::{OutPoint, TxIn, TxOut, Txid}; use anyhow::Result; use ecdsa_fun::fun::Point; use miniscript::{Descriptor, DescriptorTrait}; diff --git a/swap/src/bitcoin/punish.rs b/swap/src/bitcoin/punish.rs index 08c0f0b9..a8d1c7d6 100644 --- a/swap/src/bitcoin/punish.rs +++ b/swap/src/bitcoin/punish.rs @@ -1,5 +1,6 @@ use crate::bitcoin::{Address, PublicKey, PunishTimelock, Transaction, TxCancel}; -use ::bitcoin::{util::bip143::SigHashCache, SigHash, SigHashType}; +use ::bitcoin::util::bip143::SigHashCache; +use ::bitcoin::{SigHash, SigHashType}; use anyhow::Result; use ecdsa_fun::Signature; use miniscript::{Descriptor, DescriptorTrait}; diff --git a/swap/src/bitcoin/redeem.rs b/swap/src/bitcoin/redeem.rs index 081b0094..5171db16 100644 --- a/swap/src/bitcoin/redeem.rs +++ b/swap/src/bitcoin/redeem.rs @@ -2,7 +2,8 @@ use crate::bitcoin::{ verify_sig, Address, EmptyWitnessStack, NoInputs, NotThreeWitnesses, PublicKey, TooManyInputs, Transaction, TxLock, }; -use ::bitcoin::{util::bip143::SigHashCache, SigHash, SigHashType, Txid}; +use ::bitcoin::util::bip143::SigHashCache; +use ::bitcoin::{SigHash, SigHashType, Txid}; use anyhow::{bail, Context, Result}; use ecdsa_fun::Signature; use miniscript::{Descriptor, DescriptorTrait}; diff --git a/swap/src/bitcoin/refund.rs b/swap/src/bitcoin/refund.rs index e5124e7f..10643614 100644 --- a/swap/src/bitcoin/refund.rs +++ b/swap/src/bitcoin/refund.rs @@ -2,7 +2,8 @@ use crate::bitcoin::{ verify_sig, Address, EmptyWitnessStack, NoInputs, NotThreeWitnesses, PublicKey, TooManyInputs, Transaction, TxCancel, }; -use ::bitcoin::{util::bip143::SigHashCache, SigHash, SigHashType, Txid}; +use ::bitcoin::util::bip143::SigHashCache; +use ::bitcoin::{SigHash, SigHashType, Txid}; use anyhow::{bail, Context, Result}; use ecdsa_fun::Signature; use miniscript::{Descriptor, DescriptorTrait}; diff --git a/swap/src/bitcoin/wallet.rs b/swap/src/bitcoin/wallet.rs index 4fe3d345..8fecd22f 100644 --- a/swap/src/bitcoin/wallet.rs +++ b/swap/src/bitcoin/wallet.rs @@ -1,22 +1,24 @@ -use crate::{ - bitcoin::{timelocks::BlockHeight, Address, Amount, Transaction}, - execution_params::ExecutionParams, -}; -use ::bitcoin::{util::psbt::PartiallySignedTransaction, Txid}; +use crate::bitcoin::timelocks::BlockHeight; +use crate::bitcoin::{Address, Amount, Transaction}; +use crate::execution_params::ExecutionParams; +use ::bitcoin::util::psbt::PartiallySignedTransaction; +use ::bitcoin::Txid; use anyhow::{anyhow, bail, Context, Result}; -use backoff::{backoff::Constant as ConstantBackoff, future::retry}; -use bdk::{ - blockchain::{noop_progress, Blockchain, ElectrumBlockchain}, - descriptor::Segwitv0, - electrum_client::{self, Client, ElectrumApi}, - keys::DerivableKey, - FeeRate, KeychainKind, -}; +use backoff::backoff::Constant as ConstantBackoff; +use backoff::future::retry; +use bdk::blockchain::{noop_progress, Blockchain, ElectrumBlockchain}; +use bdk::descriptor::Segwitv0; +use bdk::electrum_client::{self, Client, ElectrumApi}; +use bdk::keys::DerivableKey; +use bdk::{FeeRate, KeychainKind}; use bitcoin::Script; use reqwest::{Method, Url}; use serde::{Deserialize, Serialize}; -use std::{path::Path, sync::Arc, time::Duration}; -use tokio::{sync::Mutex, time::interval}; +use std::path::Path; +use std::sync::Arc; +use std::time::Duration; +use tokio::sync::Mutex; +use tokio::time::interval; const SLED_TREE_NAME: &str = "default_tree"; @@ -309,13 +311,9 @@ fn blocks_tip_height_url(base_url: &Url) -> Result { #[cfg(test)] mod tests { - use crate::{ - bitcoin::{ - wallet::{blocks_tip_height_url, tx_status_url}, - Txid, - }, - cli::config::DEFAULT_ELECTRUM_HTTP_URL, - }; + use crate::bitcoin::wallet::{blocks_tip_height_url, tx_status_url}; + use crate::bitcoin::Txid; + use crate::cli::config::DEFAULT_ELECTRUM_HTTP_URL; use reqwest::Url; #[test] diff --git a/swap/src/cli/command.rs b/swap/src/cli/command.rs index 30a675e0..e478680f 100644 --- a/swap/src/cli/command.rs +++ b/swap/src/cli/command.rs @@ -1,6 +1,8 @@ use anyhow::{Context, Result}; -use libp2p::{core::Multiaddr, PeerId}; -use std::{path::PathBuf, str::FromStr}; +use libp2p::core::Multiaddr; +use libp2p::PeerId; +use std::path::PathBuf; +use std::str::FromStr; use uuid::Uuid; pub const DEFAULT_ALICE_MULTIADDR: &str = "/dns4/xmr-btc-asb.coblox.tech/tcp/9876"; @@ -85,7 +87,8 @@ fn parse_monero_address(s: &str) -> Result { #[cfg(test)] mod tests { use crate::cli::command::{DEFAULT_ALICE_MULTIADDR, DEFAULT_ALICE_PEER_ID}; - use libp2p::{core::Multiaddr, PeerId}; + use libp2p::core::Multiaddr; + use libp2p::PeerId; #[test] fn parse_default_alice_peer_id_success() { diff --git a/swap/src/cli/config.rs b/swap/src/cli/config.rs index ce963a25..4872ecf5 100644 --- a/swap/src/cli/config.rs +++ b/swap/src/cli/config.rs @@ -2,10 +2,8 @@ use crate::fs::default_data_dir; use anyhow::{Context, Result}; use config::ConfigError; use serde::{Deserialize, Serialize}; -use std::{ - ffi::OsStr, - path::{Path, PathBuf}, -}; +use std::ffi::OsStr; +use std::path::{Path, PathBuf}; use tracing::debug; use url::Url; @@ -84,7 +82,8 @@ pub fn read_config(config_path: PathBuf) -> Result Result<()> { diff --git a/swap/src/database.rs b/swap/src/database.rs index 6241b8d3..b591d2c1 100644 --- a/swap/src/database.rs +++ b/swap/src/database.rs @@ -2,8 +2,10 @@ pub use alice::Alice; pub use bob::Bob; use anyhow::{anyhow, bail, Context, Result}; -use serde::{de::DeserializeOwned, Deserialize, Serialize}; -use std::{fmt::Display, path::Path}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use std::fmt::Display; +use std::path::Path; use uuid::Uuid; mod alice; @@ -123,10 +125,8 @@ where #[cfg(test)] mod tests { use super::*; - use crate::database::{ - alice::{Alice, AliceEndState}, - bob::{Bob, BobEndState}, - }; + use crate::database::alice::{Alice, AliceEndState}; + use crate::database::bob::{Bob, BobEndState}; #[tokio::test] async fn can_write_and_read_to_multiple_keys() { diff --git a/swap/src/database/alice.rs b/swap/src/database/alice.rs index 8a5ba68f..6c1a19ab 100644 --- a/swap/src/database/alice.rs +++ b/swap/src/database/alice.rs @@ -1,9 +1,8 @@ -use crate::{ - bitcoin::{EncryptedSignature, TxCancel, TxRefund}, - monero, - monero::monero_private_key, - protocol::{alice, alice::AliceState}, -}; +use crate::bitcoin::{EncryptedSignature, TxCancel, TxRefund}; +use crate::monero; +use crate::monero::monero_private_key; +use crate::protocol::alice; +use crate::protocol::alice::AliceState; use ::bitcoin::hashes::core::fmt::Display; use libp2p::PeerId; use monero_rpc::wallet::BlockHeight; diff --git a/swap/src/database/bob.rs b/swap/src/database/bob.rs index 4ee796e4..943957dd 100644 --- a/swap/src/database/bob.rs +++ b/swap/src/database/bob.rs @@ -1,7 +1,6 @@ -use crate::{ - monero::TransferProof, - protocol::{bob, bob::BobState}, -}; +use crate::monero::TransferProof; +use crate::protocol::bob; +use crate::protocol::bob::BobState; use ::bitcoin::hashes::core::fmt::Display; use monero_rpc::wallet::BlockHeight; use serde::{Deserialize, Serialize}; diff --git a/swap/src/monero.rs b/swap/src/monero.rs index 613e2095..45229ea7 100644 --- a/swap/src/monero.rs +++ b/swap/src/monero.rs @@ -10,17 +10,13 @@ use crate::bitcoin; use ::bitcoin::hashes::core::fmt::Formatter; use anyhow::Result; use rand::{CryptoRng, RngCore}; -use rust_decimal::{ - prelude::{FromPrimitive, ToPrimitive}, - Decimal, -}; +use rust_decimal::prelude::{FromPrimitive, ToPrimitive}; +use rust_decimal::Decimal; use serde::{Deserialize, Serialize}; -use std::{ - convert::TryFrom, - fmt::Display, - ops::{Add, Mul, Sub}, - str::FromStr, -}; +use std::convert::TryFrom; +use std::fmt::Display; +use std::ops::{Add, Mul, Sub}; +use std::str::FromStr; pub const PICONERO_OFFSET: u64 = 1_000_000_000_000; @@ -198,12 +194,13 @@ pub struct BalanceTooLow { pub struct OverflowError(pub String); pub mod monero_private_key { - use monero::{ - consensus::{Decodable, Encodable}, - PrivateKey, - }; - use serde::{de, de::Visitor, ser::Error, Deserializer, Serializer}; - use std::{fmt, io::Cursor}; + use monero::consensus::{Decodable, Encodable}; + use monero::PrivateKey; + use serde::de::Visitor; + use serde::ser::Error; + use serde::{de, Deserializer, Serializer}; + use std::fmt; + use std::io::Cursor; struct BytesVisitor; diff --git a/swap/src/monero/wallet.rs b/swap/src/monero/wallet.rs index 04fe14dd..7185a061 100644 --- a/swap/src/monero/wallet.rs +++ b/swap/src/monero/wallet.rs @@ -3,13 +3,14 @@ use crate::monero::{ }; use ::monero::{Address, Network, PrivateKey, PublicKey}; use anyhow::{Context, Result}; -use backoff::{backoff::Constant as ConstantBackoff, future::retry}; +use backoff::backoff::Constant as ConstantBackoff; +use backoff::future::retry; use bitcoin::hashes::core::sync::atomic::AtomicU32; -use monero_rpc::{ - wallet, - wallet::{BlockHeight, Refreshed}, -}; -use std::{str::FromStr, sync::atomic::Ordering, time::Duration}; +use monero_rpc::wallet; +use monero_rpc::wallet::{BlockHeight, Refreshed}; +use std::str::FromStr; +use std::sync::atomic::Ordering; +use std::time::Duration; use tokio::sync::Mutex; use tracing::{debug, info}; use url::Url; diff --git a/swap/src/monero/wallet_rpc.rs b/swap/src/monero/wallet_rpc.rs index bb28b3af..925b9d95 100644 --- a/swap/src/monero/wallet_rpc.rs +++ b/swap/src/monero/wallet_rpc.rs @@ -2,21 +2,16 @@ use ::monero::Network; use anyhow::{Context, Result}; use big_bytes::BigByte; use futures::{StreamExt, TryStreamExt}; -use reqwest::{header::CONTENT_LENGTH, Url}; -use std::{ - io::ErrorKind, - path::{Path, PathBuf}, - process::Stdio, -}; -use tokio::{ - fs::{remove_file, OpenOptions}, - io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, - process::{Child, Command}, -}; -use tokio_util::{ - codec::{BytesCodec, FramedRead}, - io::StreamReader, -}; +use reqwest::header::CONTENT_LENGTH; +use reqwest::Url; +use std::io::ErrorKind; +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use tokio::fs::{remove_file, OpenOptions}; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::process::{Child, Command}; +use tokio_util::codec::{BytesCodec, FramedRead}; +use tokio_util::io::StreamReader; #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))] compile_error!("unsupported operating system"); diff --git a/swap/src/network/peer_tracker.rs b/swap/src/network/peer_tracker.rs index b6b7fda6..26d6e172 100644 --- a/swap/src/network/peer_tracker.rs +++ b/swap/src/network/peer_tracker.rs @@ -1,16 +1,11 @@ use futures::task::Context; -use libp2p::{ - core::{connection::ConnectionId, ConnectedPoint}, - swarm::{ - protocols_handler::DummyProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, - PollParameters, - }, - Multiaddr, PeerId, -}; -use std::{ - collections::{HashMap, VecDeque}, - task::Poll, -}; +use libp2p::core::connection::ConnectionId; +use libp2p::core::ConnectedPoint; +use libp2p::swarm::protocols_handler::DummyProtocolsHandler; +use libp2p::swarm::{NetworkBehaviour, NetworkBehaviourAction, PollParameters}; +use libp2p::{Multiaddr, PeerId}; +use std::collections::{HashMap, VecDeque}; +use std::task::Poll; #[derive(Debug, Copy, Clone)] pub enum OutEvent { diff --git a/swap/src/network/request_response.rs b/swap/src/network/request_response.rs index cfa40c26..5e39e347 100644 --- a/swap/src/network/request_response.rs +++ b/swap/src/network/request_response.rs @@ -1,11 +1,13 @@ use async_trait::async_trait; use futures::prelude::*; -use libp2p::{ - core::{upgrade, upgrade::ReadOneError}, - request_response::{ProtocolName, RequestResponseCodec}, -}; -use serde::{de::DeserializeOwned, Serialize}; -use std::{fmt::Debug, io, marker::PhantomData}; +use libp2p::core::upgrade; +use libp2p::core::upgrade::ReadOneError; +use libp2p::request_response::{ProtocolName, RequestResponseCodec}; +use serde::de::DeserializeOwned; +use serde::Serialize; +use std::fmt::Debug; +use std::io; +use std::marker::PhantomData; /// Time to wait for a response back once we send a request. pub const TIMEOUT: u64 = 3600; // One hour. diff --git a/swap/src/network/spot_price.rs b/swap/src/network/spot_price.rs index 5f4f34ff..f02b0487 100644 --- a/swap/src/network/spot_price.rs +++ b/swap/src/network/spot_price.rs @@ -1,9 +1,8 @@ -use crate::{bitcoin, monero, network::request_response::CborCodec}; -use libp2p::{ - core::ProtocolName, - request_response::{ - ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent, - }, +use crate::network::request_response::CborCodec; +use crate::{bitcoin, monero}; +use libp2p::core::ProtocolName; +use libp2p::request_response::{ + ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent, }; use serde::{Deserialize, Serialize}; diff --git a/swap/src/network/transport.rs b/swap/src/network/transport.rs index 7217323e..6c89bd37 100644 --- a/swap/src/network/transport.rs +++ b/swap/src/network/transport.rs @@ -1,17 +1,12 @@ use anyhow::Result; -use libp2p::{ - core::{ - identity, - muxing::StreamMuxerBox, - transport::Boxed, - upgrade::{SelectUpgrade, Version}, - Transport, - }, - dns::DnsConfig, - mplex::MplexConfig, - noise::{self, NoiseConfig, X25519Spec}, - yamux, PeerId, -}; +use libp2p::core::muxing::StreamMuxerBox; +use libp2p::core::transport::Boxed; +use libp2p::core::upgrade::{SelectUpgrade, Version}; +use libp2p::core::{identity, Transport}; +use libp2p::dns::DnsConfig; +use libp2p::mplex::MplexConfig; +use libp2p::noise::{self, NoiseConfig, X25519Spec}; +use libp2p::{yamux, PeerId}; /// Builds a libp2p transport with the following features: /// - TcpConnection diff --git a/swap/src/protocol.rs b/swap/src/protocol.rs index 23d3ac66..faab1610 100644 --- a/swap/src/protocol.rs +++ b/swap/src/protocol.rs @@ -1,7 +1,8 @@ use conquer_once::Lazy; use ecdsa_fun::fun::marker::Mark; use sha2::Sha256; -use sigma_fun::{ext::dl_secp256k1_ed25519_eq::CrossCurveDLEQ, HashTranscript}; +use sigma_fun::ext::dl_secp256k1_ed25519_eq::CrossCurveDLEQ; +use sigma_fun::HashTranscript; pub mod alice; pub mod bob; diff --git a/swap/src/protocol/alice.rs b/swap/src/protocol/alice.rs index 8cd9c51e..f49b208e 100644 --- a/swap/src/protocol/alice.rs +++ b/swap/src/protocol/alice.rs @@ -1,17 +1,17 @@ //! Run an XMR/BTC swap in the role of Alice. //! Alice holds XMR and wishes receive BTC. -use crate::{bitcoin, database::Database, execution_params::ExecutionParams, monero}; +use crate::database::Database; +use crate::execution_params::ExecutionParams; +use crate::{bitcoin, monero}; use std::sync::Arc; use uuid::Uuid; -pub use self::{ - behaviour::{Behaviour, OutEvent}, - event_loop::{EventLoop, EventLoopHandle}, - execution_setup::Message1, - state::*, - swap::{run, run_until}, - transfer_proof::TransferProof, -}; +pub use self::behaviour::{Behaviour, OutEvent}; +pub use self::event_loop::{EventLoop, EventLoopHandle}; +pub use self::execution_setup::Message1; +pub use self::state::*; +pub use self::swap::{run, run_until}; +pub use self::transfer_proof::TransferProof; pub use execution_setup::Message3; mod behaviour; diff --git a/swap/src/protocol/alice/behaviour.rs b/swap/src/protocol/alice/behaviour.rs index 19cbef94..643f2d92 100644 --- a/swap/src/protocol/alice/behaviour.rs +++ b/swap/src/protocol/alice/behaviour.rs @@ -1,25 +1,15 @@ -use crate::{ - bitcoin, - execution_params::ExecutionParams, - monero, - network::{ - peer_tracker, - peer_tracker::PeerTracker, - spot_price, - spot_price::{SpotPriceRequest, SpotPriceResponse}, - }, - protocol::{ - alice::{ - encrypted_signature, execution_setup, transfer_proof, State0, State3, TransferProof, - }, - bob::EncryptedSignature, - }, +use crate::execution_params::ExecutionParams; +use crate::network::peer_tracker::PeerTracker; +use crate::network::spot_price::{SpotPriceRequest, SpotPriceResponse}; +use crate::network::{peer_tracker, spot_price}; +use crate::protocol::alice::{ + encrypted_signature, execution_setup, transfer_proof, State0, State3, TransferProof, }; +use crate::protocol::bob::EncryptedSignature; +use crate::{bitcoin, monero}; use anyhow::{anyhow, Error, Result}; -use libp2p::{ - request_response::{RequestResponseMessage, ResponseChannel}, - NetworkBehaviour, PeerId, -}; +use libp2p::request_response::{RequestResponseMessage, ResponseChannel}; +use libp2p::{NetworkBehaviour, PeerId}; use rand::{CryptoRng, RngCore}; use tracing::debug; diff --git a/swap/src/protocol/alice/encrypted_signature.rs b/swap/src/protocol/alice/encrypted_signature.rs index 06fc1bb7..dac19113 100644 --- a/swap/src/protocol/alice/encrypted_signature.rs +++ b/swap/src/protocol/alice/encrypted_signature.rs @@ -1,15 +1,11 @@ -use crate::{ - network::request_response::{CborCodec, EncryptedSignatureProtocol, TIMEOUT}, - protocol::bob::EncryptedSignature, -}; +use crate::network::request_response::{CborCodec, EncryptedSignatureProtocol, TIMEOUT}; +use crate::protocol::bob::EncryptedSignature; use anyhow::{anyhow, Error, Result}; -use libp2p::{ - request_response::{ - ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent, - RequestResponseMessage, ResponseChannel, - }, - NetworkBehaviour, +use libp2p::request_response::{ + ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent, + RequestResponseMessage, ResponseChannel, }; +use libp2p::NetworkBehaviour; use std::time::Duration; use tracing::debug; diff --git a/swap/src/protocol/alice/event_loop.rs b/swap/src/protocol/alice/event_loop.rs index 984a8255..2e91dee8 100644 --- a/swap/src/protocol/alice/event_loop.rs +++ b/swap/src/protocol/alice/event_loop.rs @@ -1,24 +1,23 @@ -use crate::{ - asb::LatestRate, - bitcoin, - database::Database, - execution_params::ExecutionParams, - monero, - monero::BalanceTooLow, - network::{spot_price::SpotPriceResponse, transport, TokioExecutor}, - protocol::{ - alice, - alice::{AliceState, Behaviour, OutEvent, State3, Swap, TransferProof}, - bob::EncryptedSignature, - }, - seed::Seed, -}; +use crate::asb::LatestRate; +use crate::database::Database; +use crate::execution_params::ExecutionParams; +use crate::monero::BalanceTooLow; +use crate::network::spot_price::SpotPriceResponse; +use crate::network::{transport, TokioExecutor}; +use crate::protocol::alice; +use crate::protocol::alice::{AliceState, Behaviour, OutEvent, State3, Swap, TransferProof}; +use crate::protocol::bob::EncryptedSignature; +use crate::seed::Seed; +use crate::{bitcoin, monero}; use anyhow::{bail, Context, Result}; use futures::future::RemoteHandle; -use libp2p::{core::Multiaddr, futures::FutureExt, PeerId, Swarm}; +use libp2p::core::Multiaddr; +use libp2p::futures::FutureExt; +use libp2p::{PeerId, Swarm}; use rand::rngs::OsRng; use std::sync::Arc; -use tokio::sync::{broadcast, mpsc, mpsc::error::SendError}; +use tokio::sync::mpsc::error::SendError; +use tokio::sync::{broadcast, mpsc}; use tracing::{debug, error, trace}; use uuid::Uuid; diff --git a/swap/src/protocol/alice/execution_setup.rs b/swap/src/protocol/alice/execution_setup.rs index eb9505d9..1cc7fa76 100644 --- a/swap/src/protocol/alice/execution_setup.rs +++ b/swap/src/protocol/alice/execution_setup.rs @@ -1,13 +1,8 @@ -use crate::{ - bitcoin, - bitcoin::{EncryptedSignature, Signature}, - monero, - network::request_response::BUF_SIZE, - protocol::{ - alice::{State0, State3}, - bob::{Message0, Message2, Message4}, - }, -}; +use crate::bitcoin::{EncryptedSignature, Signature}; +use crate::network::request_response::BUF_SIZE; +use crate::protocol::alice::{State0, State3}; +use crate::protocol::bob::{Message0, Message2, Message4}; +use crate::{bitcoin, monero}; use anyhow::{Context, Error}; use libp2p::PeerId; use libp2p_async_await::BehaviourOutEvent; diff --git a/swap/src/protocol/alice/state.rs b/swap/src/protocol/alice/state.rs index 1fda6a29..e4c23bfd 100644 --- a/swap/src/protocol/alice/state.rs +++ b/swap/src/protocol/alice/state.rs @@ -1,17 +1,12 @@ -use crate::{ - bitcoin, - bitcoin::{ - current_epoch, wait_for_cancel_timelock_to_expire, CancelTimelock, ExpiredTimelocks, - PunishTimelock, TxCancel, TxRefund, - }, - execution_params::ExecutionParams, - monero, - protocol::{ - alice::{Message1, Message3}, - bob::{Message0, Message2, Message4}, - CROSS_CURVE_PROOF_SYSTEM, - }, +use crate::bitcoin::{ + current_epoch, wait_for_cancel_timelock_to_expire, CancelTimelock, ExpiredTimelocks, + PunishTimelock, TxCancel, TxRefund, }; +use crate::execution_params::ExecutionParams; +use crate::protocol::alice::{Message1, Message3}; +use crate::protocol::bob::{Message0, Message2, Message4}; +use crate::protocol::CROSS_CURVE_PROOF_SYSTEM; +use crate::{bitcoin, monero}; use anyhow::{anyhow, bail, Context, Result}; use libp2p::PeerId; use monero_rpc::wallet::BlockHeight; diff --git a/swap/src/protocol/alice/steps.rs b/swap/src/protocol/alice/steps.rs index aab80944..3e8558b8 100644 --- a/swap/src/protocol/alice/steps.rs +++ b/swap/src/protocol/alice/steps.rs @@ -1,25 +1,17 @@ -use crate::{ - bitcoin, - bitcoin::{ - poll_until_block_height_is_gte, BlockHeight, CancelTimelock, EncryptedSignature, - PunishTimelock, TxCancel, TxLock, TxRefund, - }, - execution_params::ExecutionParams, - monero, - protocol::{ - alice, - alice::{event_loop::EventLoopHandle, TransferProof}, - }, +use crate::bitcoin::{ + poll_until_block_height_is_gte, BlockHeight, CancelTimelock, EncryptedSignature, + PunishTimelock, TxCancel, TxLock, TxRefund, }; +use crate::execution_params::ExecutionParams; +use crate::protocol::alice; +use crate::protocol::alice::event_loop::EventLoopHandle; +use crate::protocol::alice::TransferProof; +use crate::{bitcoin, monero}; use anyhow::{Context, Result}; -use ecdsa_fun::{ - adaptor::{Adaptor, HashTranscript}, - nonce::Deterministic, -}; -use futures::{ - future::{select, Either}, - pin_mut, -}; +use ecdsa_fun::adaptor::{Adaptor, HashTranscript}; +use ecdsa_fun::nonce::Deterministic; +use futures::future::{select, Either}; +use futures::pin_mut; use libp2p::PeerId; use sha2::Sha256; use tokio::time::timeout; diff --git a/swap/src/protocol/alice/swap.rs b/swap/src/protocol/alice/swap.rs index c9bd7341..28f3d751 100644 --- a/swap/src/protocol/alice/swap.rs +++ b/swap/src/protocol/alice/swap.rs @@ -1,33 +1,22 @@ //! Run an XMR/BTC swap in the role of Alice. //! Alice holds XMR and wishes receive BTC. -use crate::{ - bitcoin, - bitcoin::ExpiredTimelocks, - database, - database::Database, - execution_params::ExecutionParams, - monero, - monero_ext::ScalarExt, - protocol::{ - alice, - alice::{ - event_loop::EventLoopHandle, - steps::{ - build_bitcoin_punish_transaction, build_bitcoin_redeem_transaction, - extract_monero_private_key, lock_xmr, publish_cancel_transaction, - wait_for_bitcoin_encrypted_signature, wait_for_bitcoin_refund, - wait_for_locked_bitcoin, - }, - AliceState, - }, - }, +use crate::bitcoin::ExpiredTimelocks; +use crate::database::Database; +use crate::execution_params::ExecutionParams; +use crate::monero_ext::ScalarExt; +use crate::protocol::alice; +use crate::protocol::alice::event_loop::EventLoopHandle; +use crate::protocol::alice::steps::{ + build_bitcoin_punish_transaction, build_bitcoin_redeem_transaction, extract_monero_private_key, + lock_xmr, publish_cancel_transaction, wait_for_bitcoin_encrypted_signature, + wait_for_bitcoin_refund, wait_for_locked_bitcoin, }; +use crate::protocol::alice::AliceState; +use crate::{bitcoin, database, monero}; use anyhow::{bail, Result}; use async_recursion::async_recursion; -use futures::{ - future::{select, Either}, - pin_mut, -}; +use futures::future::{select, Either}; +use futures::pin_mut; use rand::{CryptoRng, RngCore}; use std::sync::Arc; use tracing::{error, info}; diff --git a/swap/src/protocol/alice/transfer_proof.rs b/swap/src/protocol/alice/transfer_proof.rs index d7c06cdc..9bf8ab50 100644 --- a/swap/src/protocol/alice/transfer_proof.rs +++ b/swap/src/protocol/alice/transfer_proof.rs @@ -1,15 +1,11 @@ -use crate::{ - monero, - network::request_response::{CborCodec, TransferProofProtocol, TIMEOUT}, -}; +use crate::monero; +use crate::network::request_response::{CborCodec, TransferProofProtocol, TIMEOUT}; use anyhow::{anyhow, Error}; -use libp2p::{ - request_response::{ - ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent, - RequestResponseMessage, - }, - NetworkBehaviour, PeerId, +use libp2p::request_response::{ + ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent, + RequestResponseMessage, }; +use libp2p::{NetworkBehaviour, PeerId}; use serde::{Deserialize, Serialize}; use std::time::Duration; diff --git a/swap/src/protocol/bob.rs b/swap/src/protocol/bob.rs index 79e9e06f..92a45f17 100644 --- a/swap/src/protocol/bob.rs +++ b/swap/src/protocol/bob.rs @@ -1,34 +1,26 @@ -use crate::{ - bitcoin, - database::Database, - execution_params::ExecutionParams, - monero, - network::{ - peer_tracker::{self, PeerTracker}, - spot_price, - spot_price::{SpotPriceRequest, SpotPriceResponse}, - }, - protocol::{alice::TransferProof, bob}, -}; +use crate::database::Database; +use crate::execution_params::ExecutionParams; +use crate::network::peer_tracker::{self, PeerTracker}; +use crate::network::spot_price; +use crate::network::spot_price::{SpotPriceRequest, SpotPriceResponse}; +use crate::protocol::alice::TransferProof; +use crate::protocol::bob; +use crate::{bitcoin, monero}; use anyhow::{anyhow, Error, Result}; -use libp2p::{ - core::Multiaddr, - request_response::{RequestResponseMessage, ResponseChannel}, - NetworkBehaviour, PeerId, -}; +use libp2p::core::Multiaddr; +use libp2p::request_response::{RequestResponseMessage, ResponseChannel}; +use libp2p::{NetworkBehaviour, PeerId}; use std::sync::Arc; use tracing::debug; use uuid::Uuid; -pub use self::{ - cancel::cancel, - encrypted_signature::EncryptedSignature, - event_loop::{EventLoop, EventLoopHandle}, - execution_setup::{Message0, Message2, Message4}, - refund::refund, - state::*, - swap::{run, run_until}, -}; +pub use self::cancel::cancel; +pub use self::encrypted_signature::EncryptedSignature; +pub use self::event_loop::{EventLoop, EventLoopHandle}; +pub use self::execution_setup::{Message0, Message2, Message4}; +pub use self::refund::refund; +pub use self::state::*; +pub use self::swap::{run, run_until}; pub mod cancel; mod encrypted_signature; diff --git a/swap/src/protocol/bob/cancel.rs b/swap/src/protocol/bob/cancel.rs index dab0fc79..c3c70fd1 100644 --- a/swap/src/protocol/bob/cancel.rs +++ b/swap/src/protocol/bob/cancel.rs @@ -1,8 +1,6 @@ -use crate::{ - bitcoin::{ExpiredTimelocks, Txid, Wallet}, - database::{Database, Swap}, - protocol::bob::BobState, -}; +use crate::bitcoin::{ExpiredTimelocks, Txid, Wallet}; +use crate::database::{Database, Swap}; +use crate::protocol::bob::BobState; use anyhow::{bail, Result}; use std::sync::Arc; use uuid::Uuid; diff --git a/swap/src/protocol/bob/encrypted_signature.rs b/swap/src/protocol/bob/encrypted_signature.rs index 96a253a2..ed121975 100644 --- a/swap/src/protocol/bob/encrypted_signature.rs +++ b/swap/src/protocol/bob/encrypted_signature.rs @@ -1,12 +1,10 @@ use crate::network::request_response::{CborCodec, EncryptedSignatureProtocol, TIMEOUT}; use anyhow::{anyhow, Error}; -use libp2p::{ - request_response::{ - ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent, - RequestResponseMessage, - }, - NetworkBehaviour, PeerId, +use libp2p::request_response::{ + ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent, + RequestResponseMessage, }; +use libp2p::{NetworkBehaviour, PeerId}; use serde::{Deserialize, Serialize}; use std::time::Duration; diff --git a/swap/src/protocol/bob/event_loop.rs b/swap/src/protocol/bob/event_loop.rs index 21d26a14..78d8c286 100644 --- a/swap/src/protocol/bob/event_loop.rs +++ b/swap/src/protocol/bob/event_loop.rs @@ -1,20 +1,15 @@ -use crate::{ - bitcoin, - bitcoin::EncryptedSignature, - monero, - network::{ - spot_price::{SpotPriceRequest, SpotPriceResponse}, - transport, TokioExecutor, - }, - protocol::{ - alice::TransferProof, - bob::{Behaviour, OutEvent, State0, State2}, - }, -}; +use crate::bitcoin::EncryptedSignature; +use crate::network::spot_price::{SpotPriceRequest, SpotPriceResponse}; +use crate::network::{transport, TokioExecutor}; +use crate::protocol::alice::TransferProof; +use crate::protocol::bob::{Behaviour, OutEvent, State0, State2}; +use crate::{bitcoin, monero}; use anyhow::{anyhow, bail, Context, Result}; use futures::FutureExt; -use libp2p::{core::Multiaddr, PeerId}; -use std::{convert::Infallible, sync::Arc}; +use libp2p::core::Multiaddr; +use libp2p::PeerId; +use std::convert::Infallible; +use std::sync::Arc; use tokio::sync::mpsc::{Receiver, Sender}; use tracing::{debug, error, trace}; diff --git a/swap/src/protocol/bob/execution_setup.rs b/swap/src/protocol/bob/execution_setup.rs index 39f265a7..1443a040 100644 --- a/swap/src/protocol/bob/execution_setup.rs +++ b/swap/src/protocol/bob/execution_setup.rs @@ -1,11 +1,7 @@ -use crate::{ - bitcoin::Signature, - network::request_response::BUF_SIZE, - protocol::{ - alice::{Message1, Message3}, - bob::{State0, State2}, - }, -}; +use crate::bitcoin::Signature; +use crate::network::request_response::BUF_SIZE; +use crate::protocol::alice::{Message1, Message3}; +use crate::protocol::bob::{State0, State2}; use anyhow::{Context, Error, Result}; use libp2p::PeerId; use libp2p_async_await::BehaviourOutEvent; diff --git a/swap/src/protocol/bob/refund.rs b/swap/src/protocol/bob/refund.rs index 8536eed0..ffbfe458 100644 --- a/swap/src/protocol/bob/refund.rs +++ b/swap/src/protocol/bob/refund.rs @@ -1,9 +1,7 @@ -use crate::{ - bitcoin::Wallet, - database::{Database, Swap}, - execution_params::ExecutionParams, - protocol::bob::BobState, -}; +use crate::bitcoin::Wallet; +use crate::database::{Database, Swap}; +use crate::execution_params::ExecutionParams; +use crate::protocol::bob::BobState; use anyhow::{bail, Result}; use std::sync::Arc; use uuid::Uuid; diff --git a/swap/src/protocol/bob/state.rs b/swap/src/protocol/bob/state.rs index 3f407f0f..67cf0bc6 100644 --- a/swap/src/protocol/bob/state.rs +++ b/swap/src/protocol/bob/state.rs @@ -1,24 +1,18 @@ -use crate::{ - bitcoin::{ - self, current_epoch, wait_for_cancel_timelock_to_expire, CancelTimelock, ExpiredTimelocks, - PunishTimelock, Transaction, TxCancel, Txid, - }, - execution_params::ExecutionParams, - monero, - monero::{monero_private_key, InsufficientFunds, TransferProof}, - monero_ext::ScalarExt, - protocol::{ - alice::{Message1, Message3}, - bob::{EncryptedSignature, Message0, Message2, Message4}, - CROSS_CURVE_PROOF_SYSTEM, - }, +use crate::bitcoin::{ + self, current_epoch, wait_for_cancel_timelock_to_expire, CancelTimelock, ExpiredTimelocks, + PunishTimelock, Transaction, TxCancel, Txid, }; +use crate::execution_params::ExecutionParams; +use crate::monero; +use crate::monero::{monero_private_key, InsufficientFunds, TransferProof}; +use crate::monero_ext::ScalarExt; +use crate::protocol::alice::{Message1, Message3}; +use crate::protocol::bob::{EncryptedSignature, Message0, Message2, Message4}; +use crate::protocol::CROSS_CURVE_PROOF_SYSTEM; use anyhow::{anyhow, bail, Context, Result}; -use ecdsa_fun::{ - adaptor::{Adaptor, HashTranscript}, - nonce::Deterministic, - Signature, -}; +use ecdsa_fun::adaptor::{Adaptor, HashTranscript}; +use ecdsa_fun::nonce::Deterministic; +use ecdsa_fun::Signature; use monero_rpc::wallet::BlockHeight; use rand::{CryptoRng, RngCore}; use serde::{Deserialize, Serialize}; diff --git a/swap/src/protocol/bob/swap.rs b/swap/src/protocol/bob/swap.rs index 7b712e29..5f707ae9 100644 --- a/swap/src/protocol/bob/swap.rs +++ b/swap/src/protocol/bob/swap.rs @@ -1,12 +1,11 @@ -use crate::{ - bitcoin, - bitcoin::ExpiredTimelocks, - database::{Database, Swap}, - execution_params::ExecutionParams, - monero, - monero::InsufficientFunds, - protocol::bob::{self, event_loop::EventLoopHandle, state::*}, -}; +use crate::bitcoin::ExpiredTimelocks; +use crate::database::{Database, Swap}; +use crate::execution_params::ExecutionParams; +use crate::monero::InsufficientFunds; +use crate::protocol::bob; +use crate::protocol::bob::event_loop::EventLoopHandle; +use crate::protocol::bob::state::*; +use crate::{bitcoin, monero}; use anyhow::{bail, Result}; use async_recursion::async_recursion; use rand::rngs::OsRng; diff --git a/swap/src/protocol/bob/transfer_proof.rs b/swap/src/protocol/bob/transfer_proof.rs index 67eeb9c4..7b1ff1be 100644 --- a/swap/src/protocol/bob/transfer_proof.rs +++ b/swap/src/protocol/bob/transfer_proof.rs @@ -1,15 +1,11 @@ -use crate::{ - network::request_response::{CborCodec, TransferProofProtocol, TIMEOUT}, - protocol::alice::TransferProof, -}; +use crate::network::request_response::{CborCodec, TransferProofProtocol, TIMEOUT}; +use crate::protocol::alice::TransferProof; use anyhow::{anyhow, Error, Result}; -use libp2p::{ - request_response::{ - ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent, - RequestResponseMessage, ResponseChannel, - }, - NetworkBehaviour, +use libp2p::request_response::{ + ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent, + RequestResponseMessage, ResponseChannel, }; +use libp2p::NetworkBehaviour; use std::time::Duration; use tracing::debug; diff --git a/swap/src/seed.rs b/swap/src/seed.rs index 39235b8d..03413475 100644 --- a/swap/src/seed.rs +++ b/swap/src/seed.rs @@ -1,18 +1,17 @@ use crate::fs::ensure_directory_exists; -use ::bitcoin::secp256k1::{self, constants::SECRET_KEY_SIZE, SecretKey}; +use ::bitcoin::secp256k1::constants::SECRET_KEY_SIZE; +use ::bitcoin::secp256k1::{self, SecretKey}; use anyhow::Result; use bdk::bitcoin::util::bip32::ExtendedPrivKey; use bitcoin::hashes::{sha256, Hash, HashEngine}; use libp2p::identity; use pem::{encode, Pem}; use rand::prelude::*; -use std::{ - ffi::OsStr, - fmt, - fs::{self, File}, - io::{self, Write}, - path::{Path, PathBuf}, -}; +use std::ffi::OsStr; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; pub const SEED_LENGTH: usize = 32; diff --git a/swap/src/serde_peer_id.rs b/swap/src/serde_peer_id.rs index b0da3ac2..8dc9a3e9 100644 --- a/swap/src/serde_peer_id.rs +++ b/swap/src/serde_peer_id.rs @@ -2,7 +2,8 @@ //! HTTP-API. use libp2p::PeerId; -use serde::{de::Error, Deserialize, Deserializer, Serializer}; +use serde::de::Error; +use serde::{Deserialize, Deserializer, Serializer}; pub fn serialize(peer_id: &PeerId, serializer: S) -> Result where diff --git a/swap/src/trace.rs b/swap/src/trace.rs index 6ae1d6ef..7f55c3da 100644 --- a/swap/src/trace.rs +++ b/swap/src/trace.rs @@ -2,7 +2,8 @@ use anyhow::Result; use atty::{self}; use tracing::{info, subscriber}; use tracing_log::LogTracer; -use tracing_subscriber::{filter::LevelFilter, FmtSubscriber}; +use tracing_subscriber::filter::LevelFilter; +use tracing_subscriber::FmtSubscriber; pub fn init_tracing(level: LevelFilter) -> Result<()> { if level == LevelFilter::OFF { diff --git a/swap/tests/bob_refunds_using_cancel_and_refund_command.rs b/swap/tests/bob_refunds_using_cancel_and_refund_command.rs index 43007177..1f464adb 100644 --- a/swap/tests/bob_refunds_using_cancel_and_refund_command.rs +++ b/swap/tests/bob_refunds_using_cancel_and_refund_command.rs @@ -1,7 +1,9 @@ pub mod testutils; -use swap::protocol::{bob, bob::BobState}; -use testutils::{bob_run_until::is_btc_locked, FastCancelConfig}; +use swap::protocol::bob; +use swap::protocol::bob::BobState; +use testutils::bob_run_until::is_btc_locked; +use testutils::FastCancelConfig; #[tokio::test] async fn given_bob_manually_refunds_after_btc_locked_bob_refunds() { diff --git a/swap/tests/bob_refunds_using_cancel_and_refund_command_timelock_not_expired.rs b/swap/tests/bob_refunds_using_cancel_and_refund_command_timelock_not_expired.rs index 9e8a79aa..f2d03608 100644 --- a/swap/tests/bob_refunds_using_cancel_and_refund_command_timelock_not_expired.rs +++ b/swap/tests/bob_refunds_using_cancel_and_refund_command_timelock_not_expired.rs @@ -1,8 +1,10 @@ pub mod testutils; use bob::cancel::CancelError; -use swap::protocol::{bob, bob::BobState}; -use testutils::{bob_run_until::is_btc_locked, SlowCancelConfig}; +use swap::protocol::bob; +use swap::protocol::bob::BobState; +use testutils::bob_run_until::is_btc_locked; +use testutils::SlowCancelConfig; #[tokio::test] async fn given_bob_manually_cancels_when_timelock_not_expired_errors() { diff --git a/swap/tests/bob_refunds_using_cancel_and_refund_command_timelock_not_expired_force.rs b/swap/tests/bob_refunds_using_cancel_and_refund_command_timelock_not_expired_force.rs index fd3465d7..9ae6bf38 100644 --- a/swap/tests/bob_refunds_using_cancel_and_refund_command_timelock_not_expired_force.rs +++ b/swap/tests/bob_refunds_using_cancel_and_refund_command_timelock_not_expired_force.rs @@ -1,7 +1,9 @@ pub mod testutils; -use swap::protocol::{bob, bob::BobState}; -use testutils::{bob_run_until::is_btc_locked, SlowCancelConfig}; +use swap::protocol::bob; +use swap::protocol::bob::BobState; +use testutils::bob_run_until::is_btc_locked; +use testutils::SlowCancelConfig; #[tokio::test] async fn given_bob_manually_forces_cancel_when_timelock_not_expired_errors() { diff --git a/swap/tests/happy_path_restart_bob_before_comm.rs b/swap/tests/happy_path_restart_bob_before_comm.rs index 6235b0ec..49b9c73b 100644 --- a/swap/tests/happy_path_restart_bob_before_comm.rs +++ b/swap/tests/happy_path_restart_bob_before_comm.rs @@ -1,7 +1,9 @@ pub mod testutils; -use swap::protocol::{bob, bob::BobState}; -use testutils::{bob_run_until::is_xmr_locked, SlowCancelConfig}; +use swap::protocol::bob; +use swap::protocol::bob::BobState; +use testutils::bob_run_until::is_xmr_locked; +use testutils::SlowCancelConfig; #[tokio::test] async fn given_bob_restarts_after_xmr_is_locked_resume_swap() { diff --git a/swap/tests/testutils/bitcoind.rs b/swap/tests/testutils/bitcoind.rs index c151a38e..40151537 100644 --- a/swap/tests/testutils/bitcoind.rs +++ b/swap/tests/testutils/bitcoind.rs @@ -1,8 +1,6 @@ use std::collections::HashMap; -use testcontainers::{ - core::{Container, Docker, WaitForMessage}, - Image, -}; +use testcontainers::core::{Container, Docker, WaitForMessage}; +use testcontainers::Image; pub const RPC_USER: &str = "admin"; pub const RPC_PASSWORD: &str = "123"; diff --git a/swap/tests/testutils/electrs.rs b/swap/tests/testutils/electrs.rs index bc7b7079..c4c09720 100644 --- a/swap/tests/testutils/electrs.rs +++ b/swap/tests/testutils/electrs.rs @@ -1,10 +1,8 @@ use crate::testutils::bitcoind; use bitcoin::Network; use std::collections::HashMap; -use testcontainers::{ - core::{Container, Docker, WaitForMessage}, - Image, -}; +use testcontainers::core::{Container, Docker, WaitForMessage}; +use testcontainers::Image; pub const HTTP_PORT: u16 = 60401; pub const RPC_PORT: u16 = 3002; diff --git a/swap/tests/testutils/mod.rs b/swap/tests/testutils/mod.rs index e80094be..ad16dbb8 100644 --- a/swap/tests/testutils/mod.rs +++ b/swap/tests/testutils/mod.rs @@ -4,30 +4,32 @@ mod electrs; use crate::testutils; use anyhow::{Context, Result}; use bitcoin_harness::{BitcoindRpcApi, Client}; -use futures::{future::RemoteHandle, Future}; +use futures::future::RemoteHandle; +use futures::Future; use get_port::get_port; -use libp2p::{core::Multiaddr, PeerId}; +use libp2p::core::Multiaddr; +use libp2p::PeerId; use monero_harness::{image, Monero}; -use std::{ - convert::Infallible, - path::{Path, PathBuf}, - sync::Arc, - time::Duration, -}; -use swap::{ - asb::{fixed_rate, fixed_rate::RATE}, - bitcoin, - bitcoin::{CancelTimelock, PunishTimelock}, - database::Database, - execution_params, - execution_params::{ExecutionParams, GetExecutionParams}, - monero, - protocol::{alice, alice::AliceState, bob, bob::BobState}, - seed::Seed, -}; +use std::convert::Infallible; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; +use swap::asb::fixed_rate; +use swap::asb::fixed_rate::RATE; +use swap::bitcoin::{CancelTimelock, PunishTimelock}; +use swap::database::Database; +use swap::execution_params::{ExecutionParams, GetExecutionParams}; +use swap::protocol::alice::AliceState; +use swap::protocol::bob::BobState; +use swap::protocol::{alice, bob}; +use swap::seed::Seed; +use swap::{bitcoin, execution_params, monero}; use tempfile::tempdir; -use testcontainers::{clients::Cli, Container, Docker, RunArgs}; -use tokio::{sync::mpsc, task::JoinHandle, time::interval}; +use testcontainers::clients::Cli; +use testcontainers::{Container, Docker, RunArgs}; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; +use tokio::time::interval; use tracing::dispatcher::DefaultGuard; use tracing_log::LogTracer; use url::Url; @@ -445,7 +447,8 @@ where } fn random_prefix() -> String { - use rand::{distributions::Alphanumeric, thread_rng, Rng}; + use rand::distributions::Alphanumeric; + use rand::{thread_rng, Rng}; use std::iter; const LEN: usize = 8; let mut rng = thread_rng();