mirror of
https://github.com/comit-network/xmr-btc-swap.git
synced 2024-10-01 01:45:40 -04:00
Merge #264
264: Untangle Bob's `EventLoop` from the `Builder` r=thomaseizinger a=thomaseizinger This is work towards #255. Co-authored-by: Thomas Eizinger <thomas@eizinger.io>
This commit is contained in:
commit
ab4c98678c
@ -89,7 +89,7 @@ async fn main() -> Result<()> {
|
||||
let (bitcoin_wallet, monero_wallet) = init_wallets(
|
||||
config.clone(),
|
||||
&wallet_data_dir,
|
||||
seed.extended_private_key(BITCOIN_NETWORK)?,
|
||||
seed.derive_extended_private_key(BITCOIN_NETWORK)?,
|
||||
)
|
||||
.await?;
|
||||
|
||||
@ -100,7 +100,7 @@ async fn main() -> Result<()> {
|
||||
|
||||
let rate_service = kraken::RateService::new().await?;
|
||||
|
||||
let (mut event_loop, _) = EventLoop::new(
|
||||
let (event_loop, _) = EventLoop::new(
|
||||
config.network.listen,
|
||||
seed,
|
||||
execution_params,
|
||||
|
@ -31,7 +31,7 @@ use swap::{
|
||||
monero::{CreateWallet, OpenWallet},
|
||||
protocol::{
|
||||
bob,
|
||||
bob::{cancel::CancelError, Builder},
|
||||
bob::{cancel::CancelError, Builder, EventLoop},
|
||||
},
|
||||
seed::Seed,
|
||||
};
|
||||
@ -111,6 +111,7 @@ async fn main() -> Result<()> {
|
||||
init_bitcoin_wallet(config, bitcoin_network, &wallet_data_dir, seed).await?;
|
||||
let monero_wallet =
|
||||
init_monero_wallet(monero_network, monero_wallet_rpc_process.endpoint()).await?;
|
||||
let bitcoin_wallet = Arc::new(bitcoin_wallet);
|
||||
|
||||
let swap_id = Uuid::new_v4();
|
||||
|
||||
@ -137,19 +138,25 @@ async fn main() -> Result<()> {
|
||||
|
||||
let send_bitcoin = bitcoin_wallet.max_giveable(TxLock::script_size()).await?;
|
||||
|
||||
let bob_factory = Builder::new(
|
||||
seed,
|
||||
let (event_loop, event_loop_handle) = EventLoop::new(
|
||||
&seed.derive_libp2p_identity(),
|
||||
alice_peer_id,
|
||||
alice_addr,
|
||||
bitcoin_wallet.clone(),
|
||||
)?;
|
||||
let handle = tokio::spawn(event_loop.run());
|
||||
|
||||
let swap = Builder::new(
|
||||
db,
|
||||
swap_id,
|
||||
Arc::new(bitcoin_wallet),
|
||||
bitcoin_wallet.clone(),
|
||||
Arc::new(monero_wallet),
|
||||
alice_addr,
|
||||
alice_peer_id,
|
||||
execution_params,
|
||||
);
|
||||
let (swap, event_loop) = bob_factory.with_init_params(send_bitcoin).build().await?;
|
||||
event_loop_handle,
|
||||
)
|
||||
.with_init_params(send_bitcoin)
|
||||
.build()?;
|
||||
|
||||
let handle = tokio::spawn(async move { event_loop.run().await });
|
||||
let swap = bob::run(swap);
|
||||
tokio::select! {
|
||||
event_loop_result = handle => {
|
||||
@ -181,19 +188,26 @@ async fn main() -> Result<()> {
|
||||
init_bitcoin_wallet(config, bitcoin_network, &wallet_data_dir, seed).await?;
|
||||
let monero_wallet =
|
||||
init_monero_wallet(monero_network, monero_wallet_rpc_process.endpoint()).await?;
|
||||
let bitcoin_wallet = Arc::new(bitcoin_wallet);
|
||||
|
||||
let bob_factory = Builder::new(
|
||||
seed,
|
||||
let (event_loop, event_loop_handle) = EventLoop::new(
|
||||
&seed.derive_libp2p_identity(),
|
||||
alice_peer_id,
|
||||
alice_addr,
|
||||
bitcoin_wallet.clone(),
|
||||
)?;
|
||||
let handle = tokio::spawn(event_loop.run());
|
||||
|
||||
let swap = Builder::new(
|
||||
db,
|
||||
swap_id,
|
||||
Arc::new(bitcoin_wallet),
|
||||
bitcoin_wallet.clone(),
|
||||
Arc::new(monero_wallet),
|
||||
alice_addr,
|
||||
alice_peer_id,
|
||||
execution_params,
|
||||
);
|
||||
let (swap, event_loop) = bob_factory.build().await?;
|
||||
let handle = tokio::spawn(async move { event_loop.run().await });
|
||||
event_loop_handle,
|
||||
)
|
||||
.build()?;
|
||||
|
||||
let swap = bob::run(swap);
|
||||
tokio::select! {
|
||||
event_loop_result = handle => {
|
||||
@ -256,7 +270,7 @@ async fn init_bitcoin_wallet(
|
||||
config.bitcoin.electrum_http_url,
|
||||
bitcoin_network,
|
||||
bitcoin_wallet_data_dir,
|
||||
seed.extended_private_key(bitcoin_network)?,
|
||||
seed.derive_extended_private_key(bitcoin_network)?,
|
||||
)
|
||||
.await?;
|
||||
|
||||
|
@ -2,10 +2,8 @@ pub mod peer_tracker;
|
||||
pub mod request_response;
|
||||
pub mod transport;
|
||||
|
||||
use crate::seed::SEED_LENGTH;
|
||||
use bitcoin::hashes::{sha256, Hash, HashEngine};
|
||||
use futures::prelude::*;
|
||||
use libp2p::{core::Executor, identity::ed25519};
|
||||
use libp2p::core::Executor;
|
||||
use std::pin::Pin;
|
||||
use tokio::runtime::Handle;
|
||||
|
||||
@ -19,35 +17,3 @@ impl Executor for TokioExecutor {
|
||||
let _ = self.handle.spawn(future);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
|
||||
pub struct Seed([u8; SEED_LENGTH]);
|
||||
|
||||
impl Seed {
|
||||
/// prefix "NETWORK" to the provided seed and apply sha256
|
||||
pub fn new(seed: crate::seed::Seed) -> Self {
|
||||
let mut engine = sha256::HashEngine::default();
|
||||
|
||||
engine.input(&seed.bytes());
|
||||
engine.input(b"NETWORK");
|
||||
|
||||
let hash = sha256::Hash::from_engine(engine);
|
||||
Self(hash.into_inner())
|
||||
}
|
||||
|
||||
fn bytes(&self) -> [u8; SEED_LENGTH] {
|
||||
self.0
|
||||
}
|
||||
|
||||
pub fn derive_libp2p_identity(&self) -> libp2p::identity::Keypair {
|
||||
let mut engine = sha256::HashEngine::default();
|
||||
|
||||
engine.input(&self.bytes());
|
||||
engine.input(b"LIBP2P_IDENTITY");
|
||||
|
||||
let hash = sha256::Hash::from_engine(engine);
|
||||
let key =
|
||||
ed25519::SecretKey::from_bytes(hash.into_inner()).expect("we always pass 32 bytes");
|
||||
libp2p::identity::Keypair::Ed25519(key.into())
|
||||
}
|
||||
}
|
||||
|
@ -5,7 +5,6 @@ use crate::{
|
||||
execution_params::ExecutionParams,
|
||||
monero,
|
||||
monero::{Amount, BalanceTooLow},
|
||||
network,
|
||||
network::{transport, TokioExecutor},
|
||||
protocol::{
|
||||
alice,
|
||||
@ -113,7 +112,7 @@ where
|
||||
rate_service: RS,
|
||||
max_sell: Amount,
|
||||
) -> Result<(Self, mpsc::Receiver<RemoteHandle<Result<AliceState>>>)> {
|
||||
let identity = network::Seed::new(seed).derive_libp2p_identity();
|
||||
let identity = seed.derive_libp2p_identity();
|
||||
let behaviour = Behaviour::default();
|
||||
let transport = transport::build(&identity)?;
|
||||
let peer_id = PeerId::from(identity.public());
|
||||
@ -159,7 +158,7 @@ where
|
||||
self.peer_id
|
||||
}
|
||||
|
||||
pub async fn run(&mut self) {
|
||||
pub async fn run(mut self) {
|
||||
loop {
|
||||
tokio::select! {
|
||||
swarm_event = self.swarm.next().fuse() => {
|
||||
|
@ -4,16 +4,12 @@ use crate::{
|
||||
bitcoin,
|
||||
database::Database,
|
||||
execution_params::ExecutionParams,
|
||||
monero, network,
|
||||
network::{
|
||||
peer_tracker::{self, PeerTracker},
|
||||
transport::build,
|
||||
},
|
||||
monero,
|
||||
network::peer_tracker::{self, PeerTracker},
|
||||
protocol::{alice, alice::TransferProof, bob},
|
||||
seed::Seed,
|
||||
};
|
||||
use anyhow::{Error, Result};
|
||||
use libp2p::{core::Multiaddr, identity::Keypair, NetworkBehaviour, PeerId};
|
||||
use libp2p::{core::Multiaddr, NetworkBehaviour, PeerId};
|
||||
use std::sync::Arc;
|
||||
use tracing::debug;
|
||||
use uuid::Uuid;
|
||||
@ -52,18 +48,15 @@ pub struct Swap {
|
||||
|
||||
pub struct Builder {
|
||||
swap_id: Uuid,
|
||||
identity: Keypair,
|
||||
peer_id: PeerId,
|
||||
db: Database,
|
||||
|
||||
alice_address: Multiaddr,
|
||||
alice_peer_id: PeerId,
|
||||
|
||||
bitcoin_wallet: Arc<bitcoin::Wallet>,
|
||||
monero_wallet: Arc<monero::Wallet>,
|
||||
|
||||
init_params: InitParams,
|
||||
execution_params: ExecutionParams,
|
||||
|
||||
event_loop_handle: bob::EventLoopHandle,
|
||||
}
|
||||
|
||||
enum InitParams {
|
||||
@ -74,29 +67,21 @@ enum InitParams {
|
||||
impl Builder {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
seed: Seed,
|
||||
db: Database,
|
||||
swap_id: Uuid,
|
||||
bitcoin_wallet: Arc<bitcoin::Wallet>,
|
||||
monero_wallet: Arc<monero::Wallet>,
|
||||
alice_address: Multiaddr,
|
||||
alice_peer_id: PeerId,
|
||||
execution_params: ExecutionParams,
|
||||
event_loop_handle: bob::EventLoopHandle,
|
||||
) -> Self {
|
||||
let identity = network::Seed::new(seed).derive_libp2p_identity();
|
||||
let peer_id = identity.public().into_peer_id();
|
||||
|
||||
Self {
|
||||
swap_id,
|
||||
identity,
|
||||
peer_id,
|
||||
db,
|
||||
alice_address,
|
||||
alice_peer_id,
|
||||
bitcoin_wallet,
|
||||
monero_wallet,
|
||||
init_params: InitParams::None,
|
||||
execution_params,
|
||||
event_loop_handle,
|
||||
}
|
||||
}
|
||||
|
||||
@ -107,62 +92,21 @@ impl Builder {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn build(self) -> Result<(bob::Swap, bob::EventLoop)> {
|
||||
match self.init_params {
|
||||
InitParams::New { btc_amount } => {
|
||||
let initial_state = BobState::Started { btc_amount };
|
||||
pub fn build(self) -> Result<bob::Swap> {
|
||||
let state = match self.init_params {
|
||||
InitParams::New { btc_amount } => BobState::Started { btc_amount },
|
||||
InitParams::None => self.db.get_state(self.swap_id)?.try_into_bob()?.into(),
|
||||
};
|
||||
|
||||
let (event_loop, event_loop_handle) = self.init_event_loop()?;
|
||||
|
||||
Ok((
|
||||
Swap {
|
||||
state: initial_state,
|
||||
event_loop_handle,
|
||||
db: self.db,
|
||||
bitcoin_wallet: self.bitcoin_wallet.clone(),
|
||||
monero_wallet: self.monero_wallet.clone(),
|
||||
swap_id: self.swap_id,
|
||||
execution_params: self.execution_params,
|
||||
},
|
||||
event_loop,
|
||||
))
|
||||
}
|
||||
|
||||
InitParams::None => {
|
||||
let resume_state = self.db.get_state(self.swap_id)?.try_into_bob()?.into();
|
||||
|
||||
let (event_loop, event_loop_handle) = self.init_event_loop()?;
|
||||
|
||||
Ok((
|
||||
Swap {
|
||||
state: resume_state,
|
||||
event_loop_handle,
|
||||
db: self.db,
|
||||
bitcoin_wallet: self.bitcoin_wallet.clone(),
|
||||
monero_wallet: self.monero_wallet.clone(),
|
||||
swap_id: self.swap_id,
|
||||
execution_params: self.execution_params,
|
||||
},
|
||||
event_loop,
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn init_event_loop(
|
||||
&self,
|
||||
) -> Result<(bob::event_loop::EventLoop, bob::event_loop::EventLoopHandle)> {
|
||||
let bob_behaviour = bob::Behaviour::default();
|
||||
let bob_transport = build(&self.identity)?;
|
||||
|
||||
bob::event_loop::EventLoop::new(
|
||||
bob_transport,
|
||||
bob_behaviour,
|
||||
self.peer_id,
|
||||
self.alice_peer_id,
|
||||
self.alice_address.clone(),
|
||||
self.bitcoin_wallet.clone(),
|
||||
)
|
||||
Ok(Swap {
|
||||
state,
|
||||
event_loop_handle: self.event_loop_handle,
|
||||
db: self.db,
|
||||
bitcoin_wallet: self.bitcoin_wallet.clone(),
|
||||
monero_wallet: self.monero_wallet.clone(),
|
||||
swap_id: self.swap_id,
|
||||
execution_params: self.execution_params,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
use crate::{
|
||||
bitcoin,
|
||||
bitcoin::EncryptedSignature,
|
||||
network::{transport::SwapTransport, TokioExecutor},
|
||||
network::{transport, TokioExecutor},
|
||||
protocol::{
|
||||
alice::{QuoteResponse, TransferProof},
|
||||
bob::{Behaviour, OutEvent, QuoteRequest, State0, State2},
|
||||
@ -114,18 +114,23 @@ pub struct EventLoop {
|
||||
|
||||
impl EventLoop {
|
||||
pub fn new(
|
||||
transport: SwapTransport,
|
||||
behaviour: Behaviour,
|
||||
peer_id: PeerId,
|
||||
identity: &libp2p::core::identity::Keypair,
|
||||
alice_peer_id: PeerId,
|
||||
alice_addr: Multiaddr,
|
||||
bitcoin_wallet: Arc<bitcoin::Wallet>,
|
||||
) -> Result<(Self, EventLoopHandle)> {
|
||||
let mut swarm = libp2p::swarm::SwarmBuilder::new(transport, behaviour, peer_id)
|
||||
.executor(Box::new(TokioExecutor {
|
||||
handle: tokio::runtime::Handle::current(),
|
||||
}))
|
||||
.build();
|
||||
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);
|
||||
|
||||
|
@ -2,6 +2,8 @@ use crate::fs::ensure_directory_exists;
|
||||
use ::bitcoin::secp256k1::{self, constants::SECRET_KEY_SIZE, SecretKey};
|
||||
use anyhow::Result;
|
||||
use bdk::bitcoin::util::bip32::ExtendedPrivKey;
|
||||
use bitcoin::hashes::{sha256, Hash, HashEngine};
|
||||
use libp2p::identity;
|
||||
use pem::{encode, Pem};
|
||||
use rand::prelude::*;
|
||||
use std::{
|
||||
@ -28,13 +30,21 @@ impl Seed {
|
||||
Ok(Seed(bytes))
|
||||
}
|
||||
|
||||
pub fn extended_private_key(&self, network: bitcoin::Network) -> Result<ExtendedPrivKey> {
|
||||
let private_key = ExtendedPrivKey::new_master(network, &self.bytes())?;
|
||||
pub fn derive_extended_private_key(
|
||||
&self,
|
||||
network: bitcoin::Network,
|
||||
) -> Result<ExtendedPrivKey> {
|
||||
let seed = self.derive(b"BITCOIN_EXTENDED_PRIVATE_KEY").bytes();
|
||||
let private_key = ExtendedPrivKey::new_master(network, &seed)?;
|
||||
|
||||
Ok(private_key)
|
||||
}
|
||||
|
||||
pub fn bytes(&self) -> [u8; SEED_LENGTH] {
|
||||
self.0
|
||||
pub fn derive_libp2p_identity(&self) -> identity::Keypair {
|
||||
let bytes = self.derive(b"NETWORK").derive(b"LIBP2P_IDENTITY").bytes();
|
||||
let key = identity::ed25519::SecretKey::from_bytes(bytes).expect("we always pass 32 bytes");
|
||||
|
||||
identity::Keypair::Ed25519(key.into())
|
||||
}
|
||||
|
||||
pub fn from_file_or_generate(data_dir: &Path) -> Result<Self, Error> {
|
||||
@ -53,6 +63,26 @@ impl Seed {
|
||||
Ok(random_seed)
|
||||
}
|
||||
|
||||
/// Derive a new seed using the given scope.
|
||||
///
|
||||
/// This function is purposely kept private because it is only a helper
|
||||
/// function for deriving specific secret material from the root seed
|
||||
/// like the libp2p identity or the seed for the Bitcoin wallet.
|
||||
fn derive(&self, scope: &[u8]) -> Self {
|
||||
let mut engine = sha256::HashEngine::default();
|
||||
|
||||
engine.input(&self.bytes());
|
||||
engine.input(scope);
|
||||
|
||||
let hash = sha256::Hash::from_engine(engine);
|
||||
|
||||
Self(hash.into_inner())
|
||||
}
|
||||
|
||||
fn bytes(&self) -> [u8; SEED_LENGTH] {
|
||||
self.0
|
||||
}
|
||||
|
||||
fn from_file<D>(seed_file: D) -> Result<Self, Error>
|
||||
where
|
||||
D: AsRef<OsStr>,
|
||||
|
@ -54,16 +54,23 @@ struct BobParams {
|
||||
}
|
||||
|
||||
impl BobParams {
|
||||
pub fn builder(&self) -> bob::Builder {
|
||||
pub fn builder(&self, event_loop_handle: bob::EventLoopHandle) -> bob::Builder {
|
||||
bob::Builder::new(
|
||||
self.seed,
|
||||
Database::open(&self.db_path.clone().as_path()).unwrap(),
|
||||
self.swap_id,
|
||||
self.bitcoin_wallet.clone(),
|
||||
self.monero_wallet.clone(),
|
||||
self.alice_address.clone(),
|
||||
self.alice_peer_id,
|
||||
self.execution_params,
|
||||
event_loop_handle,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn new_eventloop(&self) -> Result<(bob::EventLoop, bob::EventLoopHandle)> {
|
||||
bob::EventLoop::new(
|
||||
&self.seed.derive_libp2p_identity(),
|
||||
self.alice_peer_id,
|
||||
self.alice_address.clone(),
|
||||
self.bitcoin_wallet.clone(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -95,15 +102,16 @@ pub struct TestContext {
|
||||
|
||||
impl TestContext {
|
||||
pub async fn new_swap_as_bob(&mut self) -> (bob::Swap, BobEventLoopJoinHandle) {
|
||||
let (swap, event_loop) = self
|
||||
let (event_loop, event_loop_handle) = self.bob_params.new_eventloop().unwrap();
|
||||
|
||||
let swap = self
|
||||
.bob_params
|
||||
.builder()
|
||||
.builder(event_loop_handle)
|
||||
.with_init_params(self.btc_amount)
|
||||
.build()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let join_handle = tokio::spawn(async move { event_loop.run().await });
|
||||
let join_handle = tokio::spawn(event_loop.run());
|
||||
|
||||
(swap, BobEventLoopJoinHandle(join_handle))
|
||||
}
|
||||
@ -114,9 +122,11 @@ impl TestContext {
|
||||
) -> (bob::Swap, BobEventLoopJoinHandle) {
|
||||
join_handle.abort();
|
||||
|
||||
let (swap, event_loop) = self.bob_params.builder().build().await.unwrap();
|
||||
let (event_loop, event_loop_handle) = self.bob_params.new_eventloop().unwrap();
|
||||
|
||||
let join_handle = tokio::spawn(async move { event_loop.run().await });
|
||||
let swap = self.bob_params.builder(event_loop_handle).build().unwrap();
|
||||
|
||||
let join_handle = tokio::spawn(event_loop.run());
|
||||
|
||||
(swap, BobEventLoopJoinHandle(join_handle))
|
||||
}
|
||||
@ -376,7 +386,7 @@ where
|
||||
)
|
||||
.await;
|
||||
|
||||
let (mut alice_event_loop, alice_swap_handle) = alice::EventLoop::new(
|
||||
let (alice_event_loop, alice_swap_handle) = alice::EventLoop::new(
|
||||
alice_listen_address.clone(),
|
||||
alice_seed,
|
||||
execution_params,
|
||||
@ -390,9 +400,7 @@ where
|
||||
|
||||
let alice_peer_id = alice_event_loop.peer_id();
|
||||
|
||||
tokio::spawn(async move {
|
||||
alice_event_loop.run().await;
|
||||
});
|
||||
tokio::spawn(alice_event_loop.run());
|
||||
|
||||
let bob_params = BobParams {
|
||||
seed: Seed::random().unwrap(),
|
||||
@ -606,7 +614,7 @@ async fn init_test_wallets(
|
||||
electrum_http_url,
|
||||
bitcoin::Network::Regtest,
|
||||
datadir,
|
||||
seed.extended_private_key(bitcoin::Network::Regtest)
|
||||
seed.derive_extended_private_key(bitcoin::Network::Regtest)
|
||||
.expect("Could not create extended private key from seed"),
|
||||
)
|
||||
.await
|
||||
|
Loading…
Reference in New Issue
Block a user