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::{
alice,
alice::{Message1, Message3, TransferProof},
bob,
bob::{EncryptedSignature, Message0, Message2, Message4},
alice::{SwapResponse, TransferProof},
bob::{EncryptedSignature, SwapRequest},
};
use async_trait::async_trait;
use futures::prelude::*;
@ -19,38 +17,16 @@ pub const TIMEOUT: u64 = 3600; // One hour.
/// Message receive buffer.
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)]
pub enum Request {
SwapRequest(Box<SwapRequest>),
TransferProof(Box<TransferProof>),
EncryptedSignature(Box<EncryptedSignature>),
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
/// Response are only used for acknowledgement purposes.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Response {
SwapResponse(Box<SwapResponse>),
TransferProof,
EncryptedSignature,
}
@ -58,15 +34,6 @@ pub enum Response {
#[derive(Debug, Clone, Copy, Default)]
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)]
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 {
fn protocol_name(&self) -> &[u8] {
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)]
pub struct OneShotCodec<P> {
phantom: PhantomData<P>,

View File

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

View File

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

View File

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

View File

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