Remove unused behaviours

pull/173/head
Franck Royer 3 years ago
parent ecb54958ee
commit 081237bb6f
No known key found for this signature in database
GPG Key ID: A82ED75A8DFC50A4

@ -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<swap_response::OutEvent>), /* Not-uniform with Bob on purpose, ready for adding
* Xmr
* event. */
Message0 {
msg: Box<bob::Message0>,
channel: ResponseChannel<AliceToBob>,
},
Message1 {
msg: Box<bob::Message1>,
channel: ResponseChannel<AliceToBob>,
},
Message2 {
msg: Box<bob::Message2>,
bob_peer_id: PeerId,
},
Request(Box<swap_response::OutEvent>),
ExecutionSetupDone(Result<Box<State3>>),
TransferProofAcknowledged,
EncryptedSignature(Box<EncryptedSignature>),
@ -258,39 +240,6 @@ impl From<swap_response::OutEvent> for OutEvent {
}
}
impl From<message0::OutEvent> for OutEvent {
fn from(event: message0::OutEvent) -> Self {
match event {
message0::OutEvent::Msg { channel, msg } => OutEvent::Message0 {
msg: Box::new(msg),
channel,
},
}
}
}
impl From<message1::OutEvent> for OutEvent {
fn from(event: message1::OutEvent) -> Self {
match event {
message1::OutEvent::Msg { msg, channel } => OutEvent::Message1 {
msg: Box::new(msg),
channel,
},
}
}
}
impl From<message2::OutEvent> 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<execution_setup::OutEvent> for OutEvent {
fn from(event: execution_setup::OutEvent) -> Self {
match event {
@ -322,9 +271,6 @@ impl From<encrypted_signature::OutEvent> 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<AliceToBob>,
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<AliceToBob>,
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);

@ -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<T> Default for Channels<T> {
#[derive(Debug)]
pub struct EventLoopHandle {
recv_message0: Receiver<(bob::Message0, ResponseChannel<AliceToBob>)>,
recv_message1: Receiver<(bob::Message1, ResponseChannel<AliceToBob>)>,
recv_message2: Receiver<bob::Message2>,
done_execution_setup: Receiver<Result<State3>>,
recv_encrypted_signature: Receiver<EncryptedSignature>,
request: Receiver<crate::protocol::alice::swap_response::OutEvent>,
conn_established: Receiver<PeerId>,
send_swap_response: Sender<(ResponseChannel<AliceToBob>, SwapResponse)>,
start_execution_setup: Sender<(PeerId, State0)>,
send_message0: Sender<(ResponseChannel<AliceToBob>, alice::Message0)>,
send_message1: Sender<(ResponseChannel<AliceToBob>, 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<AliceToBob>)> {
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<AliceToBob>)> {
self.recv_message1
.recv()
.await
.ok_or_else(|| anyhow!("Failed to receive message 1 from Bob"))
}
pub async fn recv_message2(&mut self) -> Result<bob::Message2> {
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<State3> {
let _ = self
.start_execution_setup
@ -119,24 +91,6 @@ impl EventLoopHandle {
Ok(())
}
pub async fn send_message0(
&mut self,
channel: ResponseChannel<AliceToBob>,
msg: alice::Message0,
) -> Result<()> {
let _ = self.send_message0.send((channel, msg)).await?;
Ok(())
}
pub async fn send_message1(
&mut self,
channel: ResponseChannel<AliceToBob>,
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<Behaviour>,
recv_message0: Sender<(bob::Message0, ResponseChannel<AliceToBob>)>,
recv_message1: Sender<(bob::Message1, ResponseChannel<AliceToBob>)>,
recv_message2: Sender<bob::Message2>,
start_execution_setup: Receiver<(PeerId, State0)>,
done_execution_setup: Sender<Result<State3>>,
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_message0: Receiver<(ResponseChannel<AliceToBob>, alice::Message0)>,
send_message1: Receiver<(ResponseChannel<AliceToBob>, 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);

@ -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 {

@ -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<AliceToBob>,
},
}
#[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<Codec<Message0Protocol>>,
#[behaviour(ignore)]
events: VecDeque<OutEvent>,
}
impl Behaviour {
pub fn send(&mut self, channel: ResponseChannel<AliceToBob>, 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<NetworkBehaviourAction<RequestProtocol<Codec<Message0Protocol>>, 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<RequestResponseEvent<BobToAlice, AliceToBob>> for Behaviour {
fn inject_event(&mut self, event: RequestResponseEvent<BobToAlice, AliceToBob>) {
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");
}
}
}
}

@ -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<AliceToBob>,
},
}
#[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<Codec<Message1Protocol>>,
#[behaviour(ignore)]
events: VecDeque<OutEvent>,
}
impl Behaviour {
pub fn send(&mut self, channel: ResponseChannel<AliceToBob>, 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<NetworkBehaviourAction<RequestProtocol<Codec<Message1Protocol>>, 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<RequestResponseEvent<BobToAlice, AliceToBob>> for Behaviour {
fn inject_event(&mut self, event: RequestResponseEvent<BobToAlice, AliceToBob>) {
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");
}
}
}
}

@ -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<Codec<Message2Protocol>>,
#[behaviour(ignore)]
events: VecDeque<OutEvent>,
}
impl Behaviour {
fn poll(
&mut self,
_: &mut Context<'_>,
_: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<RequestProtocol<Codec<Message2Protocol>>, 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<RequestResponseEvent<BobToAlice, AliceToBob>> for Behaviour {
fn inject_event(&mut self, event: RequestResponseEvent<BobToAlice, AliceToBob>) {
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");
}
}
}
}

@ -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<alice::Message0>),
Message1(Box<alice::Message1>),
Message2,
ExecutionSetupDone(Result<Box<State2>>),
TransferProof(Box<TransferProof>),
EncryptedSignatureAcknowledged,
@ -234,30 +226,6 @@ impl From<swap_request::OutEvent> for OutEvent {
}
}
impl From<message0::OutEvent> for OutEvent {
fn from(event: message0::OutEvent) -> Self {
match event {
message0::OutEvent::Msg(msg) => OutEvent::Message0(Box::new(msg)),
}
}
}
impl From<message1::OutEvent> for OutEvent {
fn from(event: message1::OutEvent) -> Self {
match event {
message1::OutEvent::Msg(msg) => OutEvent::Message1(Box::new(msg)),
}
}
}
impl From<message2::OutEvent> for OutEvent {
fn from(event: message2::OutEvent) -> Self {
match event {
message2::OutEvent::Msg => OutEvent::Message2,
}
}
}
impl From<execution_setup::OutEvent> for OutEvent {
fn from(event: execution_setup::OutEvent) -> Self {
match event {
@ -289,9 +257,6 @@ impl From<encrypted_signature::OutEvent> 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,

@ -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<T> Default for Channels<T> {
#[derive(Debug)]
pub struct EventLoopHandle {
recv_swap_response: Receiver<SwapResponse>,
recv_message0: Receiver<alice::Message0>,
recv_message1: Receiver<alice::Message1>,
start_execution_setup: Sender<State0>,
done_execution_setup: Receiver<Result<State2>>,
recv_transfer_proof: Receiver<TransferProof>,
conn_established: Receiver<PeerId>,
dial_alice: Sender<()>,
send_swap_request: Sender<SwapRequest>,
send_message0: Sender<bob::Message0>,
send_message1: Sender<bob::Message1>,
send_message2: Sender<bob::Message2>,
send_encrypted_signature: Sender<EncryptedSignature>,
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<alice::Message0> {
self.recv_message0
.recv()
.await
.ok_or_else(|| anyhow!("Failed to receive message 0 from Alice"))
}
pub async fn recv_message1(&mut self) -> Result<alice::Message1> {
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<State2> {
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<bitcoin::Wallet>,
alice_peer_id: PeerId,
recv_swap_response: Sender<SwapResponse>,
recv_message0: Sender<alice::Message0>,
recv_message1: Sender<alice::Message1>,
start_execution_setup: Receiver<State0>,
done_execution_setup: Sender<Result<State2>>,
recv_transfer_proof: Sender<TransferProof>,
dial_alice: Receiver<()>,
conn_established: Sender<PeerId>,
send_swap_request: Receiver<SwapRequest>,
send_message0: Receiver<bob::Message0>,
send_message1: Receiver<bob::Message1>,
send_message2: Receiver<bob::Message2>,
send_encrypted_signature: Receiver<EncryptedSignature>,
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

@ -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<State2>),

@ -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<Codec<Message0Protocol>>,
#[behaviour(ignore)]
events: VecDeque<OutEvent>,
}
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<NetworkBehaviourAction<RequestProtocol<Codec<Message0Protocol>>, 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<RequestResponseEvent<BobToAlice, AliceToBob>> for Behaviour {
fn inject_event(&mut self, event: RequestResponseEvent<BobToAlice, AliceToBob>) {
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");
}
}
}
}

@ -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<Codec<Message1Protocol>>,
#[behaviour(ignore)]
events: VecDeque<OutEvent>,
}
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<NetworkBehaviourAction<RequestProtocol<Codec<Message1Protocol>>, 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<RequestResponseEvent<BobToAlice, AliceToBob>> for Behaviour {
fn inject_event(&mut self, event: RequestResponseEvent<BobToAlice, AliceToBob>) {
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");
}
}
}
}

@ -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<Codec<Message2Protocol>>,
#[behaviour(ignore)]
events: VecDeque<OutEvent>,
}
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<NetworkBehaviourAction<RequestProtocol<Codec<Message2Protocol>>, 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<RequestResponseEvent<BobToAlice, AliceToBob>> for Behaviour {
fn inject_event(&mut self, event: RequestResponseEvent<BobToAlice, AliceToBob>) {
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");
}
}
}
}
Loading…
Cancel
Save