Remove dead code and combine swap request & one shot codecs

This commit is contained in:
Franck Royer 2021-02-04 12:29:28 +11:00
parent fc2d8d3861
commit cfc5cb5206
No known key found for this signature in database
GPG Key ID: A82ED75A8DFC50A4
5 changed files with 30 additions and 167 deletions

View File

@ -1,8 +1,6 @@
use crate::protocol::{ use crate::protocol::{
alice, alice::{SwapResponse, TransferProof},
alice::{Message1, Message3, TransferProof}, bob::{EncryptedSignature, SwapRequest},
bob,
bob::{EncryptedSignature, Message0, Message2, Message4},
}; };
use async_trait::async_trait; use async_trait::async_trait;
use futures::prelude::*; use futures::prelude::*;
@ -19,38 +17,16 @@ pub const TIMEOUT: u64 = 3600; // One hour.
/// Message receive buffer. /// Message receive buffer.
pub const BUF_SIZE: usize = 1024 * 1024; pub const BUF_SIZE: usize = 1024 * 1024;
// TODO: Think about whether there is a better way to do this, e.g., separate
// Codec for each Message and a macro that implements them.
/// Messages Bob sends to Alice.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum BobToAlice {
SwapRequest(Box<bob::SwapRequest>),
Message0(Box<Message0>),
Message2(Box<Message2>),
Message4(Box<Message4>),
}
/// Messages Alice sends to Bob.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum AliceToBob {
SwapResponse(Box<alice::SwapResponse>),
Message1(Box<Message1>),
Message3(Box<Message3>),
Message2,
}
/// Messages sent from one party to the other.
/// All responses are empty
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Request { pub enum Request {
SwapRequest(Box<SwapRequest>),
TransferProof(Box<TransferProof>), TransferProof(Box<TransferProof>),
EncryptedSignature(Box<EncryptedSignature>), EncryptedSignature(Box<EncryptedSignature>),
} }
#[derive(Clone, Copy, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
/// Response are only used for acknowledgement purposes.
pub enum Response { pub enum Response {
SwapResponse(Box<SwapResponse>),
TransferProof, TransferProof,
EncryptedSignature, EncryptedSignature,
} }
@ -58,15 +34,6 @@ pub enum Response {
#[derive(Debug, Clone, Copy, Default)] #[derive(Debug, Clone, Copy, Default)]
pub struct Swap; pub struct Swap;
#[derive(Debug, Clone, Copy, Default)]
pub struct Message0Protocol;
#[derive(Debug, Clone, Copy, Default)]
pub struct Message1Protocol;
#[derive(Debug, Clone, Copy, Default)]
pub struct Message2Protocol;
#[derive(Debug, Clone, Copy, Default)] #[derive(Debug, Clone, Copy, Default)]
pub struct TransferProofProtocol; pub struct TransferProofProtocol;
@ -79,24 +46,6 @@ impl ProtocolName for Swap {
} }
} }
impl ProtocolName for Message0Protocol {
fn protocol_name(&self) -> &[u8] {
b"/xmr/btc/message0/1.0.0"
}
}
impl ProtocolName for Message1Protocol {
fn protocol_name(&self) -> &[u8] {
b"/xmr/btc/message1/1.0.0"
}
}
impl ProtocolName for Message2Protocol {
fn protocol_name(&self) -> &[u8] {
b"/xmr/btc/message2/1.0.0"
}
}
impl ProtocolName for TransferProofProtocol { impl ProtocolName for TransferProofProtocol {
fn protocol_name(&self) -> &[u8] { fn protocol_name(&self) -> &[u8] {
b"/xmr/btc/transfer_proof/1.0.0" b"/xmr/btc/transfer_proof/1.0.0"
@ -109,92 +58,6 @@ impl ProtocolName for EncryptedSignatureProtocol {
} }
} }
#[derive(Clone, Copy, Debug, Default)]
pub struct Codec<P> {
phantom: PhantomData<P>,
}
#[async_trait]
impl<P> RequestResponseCodec for Codec<P>
where
P: Send + Sync + Clone + ProtocolName,
{
type Protocol = P;
type Request = BobToAlice;
type Response = AliceToBob;
async fn read_request<T>(&mut self, _: &Self::Protocol, io: &mut T) -> io::Result<Self::Request>
where
T: AsyncRead + Unpin + Send,
{
let message = upgrade::read_one(io, BUF_SIZE)
.await
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let mut de = serde_cbor::Deserializer::from_slice(&message);
let msg = BobToAlice::deserialize(&mut de).map_err(|e| {
tracing::debug!("serde read_request error: {:?}", e);
io::Error::new(io::ErrorKind::Other, e)
})?;
Ok(msg)
}
async fn read_response<T>(
&mut self,
_: &Self::Protocol,
io: &mut T,
) -> io::Result<Self::Response>
where
T: AsyncRead + Unpin + Send,
{
let message = upgrade::read_one(io, BUF_SIZE)
.await
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let mut de = serde_cbor::Deserializer::from_slice(&message);
let msg = AliceToBob::deserialize(&mut de).map_err(|e| {
tracing::debug!("serde read_response error: {:?}", e);
io::Error::new(io::ErrorKind::InvalidData, e)
})?;
Ok(msg)
}
async fn write_request<T>(
&mut self,
_: &Self::Protocol,
io: &mut T,
req: Self::Request,
) -> io::Result<()>
where
T: AsyncWrite + Unpin + Send,
{
let bytes =
serde_cbor::to_vec(&req).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
upgrade::write_one(io, &bytes).await?;
Ok(())
}
async fn write_response<T>(
&mut self,
_: &Self::Protocol,
io: &mut T,
res: Self::Response,
) -> io::Result<()>
where
T: AsyncWrite + Unpin + Send,
{
let bytes = serde_cbor::to_vec(&res).map_err(|e| {
tracing::debug!("serde write_reponse error: {:?}", e);
io::Error::new(io::ErrorKind::InvalidData, e)
})?;
upgrade::write_one(io, &bytes).await?;
Ok(())
}
}
#[derive(Clone, Copy, Debug, Default)] #[derive(Clone, Copy, Debug, Default)]
pub struct OneShotCodec<P> { pub struct OneShotCodec<P> {
phantom: PhantomData<P>, phantom: PhantomData<P>,

View File

@ -7,7 +7,6 @@ use crate::{
monero, monero,
network::{ network::{
peer_tracker::{self, PeerTracker}, peer_tracker::{self, PeerTracker},
request_response::AliceToBob,
transport::build, transport::build,
Seed as NetworkSeed, Seed as NetworkSeed,
}, },
@ -31,6 +30,7 @@ pub use self::{
swap_response::*, swap_response::*,
transfer_proof::TransferProof, transfer_proof::TransferProof,
}; };
use crate::network::request_response::Response;
pub use execution_setup::Message3; pub use execution_setup::Message3;
mod encrypted_signature; mod encrypted_signature;
@ -280,7 +280,7 @@ impl Behaviour {
/// Alice always sends her messages as a response to a request from Bob. /// Alice always sends her messages as a response to a request from Bob.
pub fn send_swap_response( pub fn send_swap_response(
&mut self, &mut self,
channel: ResponseChannel<AliceToBob>, channel: ResponseChannel<Response>,
swap_response: SwapResponse, swap_response: SwapResponse,
) -> Result<()> { ) -> Result<()> {
self.amounts.send(channel, swap_response)?; self.amounts.send(channel, swap_response)?;

View File

@ -1,5 +1,5 @@
use crate::{ use crate::{
network::{request_response::AliceToBob, transport::SwapTransport, TokioExecutor}, network::{request_response::Response, transport::SwapTransport, TokioExecutor},
protocol::{ protocol::{
alice::{Behaviour, OutEvent, State0, State3, SwapResponse, TransferProof}, alice::{Behaviour, OutEvent, State0, State3, SwapResponse, TransferProof},
bob::EncryptedSignature, bob::EncryptedSignature,
@ -37,7 +37,7 @@ pub struct EventLoopHandle {
recv_encrypted_signature: Receiver<EncryptedSignature>, recv_encrypted_signature: Receiver<EncryptedSignature>,
request: Receiver<crate::protocol::alice::swap_response::OutEvent>, request: Receiver<crate::protocol::alice::swap_response::OutEvent>,
conn_established: Receiver<PeerId>, conn_established: Receiver<PeerId>,
send_swap_response: Sender<(ResponseChannel<AliceToBob>, SwapResponse)>, send_swap_response: Sender<(ResponseChannel<Response>, SwapResponse)>,
start_execution_setup: Sender<(PeerId, State0)>, start_execution_setup: Sender<(PeerId, State0)>,
send_transfer_proof: Sender<(PeerId, TransferProof)>, send_transfer_proof: Sender<(PeerId, TransferProof)>,
recv_transfer_proof_ack: Receiver<()>, recv_transfer_proof_ack: Receiver<()>,
@ -81,7 +81,7 @@ impl EventLoopHandle {
pub async fn send_swap_response( pub async fn send_swap_response(
&mut self, &mut self,
channel: ResponseChannel<AliceToBob>, channel: ResponseChannel<Response>,
swap_response: SwapResponse, swap_response: SwapResponse,
) -> Result<()> { ) -> Result<()> {
let _ = self let _ = self
@ -110,7 +110,7 @@ pub struct EventLoop {
recv_encrypted_signature: Sender<EncryptedSignature>, recv_encrypted_signature: Sender<EncryptedSignature>,
request: Sender<crate::protocol::alice::swap_response::OutEvent>, request: Sender<crate::protocol::alice::swap_response::OutEvent>,
conn_established: Sender<PeerId>, conn_established: Sender<PeerId>,
send_swap_response: Receiver<(ResponseChannel<AliceToBob>, SwapResponse)>, send_swap_response: Receiver<(ResponseChannel<Response>, SwapResponse)>,
send_transfer_proof: Receiver<(PeerId, TransferProof)>, send_transfer_proof: Receiver<(PeerId, TransferProof)>,
recv_transfer_proof_ack: Sender<()>, recv_transfer_proof_ack: Sender<()>,
} }

View File

@ -1,6 +1,6 @@
use crate::{ use crate::{
monero, monero,
network::request_response::{AliceToBob, BobToAlice, Codec, Swap, TIMEOUT}, network::request_response::{OneShotCodec, Request, Response, Swap, TIMEOUT},
protocol::bob, protocol::bob,
}; };
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
@ -23,7 +23,7 @@ use tracing::{debug, error};
#[derive(Debug)] #[derive(Debug)]
pub struct OutEvent { pub struct OutEvent {
pub msg: bob::SwapRequest, pub msg: bob::SwapRequest,
pub channel: ResponseChannel<AliceToBob>, pub channel: ResponseChannel<Response>,
} }
#[derive(Copy, Clone, Debug, Serialize, Deserialize)] #[derive(Copy, Clone, Debug, Serialize, Deserialize)]
@ -37,15 +37,15 @@ pub struct SwapResponse {
#[behaviour(out_event = "OutEvent", poll_method = "poll")] #[behaviour(out_event = "OutEvent", poll_method = "poll")]
#[allow(missing_debug_implementations)] #[allow(missing_debug_implementations)]
pub struct Behaviour { pub struct Behaviour {
rr: RequestResponse<Codec<Swap>>, rr: RequestResponse<OneShotCodec<Swap>>,
#[behaviour(ignore)] #[behaviour(ignore)]
events: VecDeque<OutEvent>, events: VecDeque<OutEvent>,
} }
impl Behaviour { impl Behaviour {
/// Alice always sends her messages as a response to a request from Bob. /// Alice always sends her messages as a response to a request from Bob.
pub fn send(&mut self, channel: ResponseChannel<AliceToBob>, msg: SwapResponse) -> Result<()> { pub fn send(&mut self, channel: ResponseChannel<Response>, msg: SwapResponse) -> Result<()> {
let msg = AliceToBob::SwapResponse(Box::new(msg)); let msg = Response::SwapResponse(Box::new(msg));
self.rr self.rr
.send_response(channel, msg) .send_response(channel, msg)
.map_err(|_| anyhow!("Sending swap response failed")) .map_err(|_| anyhow!("Sending swap response failed"))
@ -55,7 +55,7 @@ impl Behaviour {
&mut self, &mut self,
_: &mut Context<'_>, _: &mut Context<'_>,
_: &mut impl PollParameters, _: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<RequestProtocol<Codec<Swap>>, OutEvent>> { ) -> Poll<NetworkBehaviourAction<RequestProtocol<OneShotCodec<Swap>>, OutEvent>> {
if let Some(event) = self.events.pop_front() { if let Some(event) = self.events.pop_front() {
return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)); return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event));
} }
@ -73,8 +73,8 @@ impl Default for Behaviour {
Self { Self {
rr: RequestResponse::new( rr: RequestResponse::new(
Codec::default(), OneShotCodec::default(),
vec![(Swap, ProtocolSupport::Full)], vec![(Swap, ProtocolSupport::Inbound)],
config, config,
), ),
events: Default::default(), events: Default::default(),
@ -82,8 +82,8 @@ impl Default for Behaviour {
} }
} }
impl NetworkBehaviourEventProcess<RequestResponseEvent<BobToAlice, AliceToBob>> for Behaviour { impl NetworkBehaviourEventProcess<RequestResponseEvent<Request, Response>> for Behaviour {
fn inject_event(&mut self, event: RequestResponseEvent<BobToAlice, AliceToBob>) { fn inject_event(&mut self, event: RequestResponseEvent<Request, Response>) {
match event { match event {
RequestResponseEvent::Message { RequestResponseEvent::Message {
message: message:
@ -92,7 +92,7 @@ impl NetworkBehaviourEventProcess<RequestResponseEvent<BobToAlice, AliceToBob>>
}, },
.. ..
} => { } => {
if let BobToAlice::SwapRequest(msg) = request { if let Request::SwapRequest(msg) = request {
debug!("Received swap request"); debug!("Received swap request");
self.events.push_back(OutEvent { msg: *msg, channel }) self.events.push_back(OutEvent { msg: *msg, channel })
} }

View File

@ -1,5 +1,5 @@
use crate::{ use crate::{
network::request_response::{AliceToBob, BobToAlice, Codec, Swap, TIMEOUT}, network::request_response::{OneShotCodec, Request, Response, Swap, TIMEOUT},
protocol::alice::SwapResponse, protocol::alice::SwapResponse,
}; };
use anyhow::Result; use anyhow::Result;
@ -35,14 +35,14 @@ pub struct OutEvent {
#[behaviour(out_event = "OutEvent", poll_method = "poll")] #[behaviour(out_event = "OutEvent", poll_method = "poll")]
#[allow(missing_debug_implementations)] #[allow(missing_debug_implementations)]
pub struct Behaviour { pub struct Behaviour {
rr: RequestResponse<Codec<Swap>>, rr: RequestResponse<OneShotCodec<Swap>>,
#[behaviour(ignore)] #[behaviour(ignore)]
events: VecDeque<OutEvent>, events: VecDeque<OutEvent>,
} }
impl Behaviour { impl Behaviour {
pub fn send(&mut self, alice: PeerId, swap_request: SwapRequest) -> Result<RequestId> { pub fn send(&mut self, alice: PeerId, swap_request: SwapRequest) -> Result<RequestId> {
let msg = BobToAlice::SwapRequest(Box::new(swap_request)); let msg = Request::SwapRequest(Box::new(swap_request));
let id = self.rr.send_request(&alice, msg); let id = self.rr.send_request(&alice, msg);
Ok(id) Ok(id)
@ -52,7 +52,7 @@ impl Behaviour {
&mut self, &mut self,
_: &mut Context<'_>, _: &mut Context<'_>,
_: &mut impl PollParameters, _: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<RequestProtocol<Codec<Swap>>, OutEvent>> { ) -> Poll<NetworkBehaviourAction<RequestProtocol<OneShotCodec<Swap>>, OutEvent>> {
if let Some(event) = self.events.pop_front() { if let Some(event) = self.events.pop_front() {
return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)); return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event));
} }
@ -70,7 +70,7 @@ impl Default for Behaviour {
Self { Self {
rr: RequestResponse::new( rr: RequestResponse::new(
Codec::default(), OneShotCodec::default(),
vec![(Swap, ProtocolSupport::Outbound)], vec![(Swap, ProtocolSupport::Outbound)],
config, config,
), ),
@ -79,8 +79,8 @@ impl Default for Behaviour {
} }
} }
impl NetworkBehaviourEventProcess<RequestResponseEvent<BobToAlice, AliceToBob>> for Behaviour { impl NetworkBehaviourEventProcess<RequestResponseEvent<Request, Response>> for Behaviour {
fn inject_event(&mut self, event: RequestResponseEvent<BobToAlice, AliceToBob>) { fn inject_event(&mut self, event: RequestResponseEvent<Request, Response>) {
match event { match event {
RequestResponseEvent::Message { RequestResponseEvent::Message {
message: RequestResponseMessage::Request { .. }, message: RequestResponseMessage::Request { .. },
@ -90,7 +90,7 @@ impl NetworkBehaviourEventProcess<RequestResponseEvent<BobToAlice, AliceToBob>>
message: RequestResponseMessage::Response { response, .. }, message: RequestResponseMessage::Response { response, .. },
.. ..
} => { } => {
if let AliceToBob::SwapResponse(swap_response) = response { if let Response::SwapResponse(swap_response) = response {
debug!("Received swap response"); debug!("Received swap response");
self.events.push_back(OutEvent { self.events.push_back(OutEvent {
swap_response: *swap_response, swap_response: *swap_response,