use crate::{ bitcoin, bitcoin::EncryptedSignature, monero, network::{ spot_price::{SpotPriceRequest, SpotPriceResponse}, transport, TokioExecutor, }, protocol::{ alice::TransferProof, bob::{Behaviour, OutEvent, State0, State2}, }, }; use anyhow::{anyhow, bail, Context, Result}; use futures::FutureExt; use libp2p::{core::Multiaddr, PeerId}; use std::{convert::Infallible, sync::Arc}; use tokio::sync::mpsc::{Receiver, Sender}; use tracing::{debug, error, trace}; #[derive(Debug)] pub struct Channels { sender: Sender, receiver: Receiver, } impl Channels { pub fn new() -> Channels { let (sender, receiver) = tokio::sync::mpsc::channel(100); Channels { sender, receiver } } } impl Default for Channels { fn default() -> Self { Self::new() } } #[derive(Debug)] pub struct EventLoopHandle { recv_spot_price: Receiver, start_execution_setup: Sender, done_execution_setup: Receiver>, recv_transfer_proof: Receiver, conn_established: Receiver, dial_alice: Sender<()>, request_spot_price: Sender, send_encrypted_signature: Sender, } impl EventLoopHandle { pub async fn execution_setup(&mut self, state0: State0) -> Result { let _ = self.start_execution_setup.send(state0).await?; self.done_execution_setup .recv() .await .ok_or_else(|| anyhow!("Failed to setup execution with Alice"))? } pub async fn recv_transfer_proof(&mut self) -> Result { self.recv_transfer_proof .recv() .await .ok_or_else(|| anyhow!("Failed to receive transfer proof from Alice")) } /// Dials other party and wait for the connection to be established. /// Do nothing if we are already connected pub async fn dial(&mut self) -> Result<()> { let _ = self.dial_alice.send(()).await?; self.conn_established .recv() .await .ok_or_else(|| anyhow!("Failed to receive connection established from Alice"))?; Ok(()) } pub async fn request_spot_price(&mut self, btc: bitcoin::Amount) -> Result { let _ = self .request_spot_price .send(SpotPriceRequest { btc }) .await?; let response = self .recv_spot_price .recv() .await .ok_or_else(|| anyhow!("Failed to receive spot price from Alice"))?; Ok(response.xmr) } pub async fn send_encrypted_signature( &mut self, tx_redeem_encsig: EncryptedSignature, ) -> Result<()> { self.send_encrypted_signature.send(tx_redeem_encsig).await?; Ok(()) } } #[allow(missing_debug_implementations)] pub struct EventLoop { swarm: libp2p::Swarm, bitcoin_wallet: Arc, alice_peer_id: PeerId, request_spot_price: Receiver, recv_spot_price: Sender, start_execution_setup: Receiver, done_execution_setup: Sender>, recv_transfer_proof: Sender, dial_alice: Receiver<()>, conn_established: Sender, send_encrypted_signature: Receiver, } impl EventLoop { pub fn new( identity: &libp2p::core::identity::Keypair, alice_peer_id: PeerId, alice_addr: Multiaddr, bitcoin_wallet: Arc, ) -> Result<(Self, EventLoopHandle)> { let behaviour = Behaviour::default(); let transport = transport::build(identity)?; let mut swarm = libp2p::swarm::SwarmBuilder::new( transport, behaviour, identity.public().into_peer_id(), ) .executor(Box::new(TokioExecutor { handle: tokio::runtime::Handle::current(), })) .build(); swarm.add_address(alice_peer_id, alice_addr); let quote_response = 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_quote_request = Channels::new(); let send_encrypted_signature = Channels::new(); let event_loop = EventLoop { swarm, alice_peer_id, bitcoin_wallet, recv_spot_price: quote_response.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, request_spot_price: send_quote_request.receiver, send_encrypted_signature: send_encrypted_signature.receiver, }; let handle = EventLoopHandle { recv_spot_price: quote_response.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, request_spot_price: send_quote_request.sender, send_encrypted_signature: send_encrypted_signature.sender, }; Ok((event_loop, handle)) } pub async fn run(mut self) -> Result { loop { tokio::select! { swarm_event = self.swarm.next().fuse() => { match swarm_event { OutEvent::ConnectionEstablished(peer_id) => { let _ = self.conn_established.send(peer_id).await; } OutEvent::SpotPriceReceived(msg) => { let _ = self.recv_spot_price.send(msg).await; }, OutEvent::ExecutionSetupDone(res) => { let _ = self.done_execution_setup.send(res.map(|state|*state)).await; } OutEvent::TransferProof{ msg, channel }=> { let _ = self.recv_transfer_proof.send(*msg).await; // Send back empty response so that the request/response protocol completes. if let Err(error) = self.swarm.transfer_proof.send_ack(channel) { error!("Failed to send Transfer Proof ack: {:?}", error); } } OutEvent::EncryptedSignatureAcknowledged => { debug!("Alice acknowledged encrypted signature"); } OutEvent::ResponseSent => {} OutEvent::CommunicationError(err) => { bail!("Communication error: {:#}", err) } } }, option = self.dial_alice.recv().fuse() => { if option.is_some() { let peer_id = self.alice_peer_id; if self.swarm.pt.is_connected(&peer_id) { trace!("Already connected to Alice at {}", peer_id); let _ = self.conn_established.send(peer_id).await; } else { debug!("Dialing alice at {}", peer_id); libp2p::Swarm::dial(&mut self.swarm, &peer_id).context("failed to dial alice")?; } } }, quote_request = self.request_spot_price.recv().fuse() => { if let Some(quote_request) = quote_request { self.swarm.request_spot_price(self.alice_peer_id, quote_request); } }, option = self.start_execution_setup.recv().fuse() => { if let Some(state0) = option { let _ = self .swarm .start_execution_setup(self.alice_peer_id, state0, self.bitcoin_wallet.clone()); } }, encrypted_signature = self.send_encrypted_signature.recv().fuse() => { if let Some(tx_redeem_encsig) = encrypted_signature { self.swarm.send_encrypted_signature(self.alice_peer_id, tx_redeem_encsig); } } } } } }