From 081237bb6f0e5269c577df9ea6a51a18f1ce0d26 Mon Sep 17 00:00:00 2001 From: Franck Royer Date: Thu, 4 Feb 2021 11:39:15 +1100 Subject: [PATCH] Remove unused behaviours --- swap/src/protocol/alice.rs | 100 +++-------------- swap/src/protocol/alice/event_loop.rs | 91 ---------------- swap/src/protocol/alice/execution_setup.rs | 21 ++++ swap/src/protocol/alice/message0.rs | 119 --------------------- swap/src/protocol/alice/message1.rs | 117 -------------------- swap/src/protocol/alice/message2.rs | 104 ------------------ swap/src/protocol/bob.rs | 59 +--------- swap/src/protocol/bob/event_loop.rs | 81 +------------- swap/src/protocol/bob/execution_setup.rs | 23 ++++ swap/src/protocol/bob/message0.rs | 110 ------------------- swap/src/protocol/bob/message1.rs | 105 ------------------ swap/src/protocol/bob/message2.rs | 103 ------------------ 12 files changed, 60 insertions(+), 973 deletions(-) delete mode 100644 swap/src/protocol/alice/message0.rs delete mode 100644 swap/src/protocol/alice/message1.rs delete mode 100644 swap/src/protocol/alice/message2.rs delete mode 100644 swap/src/protocol/bob/message0.rs delete mode 100644 swap/src/protocol/bob/message1.rs delete mode 100644 swap/src/protocol/bob/message2.rs diff --git a/swap/src/protocol/alice.rs b/swap/src/protocol/alice.rs index b1585fc2..0f700f87 100644 --- a/swap/src/protocol/alice.rs +++ b/swap/src/protocol/alice.rs @@ -1,14 +1,5 @@ //! Run an XMR/BTC swap in the role of Alice. //! Alice holds XMR and wishes receive BTC. -pub use self::{ - event_loop::{EventLoop, EventLoopHandle}, - message0::Message0, - message1::Message1, - state::*, - swap::{run, run_until}, - swap_response::*, - transfer_proof::TransferProof, -}; use crate::{ bitcoin, database, database::Database, @@ -20,7 +11,7 @@ use crate::{ transport::build, Seed as NetworkSeed, }, - protocol::{bob, bob::EncryptedSignature, SwapAmounts}, + protocol::{bob::EncryptedSignature, SwapAmounts}, seed::Seed, }; use anyhow::{bail, Result}; @@ -32,12 +23,19 @@ use std::{path::PathBuf, sync::Arc}; use tracing::{debug, info}; use uuid::Uuid; +pub use self::{ + event_loop::{EventLoop, EventLoopHandle}, + execution_setup::Message0, + state::*, + swap::{run, run_until}, + swap_response::*, + transfer_proof::TransferProof, +}; +pub use execution_setup::Message1; + mod encrypted_signature; pub mod event_loop; mod execution_setup; -mod message0; -mod message1; -mod message2; pub mod state; mod steps; pub mod swap; @@ -220,23 +218,7 @@ impl Builder { #[derive(Debug)] pub enum OutEvent { ConnectionEstablished(PeerId), - // TODO (Franck): Change this to get both amounts so parties can verify the amounts are - // expected early on. - Request(Box), /* Not-uniform with Bob on purpose, ready for adding - * Xmr - * event. */ - Message0 { - msg: Box, - channel: ResponseChannel, - }, - Message1 { - msg: Box, - channel: ResponseChannel, - }, - Message2 { - msg: Box, - bob_peer_id: PeerId, - }, + Request(Box), ExecutionSetupDone(Result>), TransferProofAcknowledged, EncryptedSignature(Box), @@ -258,39 +240,6 @@ impl From for OutEvent { } } -impl From for OutEvent { - fn from(event: message0::OutEvent) -> Self { - match event { - message0::OutEvent::Msg { channel, msg } => OutEvent::Message0 { - msg: Box::new(msg), - channel, - }, - } - } -} - -impl From for OutEvent { - fn from(event: message1::OutEvent) -> Self { - match event { - message1::OutEvent::Msg { msg, channel } => OutEvent::Message1 { - msg: Box::new(msg), - channel, - }, - } - } -} - -impl From for OutEvent { - fn from(event: message2::OutEvent) -> Self { - match event { - message2::OutEvent::Msg { msg, bob_peer_id } => OutEvent::Message2 { - msg: Box::new(msg), - bob_peer_id, - }, - } - } -} - impl From for OutEvent { fn from(event: execution_setup::OutEvent) -> Self { match event { @@ -322,9 +271,6 @@ impl From for OutEvent { pub struct Behaviour { pt: PeerTracker, amounts: swap_response::Behaviour, - message0: message0::Behaviour, - message1: message1::Behaviour, - message2: message2::Behaviour, execution_setup: execution_setup::Behaviour, transfer_proof: transfer_proof::Behaviour, encrypted_signature: encrypted_signature::Behaviour, @@ -347,28 +293,6 @@ impl Behaviour { info!("Start execution setup with {}", bob_peer_id); } - /// Send Message0 to Bob in response to receiving his Message0. - pub fn send_message0( - &mut self, - channel: ResponseChannel, - msg: Message0, - ) -> Result<()> { - self.message0.send(channel, msg)?; - debug!("Sent Message0"); - Ok(()) - } - - /// Send Message1 to Bob in response to receiving his Message1. - pub fn send_message1( - &mut self, - channel: ResponseChannel, - msg: Message1, - ) -> Result<()> { - self.message1.send(channel, msg)?; - debug!("Sent Message1"); - Ok(()) - } - /// Send Transfer Proof to Bob. pub fn send_transfer_proof(&mut self, bob: PeerId, msg: TransferProof) { self.transfer_proof.send(bob, msg); diff --git a/swap/src/protocol/alice/event_loop.rs b/swap/src/protocol/alice/event_loop.rs index bc2bea31..12858179 100644 --- a/swap/src/protocol/alice/event_loop.rs +++ b/swap/src/protocol/alice/event_loop.rs @@ -1,9 +1,7 @@ use crate::{ network::{request_response::AliceToBob, transport::SwapTransport, TokioExecutor}, protocol::{ - alice, alice::{Behaviour, OutEvent, State0, State3, SwapResponse, TransferProof}, - bob, bob::EncryptedSignature, }, }; @@ -35,17 +33,12 @@ impl Default for Channels { #[derive(Debug)] pub struct EventLoopHandle { - recv_message0: Receiver<(bob::Message0, ResponseChannel)>, - recv_message1: Receiver<(bob::Message1, ResponseChannel)>, - recv_message2: Receiver, done_execution_setup: Receiver>, recv_encrypted_signature: Receiver, request: Receiver, conn_established: Receiver, send_swap_response: Sender<(ResponseChannel, SwapResponse)>, start_execution_setup: Sender<(PeerId, State0)>, - send_message0: Sender<(ResponseChannel, alice::Message0)>, - send_message1: Sender<(ResponseChannel, alice::Message1)>, send_transfer_proof: Sender<(PeerId, TransferProof)>, recv_transfer_proof_ack: Receiver<()>, } @@ -58,27 +51,6 @@ impl EventLoopHandle { .ok_or_else(|| anyhow!("Failed to receive connection established from Bob")) } - pub async fn recv_message0(&mut self) -> Result<(bob::Message0, ResponseChannel)> { - self.recv_message0 - .recv() - .await - .ok_or_else(|| anyhow!("Failed to receive message 0 from Bob")) - } - - pub async fn recv_message1(&mut self) -> Result<(bob::Message1, ResponseChannel)> { - self.recv_message1 - .recv() - .await - .ok_or_else(|| anyhow!("Failed to receive message 1 from Bob")) - } - - pub async fn recv_message2(&mut self) -> Result { - self.recv_message2 - .recv() - .await - .ok_or_else(|| anyhow!("Failed to receive message 2 from Bob")) - } - pub async fn execution_setup(&mut self, bob_peer_id: PeerId, state0: State0) -> Result { let _ = self .start_execution_setup @@ -119,24 +91,6 @@ impl EventLoopHandle { Ok(()) } - pub async fn send_message0( - &mut self, - channel: ResponseChannel, - msg: alice::Message0, - ) -> Result<()> { - let _ = self.send_message0.send((channel, msg)).await?; - Ok(()) - } - - pub async fn send_message1( - &mut self, - channel: ResponseChannel, - msg: alice::Message1, - ) -> Result<()> { - let _ = self.send_message1.send((channel, msg)).await?; - Ok(()) - } - pub async fn send_transfer_proof(&mut self, bob: PeerId, msg: TransferProof) -> Result<()> { let _ = self.send_transfer_proof.send((bob, msg)).await?; @@ -151,17 +105,12 @@ impl EventLoopHandle { #[allow(missing_debug_implementations)] pub struct EventLoop { swarm: libp2p::Swarm, - recv_message0: Sender<(bob::Message0, ResponseChannel)>, - recv_message1: Sender<(bob::Message1, ResponseChannel)>, - recv_message2: Sender, start_execution_setup: Receiver<(PeerId, State0)>, done_execution_setup: Sender>, recv_encrypted_signature: Sender, request: Sender, conn_established: Sender, send_swap_response: Receiver<(ResponseChannel, SwapResponse)>, - send_message0: Receiver<(ResponseChannel, alice::Message0)>, - send_message1: Receiver<(ResponseChannel, alice::Message1)>, send_transfer_proof: Receiver<(PeerId, TransferProof)>, recv_transfer_proof_ack: Sender<()>, } @@ -182,49 +131,34 @@ impl EventLoop { Swarm::listen_on(&mut swarm, listen.clone()) .with_context(|| format!("Address is not supported: {:#}", listen))?; - let recv_message0 = Channels::new(); - let recv_message1 = Channels::new(); - let recv_message2 = Channels::new(); let start_execution_setup = Channels::new(); let done_execution_setup = Channels::new(); let recv_encrypted_signature = Channels::new(); let request = Channels::new(); let conn_established = Channels::new(); let send_swap_response = Channels::new(); - let send_message0 = Channels::new(); - let send_message1 = Channels::new(); let send_transfer_proof = Channels::new(); let recv_transfer_proof_ack = Channels::new(); let driver = EventLoop { swarm, - recv_message0: recv_message0.sender, - recv_message1: recv_message1.sender, - recv_message2: recv_message2.sender, start_execution_setup: start_execution_setup.receiver, done_execution_setup: done_execution_setup.sender, recv_encrypted_signature: recv_encrypted_signature.sender, request: request.sender, conn_established: conn_established.sender, send_swap_response: send_swap_response.receiver, - send_message0: send_message0.receiver, - send_message1: send_message1.receiver, send_transfer_proof: send_transfer_proof.receiver, recv_transfer_proof_ack: recv_transfer_proof_ack.sender, }; let handle = EventLoopHandle { - recv_message0: recv_message0.receiver, - recv_message1: recv_message1.receiver, - recv_message2: recv_message2.receiver, start_execution_setup: start_execution_setup.sender, done_execution_setup: done_execution_setup.receiver, recv_encrypted_signature: recv_encrypted_signature.receiver, request: request.receiver, conn_established: conn_established.receiver, send_swap_response: send_swap_response.sender, - send_message0: send_message0.sender, - send_message1: send_message1.sender, send_transfer_proof: send_transfer_proof.sender, recv_transfer_proof_ack: recv_transfer_proof_ack.receiver, }; @@ -240,15 +174,6 @@ impl EventLoop { OutEvent::ConnectionEstablished(alice) => { let _ = self.conn_established.send(alice).await; } - OutEvent::Message0 { msg, channel } => { - let _ = self.recv_message0.send((*msg, channel)).await; - } - OutEvent::Message1 { msg, channel } => { - let _ = self.recv_message1.send((*msg, channel)).await; - } - OutEvent::Message2 { msg, bob_peer_id : _} => { - let _ = self.recv_message2.send(*msg).await; - } OutEvent::ExecutionSetupDone(res) => { let _ = self.done_execution_setup.send(res.map(|state|*state)).await; } @@ -279,22 +204,6 @@ impl EventLoop { .start_execution_setup(bob_peer_id, state0); } }, - msg0 = self.send_message0.recv().fuse() => { - if let Some((channel, msg)) = msg0 { - let _ = self - .swarm - .send_message0(channel, msg) - .map_err(|err|error!("Failed to send message0: {:#}", err)); - } - }, - msg1 = self.send_message1.recv().fuse() => { - if let Some((channel, msg)) = msg1 { - let _ = self - .swarm - .send_message1(channel, msg) - .map_err(|err|error!("Failed to send message1: {:#}", err)); - } - }, transfer_proof = self.send_transfer_proof.recv().fuse() => { if let Some((bob_peer_id, msg)) = transfer_proof { self.swarm.send_transfer_proof(bob_peer_id, msg); diff --git a/swap/src/protocol/alice/execution_setup.rs b/swap/src/protocol/alice/execution_setup.rs index 8360c1de..d8673448 100644 --- a/swap/src/protocol/alice/execution_setup.rs +++ b/swap/src/protocol/alice/execution_setup.rs @@ -1,4 +1,7 @@ use crate::{ + bitcoin, + bitcoin::{EncryptedSignature, Signature}, + monero, network::request_response::BUF_SIZE, protocol::{ alice::{State0, State3}, @@ -8,6 +11,24 @@ use crate::{ use anyhow::{Context, Error, Result}; use libp2p::PeerId; use libp2p_async_await::BehaviourOutEvent; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Message0 { + pub(crate) A: bitcoin::PublicKey, + pub(crate) S_a_monero: monero::PublicKey, + pub(crate) S_a_bitcoin: bitcoin::PublicKey, + pub(crate) dleq_proof_s_a: cross_curve_dleq::Proof, + pub(crate) v_a: monero::PrivateViewKey, + pub(crate) redeem_address: bitcoin::Address, + pub(crate) punish_address: bitcoin::Address, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Message1 { + pub(crate) tx_cancel_sig: Signature, + pub(crate) tx_refund_encsig: EncryptedSignature, +} #[derive(Debug)] pub enum OutEvent { diff --git a/swap/src/protocol/alice/message0.rs b/swap/src/protocol/alice/message0.rs deleted file mode 100644 index a2c42304..00000000 --- a/swap/src/protocol/alice/message0.rs +++ /dev/null @@ -1,119 +0,0 @@ -use crate::{ - bitcoin, monero, - network::request_response::{AliceToBob, BobToAlice, Codec, Message0Protocol, TIMEOUT}, - protocol::bob, -}; -use anyhow::{anyhow, Result}; -use libp2p::{ - request_response::{ - handler::RequestProtocol, ProtocolSupport, RequestResponse, RequestResponseConfig, - RequestResponseEvent, RequestResponseMessage, ResponseChannel, - }, - swarm::{NetworkBehaviourAction, NetworkBehaviourEventProcess, PollParameters}, - NetworkBehaviour, -}; -use serde::{Deserialize, Serialize}; -use std::{ - collections::VecDeque, - task::{Context, Poll}, - time::Duration, -}; -use tracing::{debug, error}; - -#[derive(Debug)] -pub enum OutEvent { - Msg { - msg: bob::Message0, - channel: ResponseChannel, - }, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct Message0 { - pub(crate) A: bitcoin::PublicKey, - pub(crate) S_a_monero: monero::PublicKey, - pub(crate) S_a_bitcoin: bitcoin::PublicKey, - pub(crate) dleq_proof_s_a: cross_curve_dleq::Proof, - pub(crate) v_a: monero::PrivateViewKey, - pub(crate) redeem_address: bitcoin::Address, - pub(crate) punish_address: bitcoin::Address, -} - -/// A `NetworkBehaviour` that represents send/recv of message 0. -#[derive(NetworkBehaviour)] -#[behaviour(out_event = "OutEvent", poll_method = "poll")] -#[allow(missing_debug_implementations)] -pub struct Behaviour { - rr: RequestResponse>, - #[behaviour(ignore)] - events: VecDeque, -} - -impl Behaviour { - pub fn send(&mut self, channel: ResponseChannel, msg: Message0) -> Result<()> { - let msg = AliceToBob::Message0(Box::new(msg)); - self.rr - .send_response(channel, msg) - .map_err(|alice_to_bob| anyhow!("Could not send response {:?}", alice_to_bob)) - } - fn poll( - &mut self, - _: &mut Context<'_>, - _: &mut impl PollParameters, - ) -> Poll>, OutEvent>> { - if let Some(event) = self.events.pop_front() { - return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)); - } - - Poll::Pending - } -} - -impl Default for Behaviour { - fn default() -> Self { - let timeout = Duration::from_secs(TIMEOUT); - let mut config = RequestResponseConfig::default(); - config.set_request_timeout(timeout); - - Self { - rr: RequestResponse::new( - Codec::default(), - vec![(Message0Protocol, ProtocolSupport::Full)], - config, - ), - events: Default::default(), - } - } -} - -impl NetworkBehaviourEventProcess> for Behaviour { - fn inject_event(&mut self, event: RequestResponseEvent) { - match event { - RequestResponseEvent::Message { - message: - RequestResponseMessage::Request { - request, channel, .. - }, - .. - } => { - if let BobToAlice::Message0(msg) = request { - debug!("Received Message0"); - self.events.push_back(OutEvent::Msg { msg: *msg, channel }); - } - } - RequestResponseEvent::Message { - message: RequestResponseMessage::Response { .. }, - .. - } => panic!("Alice should not get a Response"), - RequestResponseEvent::InboundFailure { error, .. } => { - error!("Inbound failure: {:?}", error); - } - RequestResponseEvent::OutboundFailure { error, .. } => { - error!("Outbound failure: {:?}", error); - } - RequestResponseEvent::ResponseSent { .. } => { - debug!("Alice has sent Message0 as response to Bob"); - } - } - } -} diff --git a/swap/src/protocol/alice/message1.rs b/swap/src/protocol/alice/message1.rs deleted file mode 100644 index 94992b26..00000000 --- a/swap/src/protocol/alice/message1.rs +++ /dev/null @@ -1,117 +0,0 @@ -use crate::{ - network::request_response::{AliceToBob, BobToAlice, Codec, Message1Protocol, TIMEOUT}, - protocol::bob, -}; -use anyhow::{anyhow, Result}; -use ecdsa_fun::{adaptor::EncryptedSignature, Signature}; -use libp2p::{ - request_response::{ - handler::RequestProtocol, ProtocolSupport, RequestResponse, RequestResponseConfig, - RequestResponseEvent, RequestResponseMessage, ResponseChannel, - }, - swarm::{NetworkBehaviourAction, NetworkBehaviourEventProcess, PollParameters}, - NetworkBehaviour, -}; -use serde::{Deserialize, Serialize}; -use std::{ - collections::VecDeque, - task::{Context, Poll}, - time::Duration, -}; -use tracing::{debug, error}; - -#[derive(Debug)] -pub enum OutEvent { - Msg { - /// Received message from Bob. - msg: bob::Message1, - /// Channel to send back Alice's message 1. - channel: ResponseChannel, - }, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct Message1 { - pub(crate) tx_cancel_sig: Signature, - pub(crate) tx_refund_encsig: EncryptedSignature, -} - -/// A `NetworkBehaviour` that represents send/recv of message 1. -#[derive(NetworkBehaviour)] -#[behaviour(out_event = "OutEvent", poll_method = "poll")] -#[allow(missing_debug_implementations)] -pub struct Behaviour { - rr: RequestResponse>, - #[behaviour(ignore)] - events: VecDeque, -} - -impl Behaviour { - pub fn send(&mut self, channel: ResponseChannel, msg: Message1) -> Result<()> { - let msg = AliceToBob::Message1(Box::new(msg)); - self.rr - .send_response(channel, msg) - .map_err(|alice_to_bob| anyhow!("Could not send response {:?}", alice_to_bob)) - } - - fn poll( - &mut self, - _: &mut Context<'_>, - _: &mut impl PollParameters, - ) -> Poll>, OutEvent>> { - if let Some(event) = self.events.pop_front() { - return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)); - } - - Poll::Pending - } -} - -impl Default for Behaviour { - fn default() -> Self { - let timeout = Duration::from_secs(TIMEOUT); - let mut config = RequestResponseConfig::default(); - config.set_request_timeout(timeout); - - Self { - rr: RequestResponse::new( - Codec::default(), - vec![(Message1Protocol, ProtocolSupport::Full)], - config, - ), - events: Default::default(), - } - } -} - -impl NetworkBehaviourEventProcess> for Behaviour { - fn inject_event(&mut self, event: RequestResponseEvent) { - match event { - RequestResponseEvent::Message { - message: - RequestResponseMessage::Request { - request, channel, .. - }, - .. - } => { - if let BobToAlice::Message1(msg) = request { - debug!("Received Message1"); - self.events.push_back(OutEvent::Msg { msg: *msg, channel }); - } - } - RequestResponseEvent::Message { - message: RequestResponseMessage::Response { .. }, - .. - } => panic!("Alice should not get a Response"), - RequestResponseEvent::InboundFailure { error, .. } => { - error!("Inbound failure: {:?}", error); - } - RequestResponseEvent::OutboundFailure { error, .. } => { - error!("Outbound failure: {:?}", error); - } - RequestResponseEvent::ResponseSent { .. } => { - debug!("Alice has sent an Message1 response to Bob"); - } - } - } -} diff --git a/swap/src/protocol/alice/message2.rs b/swap/src/protocol/alice/message2.rs deleted file mode 100644 index b89065e3..00000000 --- a/swap/src/protocol/alice/message2.rs +++ /dev/null @@ -1,104 +0,0 @@ -use crate::{ - network::request_response::{AliceToBob, BobToAlice, Codec, Message2Protocol, TIMEOUT}, - protocol::bob, -}; -use libp2p::{ - request_response::{ - handler::RequestProtocol, ProtocolSupport, RequestResponse, RequestResponseConfig, - RequestResponseEvent, RequestResponseMessage, - }, - swarm::{NetworkBehaviourAction, NetworkBehaviourEventProcess, PollParameters}, - NetworkBehaviour, PeerId, -}; -use std::{ - collections::VecDeque, - task::{Context, Poll}, - time::Duration, -}; -use tracing::{debug, error}; - -#[derive(Debug)] -pub enum OutEvent { - Msg { - msg: bob::Message2, - bob_peer_id: PeerId, - }, -} - -/// A `NetworkBehaviour` that represents receiving of message 2 from Bob. -#[derive(NetworkBehaviour)] -#[behaviour(out_event = "OutEvent", poll_method = "poll")] -#[allow(missing_debug_implementations)] -pub struct Behaviour { - rr: RequestResponse>, - #[behaviour(ignore)] - events: VecDeque, -} - -impl Behaviour { - fn poll( - &mut self, - _: &mut Context<'_>, - _: &mut impl PollParameters, - ) -> Poll>, OutEvent>> { - if let Some(event) = self.events.pop_front() { - return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)); - } - - Poll::Pending - } -} - -impl Default for Behaviour { - fn default() -> Self { - let timeout = Duration::from_secs(TIMEOUT); - let mut config = RequestResponseConfig::default(); - config.set_request_timeout(timeout); - - Self { - rr: RequestResponse::new( - Codec::default(), - vec![(Message2Protocol, ProtocolSupport::Full)], - config, - ), - events: Default::default(), - } - } -} - -impl NetworkBehaviourEventProcess> for Behaviour { - fn inject_event(&mut self, event: RequestResponseEvent) { - match event { - RequestResponseEvent::Message { - peer, - message: - RequestResponseMessage::Request { - request, channel, .. - }, - } => { - if let BobToAlice::Message2(msg) = request { - debug!("Received Message 2"); - self.events.push_back(OutEvent::Msg { - msg: *msg, - bob_peer_id: peer, - }); - // Send back empty response so that the request/response protocol completes. - let _ = self.rr.send_response(channel, AliceToBob::Message2); - } - } - RequestResponseEvent::Message { - message: RequestResponseMessage::Response { .. }, - .. - } => panic!("Alice should not get a Response"), - RequestResponseEvent::InboundFailure { error, .. } => { - error!("Inbound failure: {:?}", error); - } - RequestResponseEvent::OutboundFailure { error, .. } => { - error!("Outbound failure: {:?}", error); - } - RequestResponseEvent::ResponseSent { .. } => { - debug!("Alice has sent a Message2 response to Bob"); - } - } - } -} diff --git a/swap/src/protocol/bob.rs b/swap/src/protocol/bob.rs index 8c7226c9..8e0ebd36 100644 --- a/swap/src/protocol/bob.rs +++ b/swap/src/protocol/bob.rs @@ -3,12 +3,13 @@ use crate::{ bitcoin, database, database::Database, + execution_params::ExecutionParams, monero, network, network::{ peer_tracker::{self, PeerTracker}, transport::build, }, - protocol::{alice, bob, SwapAmounts}, + protocol::{alice, alice::TransferProof, bob, SwapAmounts}, seed::Seed, }; use anyhow::{bail, Result}; @@ -21,21 +22,15 @@ use uuid::Uuid; pub use self::{ encrypted_signature::EncryptedSignature, event_loop::{EventLoop, EventLoopHandle}, - message0::Message0, - message1::Message1, - message2::Message2, state::*, swap::{run, run_until}, swap_request::*, }; -use crate::{execution_params::ExecutionParams, protocol::alice::TransferProof}; +pub use execution_setup::{Message0, Message1, Message2}; mod encrypted_signature; pub mod event_loop; mod execution_setup; -mod message0; -mod message1; -mod message2; pub mod state; pub mod swap; mod swap_request; @@ -210,9 +205,6 @@ impl Builder { pub enum OutEvent { ConnectionEstablished(PeerId), SwapResponse(alice::SwapResponse), - Message0(Box), - Message1(Box), - Message2, ExecutionSetupDone(Result>), TransferProof(Box), EncryptedSignatureAcknowledged, @@ -234,30 +226,6 @@ impl From for OutEvent { } } -impl From for OutEvent { - fn from(event: message0::OutEvent) -> Self { - match event { - message0::OutEvent::Msg(msg) => OutEvent::Message0(Box::new(msg)), - } - } -} - -impl From for OutEvent { - fn from(event: message1::OutEvent) -> Self { - match event { - message1::OutEvent::Msg(msg) => OutEvent::Message1(Box::new(msg)), - } - } -} - -impl From for OutEvent { - fn from(event: message2::OutEvent) -> Self { - match event { - message2::OutEvent::Msg => OutEvent::Message2, - } - } -} - impl From for OutEvent { fn from(event: execution_setup::OutEvent) -> Self { match event { @@ -289,9 +257,6 @@ impl From for OutEvent { pub struct Behaviour { pt: PeerTracker, swap_request: swap_request::Behaviour, - message0: message0::Behaviour, - message1: message1::Behaviour, - message2: message2::Behaviour, execution_setup: execution_setup::Behaviour, transfer_proof: transfer_proof::Behaviour, encrypted_signature: encrypted_signature::Behaviour, @@ -315,24 +280,6 @@ impl Behaviour { info!("Start execution setup with {}", alice_peer_id); } - /// Sends Bob's first message to Alice. - pub fn send_message0(&mut self, alice: PeerId, msg: bob::Message0) { - self.message0.send(alice, msg); - debug!("Message0 sent"); - } - - /// Sends Bob's second message to Alice. - pub fn send_message1(&mut self, alice: PeerId, msg: bob::Message1) { - self.message1.send(alice, msg); - debug!("Message1 sent"); - } - - /// Sends Bob's third message to Alice. - pub fn send_message2(&mut self, alice: PeerId, msg: bob::Message2) { - self.message2.send(alice, msg); - debug!("Message2 sent"); - } - /// Sends Bob's fourth message to Alice. pub fn send_encrypted_signature( &mut self, diff --git a/swap/src/protocol/bob/event_loop.rs b/swap/src/protocol/bob/event_loop.rs index abc646b6..d86536a0 100644 --- a/swap/src/protocol/bob/event_loop.rs +++ b/swap/src/protocol/bob/event_loop.rs @@ -3,9 +3,8 @@ use crate::{ bitcoin::EncryptedSignature, network::{transport::SwapTransport, TokioExecutor}, protocol::{ - alice, alice::{SwapResponse, TransferProof}, - bob::{self, Behaviour, OutEvent, State0, State2, SwapRequest}, + bob::{Behaviour, OutEvent, State0, State2, SwapRequest}, }, }; use anyhow::{anyhow, Result}; @@ -37,17 +36,12 @@ impl Default for Channels { #[derive(Debug)] pub struct EventLoopHandle { recv_swap_response: Receiver, - recv_message0: Receiver, - recv_message1: Receiver, start_execution_setup: Sender, done_execution_setup: Receiver>, recv_transfer_proof: Receiver, conn_established: Receiver, dial_alice: Sender<()>, send_swap_request: Sender, - send_message0: Sender, - send_message1: Sender, - send_message2: Sender, send_encrypted_signature: Sender, recv_encrypted_signature_ack: Receiver<()>, } @@ -60,20 +54,6 @@ impl EventLoopHandle { .ok_or_else(|| anyhow!("Failed to receive swap response from Alice")) } - pub async fn recv_message0(&mut self) -> Result { - self.recv_message0 - .recv() - .await - .ok_or_else(|| anyhow!("Failed to receive message 0 from Alice")) - } - - pub async fn recv_message1(&mut self) -> Result { - self.recv_message1 - .recv() - .await - .ok_or_else(|| anyhow!("Failed to receive message 1 from Alice")) - } - pub async fn execution_setup(&mut self, state0: State0) -> Result { let _ = self.start_execution_setup.send(state0).await?; @@ -109,21 +89,6 @@ impl EventLoopHandle { Ok(()) } - pub async fn send_message0(&mut self, msg: bob::Message0) -> Result<()> { - let _ = self.send_message0.send(msg).await?; - Ok(()) - } - - pub async fn send_message1(&mut self, msg: bob::Message1) -> Result<()> { - let _ = self.send_message1.send(msg).await?; - Ok(()) - } - - pub async fn send_message2(&mut self, msg: bob::Message2) -> Result<()> { - let _ = self.send_message2.send(msg).await?; - Ok(()) - } - pub async fn send_encrypted_signature( &mut self, tx_redeem_encsig: EncryptedSignature, @@ -144,17 +109,12 @@ pub struct EventLoop { bitcoin_wallet: Arc, alice_peer_id: PeerId, recv_swap_response: Sender, - recv_message0: Sender, - recv_message1: Sender, start_execution_setup: Receiver, done_execution_setup: Sender>, recv_transfer_proof: Sender, dial_alice: Receiver<()>, conn_established: Sender, send_swap_request: Receiver, - send_message0: Receiver, - send_message1: Receiver, - send_message2: Receiver, send_encrypted_signature: Receiver, recv_encrypted_signature_ack: Sender<()>, } @@ -177,17 +137,12 @@ impl EventLoop { swarm.add_address(alice_peer_id, alice_addr); let swap_response = Channels::new(); - let recv_message0 = Channels::new(); - let recv_message1 = Channels::new(); let start_execution_setup = Channels::new(); let done_execution_setup = Channels::new(); let recv_transfer_proof = Channels::new(); let dial_alice = Channels::new(); let conn_established = Channels::new(); let send_swap_request = Channels::new(); - let send_message0 = Channels::new(); - let send_message1 = Channels::new(); - let send_message2 = Channels::new(); let send_encrypted_signature = Channels::new(); let recv_encrypted_signature_ack = Channels::new(); @@ -196,34 +151,24 @@ impl EventLoop { alice_peer_id, bitcoin_wallet, recv_swap_response: swap_response.sender, - recv_message0: recv_message0.sender, - recv_message1: recv_message1.sender, start_execution_setup: start_execution_setup.receiver, done_execution_setup: done_execution_setup.sender, recv_transfer_proof: recv_transfer_proof.sender, conn_established: conn_established.sender, dial_alice: dial_alice.receiver, send_swap_request: send_swap_request.receiver, - send_message0: send_message0.receiver, - send_message1: send_message1.receiver, - send_message2: send_message2.receiver, send_encrypted_signature: send_encrypted_signature.receiver, recv_encrypted_signature_ack: recv_encrypted_signature_ack.sender, }; let handle = EventLoopHandle { recv_swap_response: swap_response.receiver, - recv_message0: recv_message0.receiver, - recv_message1: recv_message1.receiver, start_execution_setup: start_execution_setup.sender, done_execution_setup: done_execution_setup.receiver, recv_transfer_proof: recv_transfer_proof.receiver, conn_established: conn_established.receiver, dial_alice: dial_alice.sender, send_swap_request: send_swap_request.sender, - send_message0: send_message0.sender, - send_message1: send_message1.sender, - send_message2: send_message2.sender, send_encrypted_signature: send_encrypted_signature.sender, recv_encrypted_signature_ack: recv_encrypted_signature_ack.receiver, }; @@ -242,13 +187,6 @@ impl EventLoop { OutEvent::SwapResponse(msg) => { let _ = self.recv_swap_response.send(msg).await; }, - OutEvent::Message0(msg) => { - let _ = self.recv_message0.send(*msg).await; - } - OutEvent::Message1(msg) => { - let _ = self.recv_message1.send(*msg).await; - } - OutEvent::Message2 => info!("Alice acknowledged message 2 received"), OutEvent::ExecutionSetupDone(res) => { let _ = self.done_execution_setup.send(res.map(|state|*state)).await; } @@ -282,23 +220,6 @@ impl EventLoop { self.swarm.send_swap_request(self.alice_peer_id, swap_request); } }, - - msg0 = self.send_message0.recv().fuse() => { - if let Some(msg) = msg0 { - self.swarm.send_message0(self.alice_peer_id, msg); - } - } - - msg1 = self.send_message1.recv().fuse() => { - if let Some(msg) = msg1 { - self.swarm.send_message1(self.alice_peer_id, msg); - } - }, - msg2 = self.send_message2.recv().fuse() => { - if let Some(msg) = msg2 { - self.swarm.send_message2(self.alice_peer_id, msg); - } - }, option = self.start_execution_setup.recv().fuse() => { if let Some(state0) = option { let _ = self diff --git a/swap/src/protocol/bob/execution_setup.rs b/swap/src/protocol/bob/execution_setup.rs index 3a0f3af0..d3eacac0 100644 --- a/swap/src/protocol/bob/execution_setup.rs +++ b/swap/src/protocol/bob/execution_setup.rs @@ -1,4 +1,5 @@ use crate::{ + bitcoin::Signature, network::request_response::BUF_SIZE, protocol::{ alice, @@ -8,8 +9,30 @@ use crate::{ use anyhow::{Context, Error, Result}; use libp2p::PeerId; use libp2p_async_await::BehaviourOutEvent; +use serde::{Deserialize, Serialize}; use std::sync::Arc; +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Message0 { + pub(crate) B: crate::bitcoin::PublicKey, + pub(crate) S_b_monero: monero::PublicKey, + pub(crate) S_b_bitcoin: crate::bitcoin::PublicKey, + pub(crate) dleq_proof_s_b: cross_curve_dleq::Proof, + pub(crate) v_b: crate::monero::PrivateViewKey, + pub(crate) refund_address: bitcoin::Address, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Message1 { + pub(crate) tx_lock: crate::bitcoin::TxLock, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Message2 { + pub(crate) tx_punish_sig: Signature, + pub(crate) tx_cancel_sig: Signature, +} + #[derive(Debug)] pub enum OutEvent { Done(Result), diff --git a/swap/src/protocol/bob/message0.rs b/swap/src/protocol/bob/message0.rs deleted file mode 100644 index 1903a62e..00000000 --- a/swap/src/protocol/bob/message0.rs +++ /dev/null @@ -1,110 +0,0 @@ -use crate::{ - bitcoin, monero, - network::request_response::{AliceToBob, BobToAlice, Codec, Message0Protocol, TIMEOUT}, - protocol::{alice, bob}, -}; -use libp2p::{ - request_response::{ - handler::RequestProtocol, ProtocolSupport, RequestResponse, RequestResponseConfig, - RequestResponseEvent, RequestResponseMessage, - }, - swarm::{NetworkBehaviourAction, NetworkBehaviourEventProcess, PollParameters}, - NetworkBehaviour, PeerId, -}; -use serde::{Deserialize, Serialize}; -use std::{ - collections::VecDeque, - task::{Context, Poll}, - time::Duration, -}; -use tracing::{debug, error}; - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct Message0 { - pub(crate) B: bitcoin::PublicKey, - pub(crate) S_b_monero: monero::PublicKey, - pub(crate) S_b_bitcoin: bitcoin::PublicKey, - pub(crate) dleq_proof_s_b: cross_curve_dleq::Proof, - pub(crate) v_b: monero::PrivateViewKey, - pub(crate) refund_address: bitcoin::Address, -} - -#[derive(Debug)] -pub enum OutEvent { - Msg(alice::Message0), -} - -/// A `NetworkBehaviour` that represents send/recv of message 0. -#[derive(NetworkBehaviour)] -#[behaviour(out_event = "OutEvent", poll_method = "poll")] -#[allow(missing_debug_implementations)] -pub struct Behaviour { - rr: RequestResponse>, - #[behaviour(ignore)] - events: VecDeque, -} - -impl Behaviour { - pub fn send(&mut self, alice: PeerId, msg: bob::Message0) { - let msg = BobToAlice::Message0(Box::new(msg)); - let _id = self.rr.send_request(&alice, msg); - } - - fn poll( - &mut self, - _: &mut Context<'_>, - _: &mut impl PollParameters, - ) -> Poll>, OutEvent>> { - if let Some(event) = self.events.pop_front() { - return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)); - } - - Poll::Pending - } -} - -impl Default for Behaviour { - fn default() -> Self { - let timeout = Duration::from_secs(TIMEOUT); - let mut config = RequestResponseConfig::default(); - config.set_request_timeout(timeout); - - Self { - rr: RequestResponse::new( - Codec::default(), - vec![(Message0Protocol, ProtocolSupport::Full)], - config, - ), - events: Default::default(), - } - } -} - -impl NetworkBehaviourEventProcess> for Behaviour { - fn inject_event(&mut self, event: RequestResponseEvent) { - match event { - RequestResponseEvent::Message { - message: RequestResponseMessage::Request { .. }, - .. - } => panic!("Bob should never get a request from Alice"), - RequestResponseEvent::Message { - message: RequestResponseMessage::Response { response, .. }, - .. - } => { - if let AliceToBob::Message0(msg) = response { - debug!("Received Message0"); - self.events.push_back(OutEvent::Msg(*msg)); - } - } - RequestResponseEvent::InboundFailure { error, .. } => { - error!("Inbound failure: {:?}", error); - } - RequestResponseEvent::OutboundFailure { error, .. } => { - error!("Outbound failure: {:?}", error); - } - RequestResponseEvent::ResponseSent { .. } => { - unreachable!("Bob does not send a message0 response to Alice"); - } - } - } -} diff --git a/swap/src/protocol/bob/message1.rs b/swap/src/protocol/bob/message1.rs deleted file mode 100644 index 4385ad54..00000000 --- a/swap/src/protocol/bob/message1.rs +++ /dev/null @@ -1,105 +0,0 @@ -use crate::{ - bitcoin, - network::request_response::{AliceToBob, BobToAlice, Codec, Message1Protocol, TIMEOUT}, - protocol::alice, -}; -use libp2p::{ - request_response::{ - handler::RequestProtocol, ProtocolSupport, RequestResponse, RequestResponseConfig, - RequestResponseEvent, RequestResponseMessage, - }, - swarm::{NetworkBehaviourAction, NetworkBehaviourEventProcess, PollParameters}, - NetworkBehaviour, PeerId, -}; -use serde::{Deserialize, Serialize}; -use std::{ - collections::VecDeque, - task::{Context, Poll}, - time::Duration, -}; -use tracing::{debug, error}; - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct Message1 { - pub(crate) tx_lock: bitcoin::TxLock, -} - -#[derive(Debug)] -pub enum OutEvent { - Msg(alice::Message1), -} - -/// A `NetworkBehaviour` that represents send/recv of message 1. -#[derive(NetworkBehaviour)] -#[behaviour(out_event = "OutEvent", poll_method = "poll")] -#[allow(missing_debug_implementations)] -pub struct Behaviour { - rr: RequestResponse>, - #[behaviour(ignore)] - events: VecDeque, -} - -impl Behaviour { - pub fn send(&mut self, alice: PeerId, msg: Message1) { - let msg = BobToAlice::Message1(Box::new(msg)); - let _id = self.rr.send_request(&alice, msg); - } - - fn poll( - &mut self, - _: &mut Context<'_>, - _: &mut impl PollParameters, - ) -> Poll>, OutEvent>> { - if let Some(event) = self.events.pop_front() { - return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)); - } - - Poll::Pending - } -} - -impl Default for Behaviour { - fn default() -> Self { - let timeout = Duration::from_secs(TIMEOUT); - let mut config = RequestResponseConfig::default(); - config.set_request_timeout(timeout); - - Self { - rr: RequestResponse::new( - Codec::default(), - vec![(Message1Protocol, ProtocolSupport::Full)], - config, - ), - events: Default::default(), - } - } -} - -impl NetworkBehaviourEventProcess> for Behaviour { - fn inject_event(&mut self, event: RequestResponseEvent) { - match event { - RequestResponseEvent::Message { - message: RequestResponseMessage::Request { .. }, - .. - } => panic!("Bob should never get a request from Alice"), - RequestResponseEvent::Message { - message: RequestResponseMessage::Response { response, .. }, - .. - } => { - if let AliceToBob::Message1(msg) = response { - debug!("Received Message1"); - self.events.push_back(OutEvent::Msg(*msg)); - } - } - RequestResponseEvent::InboundFailure { error, .. } => { - error!("Inbound failure: {:?}", error); - } - RequestResponseEvent::OutboundFailure { error, .. } => { - error!("Outbound failure: {:?}", error); - } - RequestResponseEvent::ResponseSent { .. } => { - unreachable!("Bob does not send a message 1 response to Alice"); - } - } - } -} diff --git a/swap/src/protocol/bob/message2.rs b/swap/src/protocol/bob/message2.rs deleted file mode 100644 index c767fd8b..00000000 --- a/swap/src/protocol/bob/message2.rs +++ /dev/null @@ -1,103 +0,0 @@ -use crate::network::request_response::{AliceToBob, BobToAlice, Codec, Message2Protocol, TIMEOUT}; -use ecdsa_fun::Signature; -use libp2p::{ - request_response::{ - handler::RequestProtocol, ProtocolSupport, RequestResponse, RequestResponseConfig, - RequestResponseEvent, RequestResponseMessage, - }, - swarm::{NetworkBehaviourAction, NetworkBehaviourEventProcess, PollParameters}, - NetworkBehaviour, PeerId, -}; -use serde::{Deserialize, Serialize}; -use std::{ - collections::VecDeque, - task::{Context, Poll}, - time::Duration, -}; -use tracing::{debug, error}; - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct Message2 { - pub(crate) tx_punish_sig: Signature, - pub(crate) tx_cancel_sig: Signature, -} - -#[derive(Clone, Copy, Debug)] -pub enum OutEvent { - Msg, -} - -/// A `NetworkBehaviour` that represents sending message 2 to Alice. -#[derive(NetworkBehaviour)] -#[behaviour(out_event = "OutEvent", poll_method = "poll")] -#[allow(missing_debug_implementations)] -pub struct Behaviour { - rr: RequestResponse>, - #[behaviour(ignore)] - events: VecDeque, -} - -impl Behaviour { - pub fn send(&mut self, alice: PeerId, msg: Message2) { - let msg = BobToAlice::Message2(Box::new(msg)); - let _id = self.rr.send_request(&alice, msg); - } - - fn poll( - &mut self, - _: &mut Context<'_>, - _: &mut impl PollParameters, - ) -> Poll>, OutEvent>> { - if let Some(event) = self.events.pop_front() { - return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)); - } - - Poll::Pending - } -} - -impl Default for Behaviour { - fn default() -> Self { - let timeout = Duration::from_secs(TIMEOUT); - let mut config = RequestResponseConfig::default(); - config.set_request_timeout(timeout); - - Self { - rr: RequestResponse::new( - Codec::default(), - vec![(Message2Protocol, ProtocolSupport::Full)], - config, - ), - events: VecDeque::default(), - } - } -} - -impl NetworkBehaviourEventProcess> for Behaviour { - fn inject_event(&mut self, event: RequestResponseEvent) { - match event { - RequestResponseEvent::Message { - message: RequestResponseMessage::Request { .. }, - .. - } => panic!("Bob should never get a request from Alice"), - RequestResponseEvent::Message { - message: RequestResponseMessage::Response { response, .. }, - .. - } => { - if let AliceToBob::Message2 = response { - debug!("Received Message 2 acknowledgement"); - self.events.push_back(OutEvent::Msg); - } - } - RequestResponseEvent::InboundFailure { error, .. } => { - error!("Inbound failure: {:?}", error); - } - RequestResponseEvent::OutboundFailure { error, .. } => { - error!("Outbound failure: {:?}", error); - } - RequestResponseEvent::ResponseSent { .. } => { - unreachable!("Bob does not send a Message2 response to Alice"); - } - } - } -}