270: Re-configure rustfmt to organize imports differently r=thomaseizinger a=thomaseizinger

Initially, I only set out to do a follow-up PR for e3a73d105b but stumbled over this rustfmt setting that I wanted to try out for a while already.

Enjoy! I already like it because imports take up less space and reduces the chances of merge conflicts.

Co-authored-by: Thomas Eizinger <thomas@eizinger.io>
pull/276/head
bors[bot] 3 years ago committed by GitHub
commit 18f968d51c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,9 +1,12 @@
edition = "2018" edition = "2018"
condense_wildcard_suffixes = true condense_wildcard_suffixes = true
format_macro_matchers = true format_macro_matchers = true
imports_granularity = "Crate" imports_granularity = "Module"
use_field_init_shorthand = true use_field_init_shorthand = true
format_code_in_doc_comments = true format_code_in_doc_comments = true
normalize_comments = true normalize_comments = true
wrap_comments = true wrap_comments = true
overflow_delimited_expr = true overflow_delimited_expr = true
ignore = [
"tokio-tar"
]

@ -1,10 +1,9 @@
mod amounts;
pub mod command; pub mod command;
pub mod config; pub mod config;
pub mod fixed_rate; pub mod fixed_rate;
pub mod kraken; pub mod kraken;
mod amounts;
pub use amounts::Rate; pub use amounts::Rate;
pub trait LatestRate { pub trait LatestRate {

@ -1,6 +1,7 @@
use crate::{bitcoin, monero}; use crate::{bitcoin, monero};
use anyhow::{anyhow, Result}; 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}; use std::fmt::{Debug, Display, Formatter};
/// Prices at which 1 XMR will be traded, in BTC (XMR/BTC pair) /// Prices at which 1 XMR will be traded, in BTC (XMR/BTC pair)

@ -1,5 +1,6 @@
use crate::bitcoin::Amount; use crate::bitcoin::Amount;
use bitcoin::{util::amount::ParseAmountError, Denomination}; use bitcoin::util::amount::ParseAmountError;
use bitcoin::Denomination;
use std::path::PathBuf; use std::path::PathBuf;
#[derive(structopt::StructOpt, Debug)] #[derive(structopt::StructOpt, Debug)]

@ -1,14 +1,13 @@
use crate::fs::{default_data_dir, ensure_directory_exists}; use crate::fs::{default_data_dir, ensure_directory_exists};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use config::ConfigError; use config::ConfigError;
use dialoguer::{theme::ColorfulTheme, Input}; use dialoguer::theme::ColorfulTheme;
use dialoguer::Input;
use libp2p::core::Multiaddr; use libp2p::core::Multiaddr;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{ use std::ffi::OsStr;
ffi::OsStr, use std::fs;
fs, use std::path::{Path, PathBuf};
path::{Path, PathBuf},
};
use tracing::info; use tracing::info;
use url::Url; use url::Url;

@ -7,7 +7,8 @@ use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use std::convert::TryFrom; use std::convert::TryFrom;
use tokio::sync::watch; 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 tracing::{error, trace};
use watch::Receiver; use watch::Receiver;

@ -13,30 +13,25 @@
#![allow(non_snake_case)] #![allow(non_snake_case)]
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use bdk::{descriptor::Segwitv0, keys::DerivableKey}; use bdk::descriptor::Segwitv0;
use bdk::keys::DerivableKey;
use prettytable::{row, Table}; use prettytable::{row, Table};
use std::{path::Path, sync::Arc}; use std::path::Path;
use std::sync::Arc;
use structopt::StructOpt; use structopt::StructOpt;
use swap::{ use swap::asb::command::{Arguments, Command};
asb::{ use swap::asb::config::{
command::{Arguments, Command}, initial_setup, query_user_for_initial_testnet_config, read_config, Config, ConfigNotInitialized,
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::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::{info, warn};
use tracing_subscriber::filter::LevelFilter; use tracing_subscriber::filter::LevelFilter;

@ -15,25 +15,20 @@
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use prettytable::{row, Table}; use prettytable::{row, Table};
use reqwest::Url; 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 structopt::StructOpt;
use swap::{ use swap::bitcoin::{Amount, TxLock};
bitcoin, use swap::cli::command::{Arguments, Command};
bitcoin::{Amount, TxLock}, use swap::cli::config::{read_config, Config};
cli::{ use swap::database::Database;
command::{Arguments, Command}, use swap::execution_params::GetExecutionParams;
config::{read_config, Config}, use swap::protocol::bob;
}, use swap::protocol::bob::cancel::CancelError;
database::Database, use swap::protocol::bob::{Builder, EventLoop};
execution_params, use swap::seed::Seed;
execution_params::GetExecutionParams, use swap::{bitcoin, execution_params, monero};
monero,
protocol::{
bob,
bob::{cancel::CancelError, Builder, EventLoop},
},
seed::Seed,
};
use tracing::{debug, error, info, warn, Level}; use tracing::{debug, error, info, warn, Level};
use tracing_subscriber::FmtSubscriber; use tracing_subscriber::FmtSubscriber;
use uuid::Uuid; use uuid::Uuid;

@ -7,30 +7,29 @@ mod redeem;
mod refund; mod refund;
mod timelocks; mod timelocks;
pub use crate::bitcoin::{ pub use crate::bitcoin::cancel::{CancelTimelock, PunishTimelock, TxCancel};
cancel::{CancelTimelock, PunishTimelock, TxCancel}, pub use crate::bitcoin::lock::TxLock;
lock::TxLock, pub use crate::bitcoin::punish::TxPunish;
punish::TxPunish, pub use crate::bitcoin::redeem::TxRedeem;
redeem::TxRedeem, pub use crate::bitcoin::refund::TxRefund;
refund::TxRefund, pub use crate::bitcoin::timelocks::{BlockHeight, ExpiredTimelocks};
timelocks::{BlockHeight, ExpiredTimelocks}, pub use ::bitcoin::util::amount::Amount;
}; pub use ::bitcoin::{Address, Network, Transaction, Txid};
pub use ::bitcoin::{util::amount::Amount, Address, Network, Transaction, Txid}; pub use ecdsa_fun::adaptor::EncryptedSignature;
pub use ecdsa_fun::{adaptor::EncryptedSignature, fun::Scalar, Signature}; pub use ecdsa_fun::fun::Scalar;
pub use ecdsa_fun::Signature;
pub use wallet::Wallet; pub use wallet::Wallet;
use ::bitcoin::{ use ::bitcoin::hashes::hex::ToHex;
hashes::{hex::ToHex, Hash}, use ::bitcoin::hashes::Hash;
secp256k1, SigHash, use ::bitcoin::{secp256k1, SigHash};
};
use anyhow::{anyhow, bail, Result}; use anyhow::{anyhow, bail, Result};
use ecdsa_fun::{ use ecdsa_fun::adaptor::{Adaptor, HashTranscript};
adaptor::{Adaptor, HashTranscript}, use ecdsa_fun::fun::Point;
fun::Point, use ecdsa_fun::nonce::Deterministic;
nonce::Deterministic, use ecdsa_fun::ECDSA;
ECDSA, use miniscript::descriptor::Wsh;
}; use miniscript::{Descriptor, Segwitv0};
use miniscript::{descriptor::Wsh, Descriptor, Segwitv0};
use rand::{CryptoRng, RngCore}; use rand::{CryptoRng, RngCore};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sha2::Sha256; use sha2::Sha256;

@ -2,12 +2,14 @@ use crate::bitcoin::{
build_shared_output_descriptor, Address, Amount, BlockHeight, PublicKey, Transaction, TxLock, build_shared_output_descriptor, Address, Amount, BlockHeight, PublicKey, Transaction, TxLock,
TX_FEE, 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 anyhow::Result;
use ecdsa_fun::Signature; use ecdsa_fun::Signature;
use miniscript::{Descriptor, DescriptorTrait}; use miniscript::{Descriptor, DescriptorTrait};
use serde::{Deserialize, Serialize}; 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 /// Represent a timelock, expressed in relative block height as defined in
/// [BIP68](https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki). /// [BIP68](https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki).

@ -1,7 +1,8 @@
use crate::bitcoin::{ use crate::bitcoin::{
build_shared_output_descriptor, Address, Amount, PublicKey, Transaction, Wallet, TX_FEE, 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 anyhow::Result;
use ecdsa_fun::fun::Point; use ecdsa_fun::fun::Point;
use miniscript::{Descriptor, DescriptorTrait}; use miniscript::{Descriptor, DescriptorTrait};

@ -1,5 +1,6 @@
use crate::bitcoin::{Address, PublicKey, PunishTimelock, Transaction, TxCancel}; 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 anyhow::Result;
use ecdsa_fun::Signature; use ecdsa_fun::Signature;
use miniscript::{Descriptor, DescriptorTrait}; use miniscript::{Descriptor, DescriptorTrait};

@ -2,7 +2,8 @@ use crate::bitcoin::{
verify_sig, Address, EmptyWitnessStack, NoInputs, NotThreeWitnesses, PublicKey, TooManyInputs, verify_sig, Address, EmptyWitnessStack, NoInputs, NotThreeWitnesses, PublicKey, TooManyInputs,
Transaction, TxLock, 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 anyhow::{bail, Context, Result};
use ecdsa_fun::Signature; use ecdsa_fun::Signature;
use miniscript::{Descriptor, DescriptorTrait}; use miniscript::{Descriptor, DescriptorTrait};

@ -2,7 +2,8 @@ use crate::bitcoin::{
verify_sig, Address, EmptyWitnessStack, NoInputs, NotThreeWitnesses, PublicKey, TooManyInputs, verify_sig, Address, EmptyWitnessStack, NoInputs, NotThreeWitnesses, PublicKey, TooManyInputs,
Transaction, TxCancel, 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 anyhow::{bail, Context, Result};
use ecdsa_fun::Signature; use ecdsa_fun::Signature;
use miniscript::{Descriptor, DescriptorTrait}; use miniscript::{Descriptor, DescriptorTrait};

@ -1,22 +1,24 @@
use crate::{ use crate::bitcoin::timelocks::BlockHeight;
bitcoin::{timelocks::BlockHeight, Address, Amount, Transaction}, use crate::bitcoin::{Address, Amount, Transaction};
execution_params::ExecutionParams, use crate::execution_params::ExecutionParams;
}; use ::bitcoin::util::psbt::PartiallySignedTransaction;
use ::bitcoin::{util::psbt::PartiallySignedTransaction, Txid}; use ::bitcoin::Txid;
use anyhow::{anyhow, bail, Context, Result}; use anyhow::{anyhow, bail, Context, Result};
use backoff::{backoff::Constant as ConstantBackoff, future::retry}; use backoff::backoff::Constant as ConstantBackoff;
use bdk::{ use backoff::future::retry;
blockchain::{noop_progress, Blockchain, ElectrumBlockchain}, use bdk::blockchain::{noop_progress, Blockchain, ElectrumBlockchain};
descriptor::Segwitv0, use bdk::descriptor::Segwitv0;
electrum_client::{self, Client, ElectrumApi}, use bdk::electrum_client::{self, Client, ElectrumApi};
keys::DerivableKey, use bdk::keys::DerivableKey;
FeeRate, KeychainKind, use bdk::{FeeRate, KeychainKind};
};
use bitcoin::Script; use bitcoin::Script;
use reqwest::{Method, Url}; use reqwest::{Method, Url};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{path::Path, sync::Arc, time::Duration}; use std::path::Path;
use tokio::{sync::Mutex, time::interval}; use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use tokio::time::interval;
const SLED_TREE_NAME: &str = "default_tree"; const SLED_TREE_NAME: &str = "default_tree";
@ -309,13 +311,9 @@ fn blocks_tip_height_url(base_url: &Url) -> Result<Url> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::{ use crate::bitcoin::wallet::{blocks_tip_height_url, tx_status_url};
bitcoin::{ use crate::bitcoin::Txid;
wallet::{blocks_tip_height_url, tx_status_url}, use crate::cli::config::DEFAULT_ELECTRUM_HTTP_URL;
Txid,
},
cli::config::DEFAULT_ELECTRUM_HTTP_URL,
};
use reqwest::Url; use reqwest::Url;
#[test] #[test]

@ -1,6 +1,8 @@
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use libp2p::{core::Multiaddr, PeerId}; use libp2p::core::Multiaddr;
use std::{path::PathBuf, str::FromStr}; use libp2p::PeerId;
use std::path::PathBuf;
use std::str::FromStr;
use uuid::Uuid; use uuid::Uuid;
pub const DEFAULT_ALICE_MULTIADDR: &str = "/dns4/xmr-btc-asb.coblox.tech/tcp/9876"; 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<monero::Address> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::cli::command::{DEFAULT_ALICE_MULTIADDR, DEFAULT_ALICE_PEER_ID}; use crate::cli::command::{DEFAULT_ALICE_MULTIADDR, DEFAULT_ALICE_PEER_ID};
use libp2p::{core::Multiaddr, PeerId}; use libp2p::core::Multiaddr;
use libp2p::PeerId;
#[test] #[test]
fn parse_default_alice_peer_id_success() { fn parse_default_alice_peer_id_success() {

@ -2,10 +2,8 @@ use crate::fs::default_data_dir;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use config::ConfigError; use config::ConfigError;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{ use std::ffi::OsStr;
ffi::OsStr, use std::path::{Path, PathBuf};
path::{Path, PathBuf},
};
use tracing::debug; use tracing::debug;
use url::Url; use url::Url;
@ -84,7 +82,8 @@ pub fn read_config(config_path: PathBuf) -> Result<Result<Config, ConfigNotIniti
mod tests { mod tests {
use super::*; use super::*;
use crate::fs::ensure_directory_exists; use crate::fs::ensure_directory_exists;
use std::{fs, str::FromStr}; use std::fs;
use std::str::FromStr;
use tempfile::tempdir; use tempfile::tempdir;
pub fn initial_setup(config_path: PathBuf, config: Config) -> Result<()> { pub fn initial_setup(config_path: PathBuf, config: Config) -> Result<()> {

@ -2,8 +2,10 @@ pub use alice::Alice;
pub use bob::Bob; pub use bob::Bob;
use anyhow::{anyhow, bail, Context, Result}; use anyhow::{anyhow, bail, Context, Result};
use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde::de::DeserializeOwned;
use std::{fmt::Display, path::Path}; use serde::{Deserialize, Serialize};
use std::fmt::Display;
use std::path::Path;
use uuid::Uuid; use uuid::Uuid;
mod alice; mod alice;
@ -123,10 +125,8 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::database::{ use crate::database::alice::{Alice, AliceEndState};
alice::{Alice, AliceEndState}, use crate::database::bob::{Bob, BobEndState};
bob::{Bob, BobEndState},
};
#[tokio::test] #[tokio::test]
async fn can_write_and_read_to_multiple_keys() { async fn can_write_and_read_to_multiple_keys() {

@ -1,9 +1,8 @@
use crate::{ use crate::bitcoin::{EncryptedSignature, TxCancel, TxRefund};
bitcoin::{EncryptedSignature, TxCancel, TxRefund}, use crate::monero;
monero, use crate::monero::monero_private_key;
monero::monero_private_key, use crate::protocol::alice;
protocol::{alice, alice::AliceState}, use crate::protocol::alice::AliceState;
};
use ::bitcoin::hashes::core::fmt::Display; use ::bitcoin::hashes::core::fmt::Display;
use libp2p::PeerId; use libp2p::PeerId;
use monero_rpc::wallet::BlockHeight; use monero_rpc::wallet::BlockHeight;

@ -1,7 +1,6 @@
use crate::{ use crate::monero::TransferProof;
monero::TransferProof, use crate::protocol::bob;
protocol::{bob, bob::BobState}, use crate::protocol::bob::BobState;
};
use ::bitcoin::hashes::core::fmt::Display; use ::bitcoin::hashes::core::fmt::Display;
use monero_rpc::wallet::BlockHeight; use monero_rpc::wallet::BlockHeight;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};

@ -7,20 +7,15 @@ pub use wallet::Wallet;
pub use wallet_rpc::{WalletRpc, WalletRpcProcess}; pub use wallet_rpc::{WalletRpc, WalletRpcProcess};
use crate::bitcoin; use crate::bitcoin;
use ::bitcoin::hashes::core::fmt::Formatter;
use anyhow::Result; use anyhow::Result;
use rand::{CryptoRng, RngCore}; use rand::{CryptoRng, RngCore};
use rust_decimal::{ use rust_decimal::prelude::*;
prelude::{FromPrimitive, ToPrimitive}, use rust_decimal::Decimal;
Decimal,
};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{ use std::convert::TryFrom;
convert::TryFrom, use std::fmt;
fmt::Display, use std::ops::{Add, Mul, Sub};
ops::{Add, Mul, Sub}, use std::str::FromStr;
str::FromStr,
};
pub const PICONERO_OFFSET: u64 = 1_000_000_000_000; pub const PICONERO_OFFSET: u64 = 1_000_000_000_000;
@ -141,8 +136,8 @@ impl From<Amount> for u64 {
} }
} }
impl Display for Amount { impl fmt::Display for Amount {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut decimal = Decimal::from(self.0); let mut decimal = Decimal::from(self.0);
decimal decimal
.set_scale(12) .set_scale(12)
@ -198,12 +193,13 @@ pub struct BalanceTooLow {
pub struct OverflowError(pub String); pub struct OverflowError(pub String);
pub mod monero_private_key { pub mod monero_private_key {
use monero::{ use monero::consensus::{Decodable, Encodable};
consensus::{Decodable, Encodable}, use monero::PrivateKey;
PrivateKey, use serde::de::Visitor;
}; use serde::ser::Error;
use serde::{de, de::Visitor, ser::Error, Deserializer, Serializer}; use serde::{de, Deserializer, Serializer};
use std::{fmt, io::Cursor}; use std::fmt;
use std::io::Cursor;
struct BytesVisitor; struct BytesVisitor;

@ -3,13 +3,14 @@ use crate::monero::{
}; };
use ::monero::{Address, Network, PrivateKey, PublicKey}; use ::monero::{Address, Network, PrivateKey, PublicKey};
use anyhow::{Context, Result}; 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 bitcoin::hashes::core::sync::atomic::AtomicU32;
use monero_rpc::{ use monero_rpc::wallet;
wallet, use monero_rpc::wallet::{BlockHeight, Refreshed};
wallet::{BlockHeight, Refreshed}, use std::str::FromStr;
}; use std::sync::atomic::Ordering;
use std::{str::FromStr, sync::atomic::Ordering, time::Duration}; use std::time::Duration;
use tokio::sync::Mutex; use tokio::sync::Mutex;
use tracing::{debug, info}; use tracing::{debug, info};
use url::Url; use url::Url;

@ -2,21 +2,16 @@ use ::monero::Network;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use big_bytes::BigByte; use big_bytes::BigByte;
use futures::{StreamExt, TryStreamExt}; use futures::{StreamExt, TryStreamExt};
use reqwest::{header::CONTENT_LENGTH, Url}; use reqwest::header::CONTENT_LENGTH;
use std::{ use reqwest::Url;
io::ErrorKind, use std::io::ErrorKind;
path::{Path, PathBuf}, use std::path::{Path, PathBuf};
process::Stdio, use std::process::Stdio;
}; use tokio::fs::{remove_file, OpenOptions};
use tokio::{ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
fs::{remove_file, OpenOptions}, use tokio::process::{Child, Command};
io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, use tokio_util::codec::{BytesCodec, FramedRead};
process::{Child, Command}, use tokio_util::io::StreamReader;
};
use tokio_util::{
codec::{BytesCodec, FramedRead},
io::StreamReader,
};
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))] #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
compile_error!("unsupported operating system"); compile_error!("unsupported operating system");

@ -3,8 +3,8 @@ pub mod request_response;
pub mod spot_price; pub mod spot_price;
pub mod transport; pub mod transport;
use futures::prelude::*;
use libp2p::core::Executor; use libp2p::core::Executor;
use std::future::Future;
use std::pin::Pin; use std::pin::Pin;
use tokio::runtime::Handle; use tokio::runtime::Handle;

@ -1,16 +1,11 @@
use futures::task::Context; use futures::task::Context;
use libp2p::{ use libp2p::core::connection::ConnectionId;
core::{connection::ConnectionId, ConnectedPoint}, use libp2p::core::ConnectedPoint;
swarm::{ use libp2p::swarm::protocols_handler::DummyProtocolsHandler;
protocols_handler::DummyProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, use libp2p::swarm::{NetworkBehaviour, NetworkBehaviourAction, PollParameters};
PollParameters, use libp2p::{Multiaddr, PeerId};
}, use std::collections::{HashMap, VecDeque};
Multiaddr, PeerId, use std::task::Poll;
};
use std::{
collections::{HashMap, VecDeque},
task::Poll,
};
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
pub enum OutEvent { pub enum OutEvent {
@ -22,13 +17,13 @@ pub enum OutEvent {
/// peers we only ever connect to a single counterparty. Peer Tracker tracks /// peers we only ever connect to a single counterparty. Peer Tracker tracks
/// that connection. /// that connection.
#[derive(Default, Debug)] #[derive(Default, Debug)]
pub struct PeerTracker { pub struct Behaviour {
connected: Option<(PeerId, Multiaddr)>, connected: Option<(PeerId, Multiaddr)>,
address_of_peer: HashMap<PeerId, Multiaddr>, address_of_peer: HashMap<PeerId, Multiaddr>,
events: VecDeque<OutEvent>, events: VecDeque<OutEvent>,
} }
impl PeerTracker { impl Behaviour {
/// Return whether we are connected to the given peer. /// Return whether we are connected to the given peer.
pub fn is_connected(&self, peer_id: &PeerId) -> bool { pub fn is_connected(&self, peer_id: &PeerId) -> bool {
if let Some((connected_peer_id, _)) = &self.connected { if let Some((connected_peer_id, _)) = &self.connected {
@ -61,7 +56,7 @@ impl PeerTracker {
} }
} }
impl NetworkBehaviour for PeerTracker { impl NetworkBehaviour for Behaviour {
type ProtocolsHandler = DummyProtocolsHandler; type ProtocolsHandler = DummyProtocolsHandler;
type OutEvent = OutEvent; type OutEvent = OutEvent;

@ -1,11 +1,13 @@
use async_trait::async_trait; use async_trait::async_trait;
use futures::prelude::*; use futures::prelude::*;
use libp2p::{ use libp2p::core::upgrade;
core::{upgrade, upgrade::ReadOneError}, use libp2p::core::upgrade::ReadOneError;
request_response::{ProtocolName, RequestResponseCodec}, use libp2p::request_response::{ProtocolName, RequestResponseCodec};
}; use serde::de::DeserializeOwned;
use serde::{de::DeserializeOwned, Serialize}; use serde::Serialize;
use std::{fmt::Debug, io, marker::PhantomData}; use std::fmt::Debug;
use std::io;
use std::marker::PhantomData;
/// Time to wait for a response back once we send a request. /// Time to wait for a response back once we send a request.
pub const TIMEOUT: u64 = 3600; // One hour. pub const TIMEOUT: u64 = 3600; // One hour.

@ -1,13 +1,12 @@
use crate::{bitcoin, monero, network::request_response::CborCodec}; use crate::network::request_response::CborCodec;
use libp2p::{ use crate::{bitcoin, monero};
core::ProtocolName, use libp2p::core::ProtocolName;
request_response::{ use libp2p::request_response::{
ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent, ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent,
},
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
pub type OutEvent = RequestResponseEvent<SpotPriceRequest, SpotPriceResponse>; pub type OutEvent = RequestResponseEvent<Request, Response>;
/// The spot price protocol allows parties to **initiate** a trade by requesting /// The spot price protocol allows parties to **initiate** a trade by requesting
/// a spot price. /// a spot price.
@ -28,18 +27,17 @@ impl ProtocolName for SpotPriceProtocol {
} }
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SpotPriceRequest { pub struct Request {
#[serde(with = "::bitcoin::util::amount::serde::as_sat")] #[serde(with = "::bitcoin::util::amount::serde::as_sat")]
pub btc: bitcoin::Amount, pub btc: bitcoin::Amount,
} }
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SpotPriceResponse { pub struct Response {
pub xmr: monero::Amount, pub xmr: monero::Amount,
} }
pub type Behaviour = pub type Behaviour = RequestResponse<CborCodec<SpotPriceProtocol, Request, Response>>;
RequestResponse<CborCodec<SpotPriceProtocol, SpotPriceRequest, SpotPriceResponse>>;
/// Constructs a new instance of the `spot-price` behaviour to be used by Alice. /// Constructs a new instance of the `spot-price` behaviour to be used by Alice.
/// ///

@ -1,17 +1,12 @@
use anyhow::Result; use anyhow::Result;
use libp2p::{ use libp2p::core::muxing::StreamMuxerBox;
core::{ use libp2p::core::transport::Boxed;
identity, use libp2p::core::upgrade::{SelectUpgrade, Version};
muxing::StreamMuxerBox, use libp2p::core::{identity, Transport};
transport::Boxed, use libp2p::dns::DnsConfig;
upgrade::{SelectUpgrade, Version}, use libp2p::mplex::MplexConfig;
Transport, use libp2p::noise::{self, NoiseConfig, X25519Spec};
}, use libp2p::{yamux, PeerId};
dns::DnsConfig,
mplex::MplexConfig,
noise::{self, NoiseConfig, X25519Spec},
yamux, PeerId,
};
/// Builds a libp2p transport with the following features: /// Builds a libp2p transport with the following features:
/// - TcpConnection /// - TcpConnection

@ -1,7 +1,8 @@
use conquer_once::Lazy; use conquer_once::Lazy;
use ecdsa_fun::fun::marker::Mark; use ecdsa_fun::fun::marker::Mark;
use sha2::Sha256; 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 alice;
pub mod bob; pub mod bob;

@ -1,17 +1,17 @@
//! Run an XMR/BTC swap in the role of Alice. //! Run an XMR/BTC swap in the role of Alice.
//! Alice holds XMR and wishes receive BTC. //! 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 std::sync::Arc;
use uuid::Uuid; use uuid::Uuid;
pub use self::{ pub use self::behaviour::{Behaviour, OutEvent};
behaviour::{Behaviour, OutEvent}, pub use self::event_loop::{EventLoop, EventLoopHandle};
event_loop::{EventLoop, EventLoopHandle}, pub use self::execution_setup::Message1;
execution_setup::Message1, pub use self::state::*;
state::*, pub use self::swap::{run, run_until};
swap::{run, run_until}, pub use self::transfer_proof::TransferProof;
transfer_proof::TransferProof,
};
pub use execution_setup::Message3; pub use execution_setup::Message3;
mod behaviour; mod behaviour;

@ -1,25 +1,14 @@
use crate::{ use crate::execution_params::ExecutionParams;
bitcoin, use crate::network::spot_price::{Request, Response};
execution_params::ExecutionParams, use crate::network::{peer_tracker, spot_price};
monero, use crate::protocol::alice::{
network::{
peer_tracker,
peer_tracker::PeerTracker,
spot_price,
spot_price::{SpotPriceRequest, SpotPriceResponse},
},
protocol::{
alice::{
encrypted_signature, execution_setup, transfer_proof, State0, State3, TransferProof, encrypted_signature, execution_setup, transfer_proof, State0, State3, TransferProof,
},
bob::EncryptedSignature,
},
}; };
use crate::protocol::bob::EncryptedSignature;
use crate::{bitcoin, monero};
use anyhow::{anyhow, Error, Result}; use anyhow::{anyhow, Error, Result};
use libp2p::{ use libp2p::request_response::{RequestResponseMessage, ResponseChannel};
request_response::{RequestResponseMessage, ResponseChannel}, use libp2p::{NetworkBehaviour, PeerId};
NetworkBehaviour, PeerId,
};
use rand::{CryptoRng, RngCore}; use rand::{CryptoRng, RngCore};
use tracing::debug; use tracing::debug;
@ -27,8 +16,8 @@ use tracing::debug;
pub enum OutEvent { pub enum OutEvent {
ConnectionEstablished(PeerId), ConnectionEstablished(PeerId),
SpotPriceRequested { SpotPriceRequested {
msg: SpotPriceRequest, msg: Request,
channel: ResponseChannel<SpotPriceResponse>, channel: ResponseChannel<Response>,
peer: PeerId, peer: PeerId,
}, },
ExecutionSetupDone { ExecutionSetupDone {
@ -134,7 +123,7 @@ impl From<encrypted_signature::OutEvent> for OutEvent {
#[behaviour(out_event = "OutEvent", event_process = false)] #[behaviour(out_event = "OutEvent", event_process = false)]
#[allow(missing_debug_implementations)] #[allow(missing_debug_implementations)]
pub struct Behaviour { pub struct Behaviour {
pt: PeerTracker, pt: peer_tracker::Behaviour,
spot_price: spot_price::Behaviour, spot_price: spot_price::Behaviour,
execution_setup: execution_setup::Behaviour, execution_setup: execution_setup::Behaviour,
transfer_proof: transfer_proof::Behaviour, transfer_proof: transfer_proof::Behaviour,
@ -156,8 +145,8 @@ impl Default for Behaviour {
impl Behaviour { impl Behaviour {
pub fn send_spot_price( pub fn send_spot_price(
&mut self, &mut self,
channel: ResponseChannel<SpotPriceResponse>, channel: ResponseChannel<Response>,
response: SpotPriceResponse, response: Response,
) -> Result<()> { ) -> Result<()> {
self.spot_price self.spot_price
.send_response(channel, response) .send_response(channel, response)

@ -1,15 +1,11 @@
use crate::{ use crate::network::request_response::{CborCodec, EncryptedSignatureProtocol, TIMEOUT};
network::request_response::{CborCodec, EncryptedSignatureProtocol, TIMEOUT}, use crate::protocol::bob::EncryptedSignature;
protocol::bob::EncryptedSignature,
};
use anyhow::{anyhow, Error, Result}; use anyhow::{anyhow, Error, Result};
use libp2p::{ use libp2p::request_response::{
request_response::{
ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent, ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent,
RequestResponseMessage, ResponseChannel, RequestResponseMessage, ResponseChannel,
},
NetworkBehaviour,
}; };
use libp2p::NetworkBehaviour;
use std::time::Duration; use std::time::Duration;
use tracing::debug; use tracing::debug;

@ -1,24 +1,23 @@
use crate::{ use crate::asb::LatestRate;
asb::LatestRate, use crate::database::Database;
bitcoin, use crate::execution_params::ExecutionParams;
database::Database, use crate::monero::BalanceTooLow;
execution_params::ExecutionParams, use crate::network::spot_price::Response;
monero, use crate::network::{transport, TokioExecutor};
monero::BalanceTooLow, use crate::protocol::alice;
network::{spot_price::SpotPriceResponse, transport, TokioExecutor}, use crate::protocol::alice::{AliceState, Behaviour, OutEvent, State3, Swap, TransferProof};
protocol::{ use crate::protocol::bob::EncryptedSignature;
alice, use crate::seed::Seed;
alice::{AliceState, Behaviour, OutEvent, State3, Swap, TransferProof}, use crate::{bitcoin, monero};
bob::EncryptedSignature,
},
seed::Seed,
};
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use futures::future::RemoteHandle; 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 rand::rngs::OsRng;
use std::sync::Arc; 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 tracing::{debug, error, trace};
use uuid::Uuid; use uuid::Uuid;
@ -172,7 +171,7 @@ where
} }
}; };
match self.swarm.send_spot_price(channel, SpotPriceResponse { xmr }) { match self.swarm.send_spot_price(channel, Response { xmr }) {
Ok(_) => {}, Ok(_) => {},
Err(e) => { Err(e) => {
// if we can't respond, the peer probably just disconnected so it is not a huge deal, only log this on debug // if we can't respond, the peer probably just disconnected so it is not a huge deal, only log this on debug

@ -1,13 +1,8 @@
use crate::{ use crate::bitcoin::{EncryptedSignature, Signature};
bitcoin, use crate::network::request_response::BUF_SIZE;
bitcoin::{EncryptedSignature, Signature}, use crate::protocol::alice::{State0, State3};
monero, use crate::protocol::bob::{Message0, Message2, Message4};
network::request_response::BUF_SIZE, use crate::{bitcoin, monero};
protocol::{
alice::{State0, State3},
bob::{Message0, Message2, Message4},
},
};
use anyhow::{Context, Error}; use anyhow::{Context, Error};
use libp2p::PeerId; use libp2p::PeerId;
use libp2p_async_await::BehaviourOutEvent; use libp2p_async_await::BehaviourOutEvent;

@ -1,17 +1,12 @@
use crate::{ use crate::bitcoin::{
bitcoin,
bitcoin::{
current_epoch, wait_for_cancel_timelock_to_expire, CancelTimelock, ExpiredTimelocks, current_epoch, wait_for_cancel_timelock_to_expire, CancelTimelock, ExpiredTimelocks,
PunishTimelock, TxCancel, TxRefund, PunishTimelock, TxCancel, TxRefund,
},
execution_params::ExecutionParams,
monero,
protocol::{
alice::{Message1, Message3},
bob::{Message0, Message2, Message4},
CROSS_CURVE_PROOF_SYSTEM,
},
}; };
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 anyhow::{anyhow, bail, Context, Result};
use libp2p::PeerId; use libp2p::PeerId;
use monero_rpc::wallet::BlockHeight; use monero_rpc::wallet::BlockHeight;

@ -1,25 +1,17 @@
use crate::{ use crate::bitcoin::{
bitcoin,
bitcoin::{
poll_until_block_height_is_gte, BlockHeight, CancelTimelock, EncryptedSignature, poll_until_block_height_is_gte, BlockHeight, CancelTimelock, EncryptedSignature,
PunishTimelock, TxCancel, TxLock, TxRefund, PunishTimelock, TxCancel, TxLock, TxRefund,
},
execution_params::ExecutionParams,
monero,
protocol::{
alice,
alice::{event_loop::EventLoopHandle, TransferProof},
},
}; };
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 anyhow::{Context, Result};
use ecdsa_fun::{ use ecdsa_fun::adaptor::{Adaptor, HashTranscript};
adaptor::{Adaptor, HashTranscript}, use ecdsa_fun::nonce::Deterministic;
nonce::Deterministic, use futures::future::{select, Either};
}; use futures::pin_mut;
use futures::{
future::{select, Either},
pin_mut,
};
use libp2p::PeerId; use libp2p::PeerId;
use sha2::Sha256; use sha2::Sha256;
use tokio::time::timeout; use tokio::time::timeout;

@ -1,33 +1,22 @@
//! Run an XMR/BTC swap in the role of Alice. //! Run an XMR/BTC swap in the role of Alice.
//! Alice holds XMR and wishes receive BTC. //! Alice holds XMR and wishes receive BTC.
use crate::{ use crate::bitcoin::ExpiredTimelocks;
bitcoin, use crate::database::Database;
bitcoin::ExpiredTimelocks, use crate::execution_params::ExecutionParams;
database, use crate::monero_ext::ScalarExt;
database::Database, use crate::protocol::alice;
execution_params::ExecutionParams, use crate::protocol::alice::event_loop::EventLoopHandle;
monero, use crate::protocol::alice::steps::{
monero_ext::ScalarExt, build_bitcoin_punish_transaction, build_bitcoin_redeem_transaction, extract_monero_private_key,
protocol::{ lock_xmr, publish_cancel_transaction, wait_for_bitcoin_encrypted_signature,
alice, wait_for_bitcoin_refund, wait_for_locked_bitcoin,
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::protocol::alice::AliceState;
use crate::{bitcoin, database, monero};
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use async_recursion::async_recursion; use async_recursion::async_recursion;
use futures::{ use futures::future::{select, Either};
future::{select, Either}, use futures::pin_mut;
pin_mut,
};
use rand::{CryptoRng, RngCore}; use rand::{CryptoRng, RngCore};
use std::sync::Arc; use std::sync::Arc;
use tracing::{error, info}; use tracing::{error, info};

@ -1,15 +1,11 @@
use crate::{ use crate::monero;
monero, use crate::network::request_response::{CborCodec, TransferProofProtocol, TIMEOUT};
network::request_response::{CborCodec, TransferProofProtocol, TIMEOUT},
};
use anyhow::{anyhow, Error}; use anyhow::{anyhow, Error};
use libp2p::{ use libp2p::request_response::{
request_response::{
ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent, ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent,
RequestResponseMessage, RequestResponseMessage,
},
NetworkBehaviour, PeerId,
}; };
use libp2p::{NetworkBehaviour, PeerId};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::time::Duration; use std::time::Duration;

@ -1,34 +1,23 @@
use crate::{ use crate::database::Database;
bitcoin, use crate::execution_params::ExecutionParams;
database::Database, use crate::network::{peer_tracker, spot_price};
execution_params::ExecutionParams, use crate::protocol::alice::TransferProof;
monero, use crate::{bitcoin, monero};
network::{
peer_tracker::{self, PeerTracker},
spot_price,
spot_price::{SpotPriceRequest, SpotPriceResponse},
},
protocol::{alice::TransferProof, bob},
};
use anyhow::{anyhow, Error, Result}; use anyhow::{anyhow, Error, Result};
pub use execution_setup::{Message0, Message2, Message4}; use libp2p::core::Multiaddr;
use libp2p::{ use libp2p::request_response::{RequestResponseMessage, ResponseChannel};
core::Multiaddr, use libp2p::{NetworkBehaviour, PeerId};
request_response::{RequestResponseMessage, ResponseChannel},
NetworkBehaviour, PeerId,
};
use std::sync::Arc; use std::sync::Arc;
use tracing::debug; use tracing::debug;
use uuid::Uuid; use uuid::Uuid;
pub use self::{ pub use self::cancel::cancel;
cancel::cancel, pub use self::encrypted_signature::EncryptedSignature;
encrypted_signature::EncryptedSignature, pub use self::event_loop::{EventLoop, EventLoopHandle};
event_loop::{EventLoop, EventLoopHandle}, pub use self::execution_setup::{Message0, Message2, Message4};
refund::refund, pub use self::refund::refund;
state::*, pub use self::state::*;
swap::{run, run_until}, pub use self::swap::{run, run_until};
};
pub mod cancel; pub mod cancel;
mod encrypted_signature; mod encrypted_signature;
@ -41,7 +30,7 @@ mod transfer_proof;
pub struct Swap { pub struct Swap {
pub state: BobState, pub state: BobState,
pub event_loop_handle: bob::EventLoopHandle, pub event_loop_handle: EventLoopHandle,
pub db: Database, pub db: Database,
pub bitcoin_wallet: Arc<bitcoin::Wallet>, pub bitcoin_wallet: Arc<bitcoin::Wallet>,
pub monero_wallet: Arc<monero::Wallet>, pub monero_wallet: Arc<monero::Wallet>,
@ -60,7 +49,7 @@ pub struct Builder {
init_params: InitParams, init_params: InitParams,
execution_params: ExecutionParams, execution_params: ExecutionParams,
event_loop_handle: bob::EventLoopHandle, event_loop_handle: EventLoopHandle,
receive_monero_address: ::monero::Address, receive_monero_address: ::monero::Address,
} }
@ -78,7 +67,7 @@ impl Builder {
bitcoin_wallet: Arc<bitcoin::Wallet>, bitcoin_wallet: Arc<bitcoin::Wallet>,
monero_wallet: Arc<monero::Wallet>, monero_wallet: Arc<monero::Wallet>,
execution_params: ExecutionParams, execution_params: ExecutionParams,
event_loop_handle: bob::EventLoopHandle, event_loop_handle: EventLoopHandle,
receive_monero_address: ::monero::Address, receive_monero_address: ::monero::Address,
) -> Self { ) -> Self {
Self { Self {
@ -100,7 +89,7 @@ impl Builder {
} }
} }
pub fn build(self) -> Result<bob::Swap> { pub fn build(self) -> Result<Swap> {
let state = match self.init_params { let state = match self.init_params {
InitParams::New { btc_amount } => BobState::Started { btc_amount }, InitParams::New { btc_amount } => BobState::Started { btc_amount },
InitParams::None => self.db.get_state(self.swap_id)?.try_into_bob()?.into(), InitParams::None => self.db.get_state(self.swap_id)?.try_into_bob()?.into(),
@ -122,7 +111,7 @@ impl Builder {
#[derive(Debug)] #[derive(Debug)]
pub enum OutEvent { pub enum OutEvent {
ConnectionEstablished(PeerId), ConnectionEstablished(PeerId),
SpotPriceReceived(SpotPriceResponse), SpotPriceReceived(spot_price::Response),
ExecutionSetupDone(Result<Box<State2>>), ExecutionSetupDone(Result<Box<State2>>),
TransferProof { TransferProof {
msg: Box<TransferProof>, msg: Box<TransferProof>,
@ -216,7 +205,7 @@ impl From<encrypted_signature::OutEvent> for OutEvent {
#[behaviour(out_event = "OutEvent", event_process = false)] #[behaviour(out_event = "OutEvent", event_process = false)]
#[allow(missing_debug_implementations)] #[allow(missing_debug_implementations)]
pub struct Behaviour { pub struct Behaviour {
pt: PeerTracker, pt: peer_tracker::Behaviour,
spot_price: spot_price::Behaviour, spot_price: spot_price::Behaviour,
execution_setup: execution_setup::Behaviour, execution_setup: execution_setup::Behaviour,
transfer_proof: transfer_proof::Behaviour, transfer_proof: transfer_proof::Behaviour,
@ -236,7 +225,7 @@ impl Default for Behaviour {
} }
impl Behaviour { impl Behaviour {
pub fn request_spot_price(&mut self, alice: PeerId, request: SpotPriceRequest) { pub fn request_spot_price(&mut self, alice: PeerId, request: spot_price::Request) {
let _ = self.spot_price.send_request(&alice, request); let _ = self.spot_price.send_request(&alice, request);
} }

@ -1,8 +1,6 @@
use crate::{ use crate::bitcoin::{ExpiredTimelocks, Txid, Wallet};
bitcoin::{ExpiredTimelocks, Txid, Wallet}, use crate::database::{Database, Swap};
database::{Database, Swap}, use crate::protocol::bob::BobState;
protocol::bob::BobState,
};
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use std::sync::Arc; use std::sync::Arc;
use uuid::Uuid; use uuid::Uuid;

@ -1,12 +1,10 @@
use crate::network::request_response::{CborCodec, EncryptedSignatureProtocol, TIMEOUT}; use crate::network::request_response::{CborCodec, EncryptedSignatureProtocol, TIMEOUT};
use anyhow::{anyhow, Error}; use anyhow::{anyhow, Error};
use libp2p::{ use libp2p::request_response::{
request_response::{
ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent, ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent,
RequestResponseMessage, RequestResponseMessage,
},
NetworkBehaviour, PeerId,
}; };
use libp2p::{NetworkBehaviour, PeerId};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::time::Duration; use std::time::Duration;

@ -1,20 +1,15 @@
use crate::{ use crate::bitcoin::EncryptedSignature;
bitcoin, use crate::network::spot_price::{Request, Response};
bitcoin::EncryptedSignature, use crate::network::{transport, TokioExecutor};
monero, use crate::protocol::alice::TransferProof;
network::{ use crate::protocol::bob::{Behaviour, OutEvent, State0, State2};
spot_price::{SpotPriceRequest, SpotPriceResponse}, use crate::{bitcoin, monero};
transport, TokioExecutor,
},
protocol::{
alice::TransferProof,
bob::{Behaviour, OutEvent, State0, State2},
},
};
use anyhow::{anyhow, bail, Context, Result}; use anyhow::{anyhow, bail, Context, Result};
use futures::FutureExt; use futures::FutureExt;
use libp2p::{core::Multiaddr, PeerId}; use libp2p::core::Multiaddr;
use std::{convert::Infallible, sync::Arc}; use libp2p::PeerId;
use std::convert::Infallible;
use std::sync::Arc;
use tokio::sync::mpsc::{Receiver, Sender}; use tokio::sync::mpsc::{Receiver, Sender};
use tracing::{debug, error, trace}; use tracing::{debug, error, trace};
@ -39,13 +34,13 @@ impl<T> Default for Channels<T> {
#[derive(Debug)] #[derive(Debug)]
pub struct EventLoopHandle { pub struct EventLoopHandle {
recv_spot_price: Receiver<SpotPriceResponse>, recv_spot_price: Receiver<Response>,
start_execution_setup: Sender<State0>, start_execution_setup: Sender<State0>,
done_execution_setup: Receiver<Result<State2>>, done_execution_setup: Receiver<Result<State2>>,
recv_transfer_proof: Receiver<TransferProof>, recv_transfer_proof: Receiver<TransferProof>,
conn_established: Receiver<PeerId>, conn_established: Receiver<PeerId>,
dial_alice: Sender<()>, dial_alice: Sender<()>,
request_spot_price: Sender<SpotPriceRequest>, request_spot_price: Sender<Request>,
send_encrypted_signature: Sender<EncryptedSignature>, send_encrypted_signature: Sender<EncryptedSignature>,
} }
@ -80,10 +75,7 @@ impl EventLoopHandle {
} }
pub async fn request_spot_price(&mut self, btc: bitcoin::Amount) -> Result<monero::Amount> { pub async fn request_spot_price(&mut self, btc: bitcoin::Amount) -> Result<monero::Amount> {
let _ = self let _ = self.request_spot_price.send(Request { btc }).await?;
.request_spot_price
.send(SpotPriceRequest { btc })
.await?;
let response = self let response = self
.recv_spot_price .recv_spot_price
@ -109,8 +101,8 @@ pub struct EventLoop {
swarm: libp2p::Swarm<Behaviour>, swarm: libp2p::Swarm<Behaviour>,
bitcoin_wallet: Arc<bitcoin::Wallet>, bitcoin_wallet: Arc<bitcoin::Wallet>,
alice_peer_id: PeerId, alice_peer_id: PeerId,
request_spot_price: Receiver<SpotPriceRequest>, request_spot_price: Receiver<Request>,
recv_spot_price: Sender<SpotPriceResponse>, recv_spot_price: Sender<Response>,
start_execution_setup: Receiver<State0>, start_execution_setup: Receiver<State0>,
done_execution_setup: Sender<Result<State2>>, done_execution_setup: Sender<Result<State2>>,
recv_transfer_proof: Sender<TransferProof>, recv_transfer_proof: Sender<TransferProof>,

@ -1,11 +1,7 @@
use crate::{ use crate::bitcoin::Signature;
bitcoin::Signature, use crate::network::request_response::BUF_SIZE;
network::request_response::BUF_SIZE, use crate::protocol::alice::{Message1, Message3};
protocol::{ use crate::protocol::bob::{State0, State2};
alice::{Message1, Message3},
bob::{State0, State2},
},
};
use anyhow::{Context, Error, Result}; use anyhow::{Context, Error, Result};
use libp2p::PeerId; use libp2p::PeerId;
use libp2p_async_await::BehaviourOutEvent; use libp2p_async_await::BehaviourOutEvent;

@ -1,9 +1,7 @@
use crate::{ use crate::bitcoin::Wallet;
bitcoin::Wallet, use crate::database::{Database, Swap};
database::{Database, Swap}, use crate::execution_params::ExecutionParams;
execution_params::ExecutionParams, use crate::protocol::bob::BobState;
protocol::bob::BobState,
};
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use std::sync::Arc; use std::sync::Arc;
use uuid::Uuid; use uuid::Uuid;

@ -1,24 +1,18 @@
use crate::{ use crate::bitcoin::{
bitcoin::{
self, current_epoch, wait_for_cancel_timelock_to_expire, CancelTimelock, ExpiredTimelocks, self, current_epoch, wait_for_cancel_timelock_to_expire, CancelTimelock, ExpiredTimelocks,
PunishTimelock, Transaction, TxCancel, Txid, 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::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 anyhow::{anyhow, bail, Context, Result};
use ecdsa_fun::{ use ecdsa_fun::adaptor::{Adaptor, HashTranscript};
adaptor::{Adaptor, HashTranscript}, use ecdsa_fun::nonce::Deterministic;
nonce::Deterministic, use ecdsa_fun::Signature;
Signature,
};
use monero_rpc::wallet::BlockHeight; use monero_rpc::wallet::BlockHeight;
use rand::{CryptoRng, RngCore}; use rand::{CryptoRng, RngCore};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};

@ -1,12 +1,11 @@
use crate::{ use crate::bitcoin::ExpiredTimelocks;
bitcoin, use crate::database::{Database, Swap};
bitcoin::ExpiredTimelocks, use crate::execution_params::ExecutionParams;
database::{Database, Swap}, use crate::monero::InsufficientFunds;
execution_params::ExecutionParams, use crate::protocol::bob;
monero, use crate::protocol::bob::event_loop::EventLoopHandle;
monero::InsufficientFunds, use crate::protocol::bob::state::*;
protocol::bob::{self, event_loop::EventLoopHandle, state::*}, use crate::{bitcoin, monero};
};
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use async_recursion::async_recursion; use async_recursion::async_recursion;
use rand::rngs::OsRng; use rand::rngs::OsRng;

@ -1,15 +1,11 @@
use crate::{ use crate::network::request_response::{CborCodec, TransferProofProtocol, TIMEOUT};
network::request_response::{CborCodec, TransferProofProtocol, TIMEOUT}, use crate::protocol::alice::TransferProof;
protocol::alice::TransferProof,
};
use anyhow::{anyhow, Error, Result}; use anyhow::{anyhow, Error, Result};
use libp2p::{ use libp2p::request_response::{
request_response::{
ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent, ProtocolSupport, RequestResponse, RequestResponseConfig, RequestResponseEvent,
RequestResponseMessage, ResponseChannel, RequestResponseMessage, ResponseChannel,
},
NetworkBehaviour,
}; };
use libp2p::NetworkBehaviour;
use std::time::Duration; use std::time::Duration;
use tracing::debug; use tracing::debug;

@ -1,18 +1,17 @@
use crate::fs::ensure_directory_exists; 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 anyhow::Result;
use bdk::bitcoin::util::bip32::ExtendedPrivKey; use bdk::bitcoin::util::bip32::ExtendedPrivKey;
use bitcoin::hashes::{sha256, Hash, HashEngine}; use bitcoin::hashes::{sha256, Hash, HashEngine};
use libp2p::identity; use libp2p::identity;
use pem::{encode, Pem}; use pem::{encode, Pem};
use rand::prelude::*; use rand::prelude::*;
use std::{ use std::ffi::OsStr;
ffi::OsStr, use std::fmt;
fmt, use std::fs::{self, File};
fs::{self, File}, use std::io::{self, Write};
io::{self, Write}, use std::path::{Path, PathBuf};
path::{Path, PathBuf},
};
pub const SEED_LENGTH: usize = 32; pub const SEED_LENGTH: usize = 32;

@ -2,7 +2,8 @@
//! HTTP-API. //! HTTP-API.
use libp2p::PeerId; use libp2p::PeerId;
use serde::{de::Error, Deserialize, Deserializer, Serializer}; use serde::de::Error;
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S>(peer_id: &PeerId, serializer: S) -> Result<S::Ok, S::Error> pub fn serialize<S>(peer_id: &PeerId, serializer: S) -> Result<S::Ok, S::Error>
where where

@ -1,8 +1,8 @@
use anyhow::Result; use anyhow::Result;
use atty::{self};
use tracing::{info, subscriber}; use tracing::{info, subscriber};
use tracing_log::LogTracer; 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<()> { pub fn init_tracing(level: LevelFilter) -> Result<()> {
if level == LevelFilter::OFF { if level == LevelFilter::OFF {

@ -1,7 +1,9 @@
pub mod testutils; pub mod testutils;
use swap::protocol::{bob, bob::BobState}; use swap::protocol::bob;
use testutils::{bob_run_until::is_btc_locked, FastCancelConfig}; use swap::protocol::bob::BobState;
use testutils::bob_run_until::is_btc_locked;
use testutils::FastCancelConfig;
#[tokio::test] #[tokio::test]
async fn given_bob_manually_refunds_after_btc_locked_bob_refunds() { async fn given_bob_manually_refunds_after_btc_locked_bob_refunds() {

@ -1,8 +1,10 @@
pub mod testutils; pub mod testutils;
use bob::cancel::CancelError; use bob::cancel::CancelError;
use swap::protocol::{bob, bob::BobState}; use swap::protocol::bob;
use testutils::{bob_run_until::is_btc_locked, SlowCancelConfig}; use swap::protocol::bob::BobState;
use testutils::bob_run_until::is_btc_locked;
use testutils::SlowCancelConfig;
#[tokio::test] #[tokio::test]
async fn given_bob_manually_cancels_when_timelock_not_expired_errors() { async fn given_bob_manually_cancels_when_timelock_not_expired_errors() {

@ -1,7 +1,9 @@
pub mod testutils; pub mod testutils;
use swap::protocol::{bob, bob::BobState}; use swap::protocol::bob;
use testutils::{bob_run_until::is_btc_locked, SlowCancelConfig}; use swap::protocol::bob::BobState;
use testutils::bob_run_until::is_btc_locked;
use testutils::SlowCancelConfig;
#[tokio::test] #[tokio::test]
async fn given_bob_manually_forces_cancel_when_timelock_not_expired_errors() { async fn given_bob_manually_forces_cancel_when_timelock_not_expired_errors() {

@ -1,7 +1,9 @@
pub mod testutils; pub mod testutils;
use swap::protocol::{bob, bob::BobState}; use swap::protocol::bob;
use testutils::{bob_run_until::is_xmr_locked, SlowCancelConfig}; use swap::protocol::bob::BobState;
use testutils::bob_run_until::is_xmr_locked;
use testutils::SlowCancelConfig;
#[tokio::test] #[tokio::test]
async fn given_bob_restarts_after_xmr_is_locked_resume_swap() { async fn given_bob_restarts_after_xmr_is_locked_resume_swap() {

@ -1,8 +1,6 @@
use std::collections::HashMap; use std::collections::HashMap;
use testcontainers::{ use testcontainers::core::{Container, Docker, WaitForMessage};
core::{Container, Docker, WaitForMessage}, use testcontainers::Image;
Image,
};
pub const RPC_USER: &str = "admin"; pub const RPC_USER: &str = "admin";
pub const RPC_PASSWORD: &str = "123"; pub const RPC_PASSWORD: &str = "123";

@ -1,10 +1,8 @@
use crate::testutils::bitcoind; use crate::testutils::bitcoind;
use bitcoin::Network; use bitcoin::Network;
use std::collections::HashMap; use std::collections::HashMap;
use testcontainers::{ use testcontainers::core::{Container, Docker, WaitForMessage};
core::{Container, Docker, WaitForMessage}, use testcontainers::Image;
Image,
};
pub const HTTP_PORT: u16 = 60401; pub const HTTP_PORT: u16 = 60401;
pub const RPC_PORT: u16 = 3002; pub const RPC_PORT: u16 = 3002;

@ -4,30 +4,32 @@ mod electrs;
use crate::testutils; use crate::testutils;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use bitcoin_harness::{BitcoindRpcApi, Client}; use bitcoin_harness::{BitcoindRpcApi, Client};
use futures::{future::RemoteHandle, Future}; use futures::future::RemoteHandle;
use futures::Future;
use get_port::get_port; use get_port::get_port;
use libp2p::{core::Multiaddr, PeerId}; use libp2p::core::Multiaddr;
use libp2p::PeerId;
use monero_harness::{image, Monero}; use monero_harness::{image, Monero};
use std::{ use std::convert::Infallible;
convert::Infallible, use std::path::{Path, PathBuf};
path::{Path, PathBuf}, use std::sync::Arc;
sync::Arc, use std::time::Duration;
time::Duration, use swap::asb::fixed_rate;
}; use swap::asb::fixed_rate::RATE;
use swap::{ use swap::bitcoin::{CancelTimelock, PunishTimelock};
asb::{fixed_rate, fixed_rate::RATE}, use swap::database::Database;
bitcoin, use swap::execution_params::{ExecutionParams, GetExecutionParams};
bitcoin::{CancelTimelock, PunishTimelock}, use swap::protocol::alice::AliceState;
database::Database, use swap::protocol::bob::BobState;
execution_params, use swap::protocol::{alice, bob};
execution_params::{ExecutionParams, GetExecutionParams}, use swap::seed::Seed;
monero, use swap::{bitcoin, execution_params, monero};
protocol::{alice, alice::AliceState, bob, bob::BobState},
seed::Seed,
};
use tempfile::tempdir; use tempfile::tempdir;
use testcontainers::{clients::Cli, Container, Docker, RunArgs}; use testcontainers::clients::Cli;
use tokio::{sync::mpsc, task::JoinHandle, time::interval}; use testcontainers::{Container, Docker, RunArgs};
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio::time::interval;
use tracing::dispatcher::DefaultGuard; use tracing::dispatcher::DefaultGuard;
use tracing_log::LogTracer; use tracing_log::LogTracer;
use url::Url; use url::Url;
@ -445,7 +447,8 @@ where
} }
fn random_prefix() -> String { fn random_prefix() -> String {
use rand::{distributions::Alphanumeric, thread_rng, Rng}; use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use std::iter; use std::iter;
const LEN: usize = 8; const LEN: usize = 8;
let mut rng = thread_rng(); let mut rng = thread_rng();

Loading…
Cancel
Save