Remove need to send Monero transfer proof from Alice to Bob

This commit is contained in:
Lucas Soriano del Pino 2020-11-04 20:16:54 +11:00 committed by rishflab
parent 0288e004c5
commit 620216a596
16 changed files with 233 additions and 477 deletions

View file

@ -24,16 +24,14 @@ use std::{
sync::Arc,
time::Duration,
};
use tokio::{sync::Mutex, time::timeout};
use tokio::time::timeout;
use tracing::{error, info};
pub mod message;
pub use message::{Message, Message0, Message1, Message2};
pub use message::{Message, Message0, Message1};
#[derive(Debug)]
pub enum Action {
// This action also includes proving to Bob that this has happened, given that our current
// protocol requires a transfer proof to verify that the coins have been locked on Monero
LockXmr {
amount: monero::Amount,
public_spend_key: monero::PublicKey,
@ -62,7 +60,7 @@ pub trait ReceiveBitcoinRedeemEncsig {
/// The argument `bitcoin_tx_lock_timeout` is used to determine how long we will
/// wait for Bob, the counterparty, to lock up the bitcoin.
pub fn action_generator<N, B, M>(
network: Arc<Mutex<N>>,
mut network: N,
bitcoin_client: Arc<B>,
monero_client: Arc<M>,
// TODO: Replace this with a new, slimmer struct?
@ -94,7 +92,7 @@ where
+ Send
+ Sync
+ 'static,
M: monero::WatchForTransferImproved + Send + Sync + 'static,
M: monero::WatchForTransfer + Send + Sync + 'static,
{
#[allow(clippy::enum_variant_names)]
#[derive(Debug)]
@ -149,25 +147,20 @@ where
let S_a = monero::PublicKey::from_private_key(&monero::PrivateKey {
scalar: s_a.into_ed25519(),
});
let public_spend_key = S_a + S_b_monero;
let public_view_key = v.public();
let S = S_a + S_b_monero;
co.yield_(Action::LockXmr {
amount: xmr,
public_spend_key,
public_view_key,
public_spend_key: S,
public_view_key: v.public(),
})
.await;
let monero_joint_address = monero::Address::standard(
monero::Network::Mainnet,
public_spend_key,
public_view_key.into(),
);
let monero_joint_address =
monero::Address::standard(monero::Network::Mainnet, S, v.public().into());
if let Either::Right(_) = select(
monero_client.watch_for_transfer_improved(monero_joint_address, xmr, v),
monero_client.watch_for_transfer(monero_joint_address, xmr, v),
poll_until_btc_has_expired.clone(),
)
.await
@ -176,9 +169,8 @@ where
};
let tx_redeem_encsig = {
let mut guard = network.as_ref().lock().await;
let tx_redeem_encsig = match select(
guard.receive_bitcoin_redeem_encsig(),
network.receive_bitcoin_redeem_encsig(),
poll_until_btc_has_expired.clone(),
)
.await
@ -383,7 +375,6 @@ pub async fn next_state<
Ok(state5.into())
}
State::State5(state5) => {
transport.send_message(state5.next_message().into()).await?;
// todo: pass in state4b as a parameter somewhere in this call to prevent the
// user from waiting for a message that wont be sent
let message3 = transport.receive_message().await?.try_into()?;
@ -735,7 +726,7 @@ impl State4 {
});
let S_b = self.S_b_monero;
let (tx_lock_proof, fee) = monero_wallet
let fee = monero_wallet
.transfer(S_a + S_b, self.v.public(), self.xmr)
.await?;
@ -754,7 +745,6 @@ impl State4 {
redeem_address: self.redeem_address,
punish_address: self.punish_address,
tx_lock: self.tx_lock,
tx_lock_proof,
tx_punish_sig_bob: self.tx_punish_sig_bob,
tx_cancel_sig_bob: self.tx_cancel_sig_bob,
lock_xmr_fee: fee,
@ -825,7 +815,6 @@ pub struct State5 {
redeem_address: bitcoin::Address,
punish_address: bitcoin::Address,
tx_lock: bitcoin::TxLock,
tx_lock_proof: monero::TransferProof,
tx_punish_sig_bob: bitcoin::Signature,
@ -834,12 +823,6 @@ pub struct State5 {
}
impl State5 {
pub fn next_message(&self) -> Message2 {
Message2 {
tx_lock_proof: self.tx_lock_proof.clone(),
}
}
pub fn receive(self, msg: bob::Message3) -> State6 {
State6 {
a: self.a,

View file

@ -9,7 +9,6 @@ use crate::{bitcoin, monero};
pub enum Message {
Message0(Message0),
Message1(Message1),
Message2(Message2),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
@ -29,15 +28,8 @@ pub struct Message1 {
pub(crate) tx_refund_encsig: EncryptedSignature,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Message2 {
pub tx_lock_proof: monero::TransferProof,
}
impl_try_from_parent_enum!(Message0, Message);
impl_try_from_parent_enum!(Message1, Message);
impl_try_from_parent_enum!(Message2, Message);
impl_from_child_enum!(Message0, Message);
impl_from_child_enum!(Message1, Message);
impl_from_child_enum!(Message2, Message);

View file

@ -5,11 +5,11 @@ use crate::{
SignTxLock, TxCancel, WatchForRawTransaction,
},
monero,
monero::WatchForTransfer,
serde::monero_private_key,
transport::{ReceiveMessage, SendMessage},
};
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use ecdsa_fun::{
adaptor::{Adaptor, EncryptedSignature},
nonce::Deterministic,
@ -28,11 +28,11 @@ use std::{
sync::Arc,
time::Duration,
};
use tokio::{sync::Mutex, time::timeout};
use tokio::time::timeout;
use tracing::error;
pub mod message;
use crate::monero::{CreateWalletForOutput, WatchForTransfer};
use crate::monero::CreateWalletForOutput;
pub use message::{Message, Message0, Message1, Message2, Message3};
#[allow(clippy::large_enum_variant)]
@ -48,12 +48,6 @@ pub enum Action {
RefundBtc(bitcoin::Transaction),
}
// TODO: This could be moved to the monero module
#[async_trait]
pub trait ReceiveTransferProof {
async fn receive_transfer_proof(&mut self) -> monero::TransferProof;
}
/// Perform the on-chain protocol to swap monero and bitcoin as Bob.
///
/// This is called post handshake, after all the keys, addresses and most of the
@ -61,8 +55,7 @@ pub trait ReceiveTransferProof {
///
/// The argument `bitcoin_tx_lock_timeout` is used to determine how long we will
/// wait for Bob, the caller of this function, to lock up the bitcoin.
pub fn action_generator<N, M, B>(
network: Arc<Mutex<N>>,
pub fn action_generator<M, B>(
monero_client: Arc<M>,
bitcoin_client: Arc<B>,
// TODO: Replace this with a new, slimmer struct?
@ -85,7 +78,6 @@ pub fn action_generator<N, M, B>(
bitcoin_tx_lock_timeout: u64,
) -> GenBoxed<Action, (), ()>
where
N: ReceiveTransferProof + Send + 'static,
M: monero::WatchForTransfer + Send + Sync + 'static,
B: bitcoin::BlockHeight
+ bitcoin::TransactionBlockHeight
@ -108,8 +100,6 @@ where
InactiveBob,
/// The refund timelock has been reached.
BtcExpired,
/// Alice did not lock up enough monero in the shared output.
InsufficientXmr(monero::InsufficientFunds),
/// Could not find Bob's signature on the redeem transaction witness
/// stack.
BtcRedeemSignature,
@ -140,39 +130,21 @@ where
.shared();
pin_mut!(poll_until_btc_has_expired);
let transfer_proof = {
let mut guard = network.as_ref().lock().await;
let transfer_proof = match select(
guard.receive_transfer_proof(),
poll_until_btc_has_expired.clone(),
)
.await
{
Either::Left((proof, _)) => proof,
Either::Right(_) => return Err(SwapFailed::AfterBtcLock(Reason::BtcExpired)),
};
tracing::debug!("select returned transfer proof from message");
transfer_proof
};
let S_b_monero = monero::PublicKey::from_private_key(&monero::PrivateKey::from_scalar(
s_b.into_ed25519(),
));
let S = S_a_monero + S_b_monero;
match select(
monero_client.watch_for_transfer(S, v.public(), transfer_proof, xmr, 0),
let monero_joint_address =
monero::Address::standard(monero::Network::Mainnet, S, v.public().into());
if let Either::Right(_) = select(
monero_client.watch_for_transfer(monero_joint_address, xmr, v),
poll_until_btc_has_expired.clone(),
)
.await
{
Either::Left((Err(e), _)) => {
return Err(SwapFailed::AfterBtcLock(Reason::InsufficientXmr(e)))
}
Either::Right(_) => return Err(SwapFailed::AfterBtcLock(Reason::BtcExpired)),
_ => {}
return Err(SwapFailed::AfterBtcLock(Reason::BtcExpired));
}
let tx_redeem = bitcoin::TxRedeem::new(&tx_lock, &redeem_address);
@ -300,8 +272,7 @@ pub async fn next_state<
Ok(state3.into())
}
State::State3(state3) => {
let message2 = transport.receive_message().await?.try_into()?;
let state4 = state3.watch_for_lock_xmr(monero_wallet, message2).await?;
let state4 = state3.watch_for_lock_xmr(monero_wallet).await?;
tracing::info!("bob has seen that alice has locked xmr");
Ok(state4.into())
}
@ -589,7 +560,7 @@ pub struct State3 {
}
impl State3 {
pub async fn watch_for_lock_xmr<W>(self, xmr_wallet: &W, msg: alice::Message2) -> Result<State4>
pub async fn watch_for_lock_xmr<W>(self, xmr_wallet: &W) -> Result<State4>
where
W: monero::WatchForTransfer,
{
@ -598,15 +569,12 @@ impl State3 {
));
let S = self.S_a_monero + S_b_monero;
let monero_joint_address =
monero::Address::standard(monero::Network::Mainnet, S, self.v.public().into());
xmr_wallet
.watch_for_transfer(
S,
self.v.public(),
msg.tx_lock_proof,
self.xmr,
monero::MIN_CONFIRMATIONS,
)
.await?;
.watch_for_transfer(monero_joint_address, self.xmr, self.v)
.await;
Ok(State4 {
A: self.A,

View file

@ -1,5 +1,4 @@
use crate::serde::monero_private_key;
use anyhow::Result;
use async_trait::async_trait;
use rand::{CryptoRng, RngCore};
use serde::{Deserialize, Serialize};
@ -8,8 +7,6 @@ use std::ops::{Add, Sub};
pub use curve25519_dalek::scalar::Scalar;
pub use monero::{Address, Network, PrivateKey, PublicKey};
pub const MIN_CONFIRMATIONS: u32 = 10;
pub fn random_private_key<R: RngCore + CryptoRng>(rng: &mut R) -> PrivateKey {
let scalar = Scalar::random(rng);
@ -103,35 +100,6 @@ impl From<Amount> for u64 {
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TransferProof {
tx_hash: TxHash,
#[serde(with = "monero_private_key")]
tx_key: PrivateKey,
}
impl TransferProof {
pub fn new(tx_hash: TxHash, tx_key: PrivateKey) -> Self {
Self { tx_hash, tx_key }
}
pub fn tx_hash(&self) -> TxHash {
self.tx_hash.clone()
}
pub fn tx_key(&self) -> PrivateKey {
self.tx_key
}
}
// TODO: add constructor/ change String to fixed length byte array
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TxHash(pub String);
impl From<TxHash> for String {
fn from(from: TxHash) -> Self {
from.0
}
}
#[async_trait]
pub trait Transfer {
async fn transfer(
@ -139,29 +107,17 @@ pub trait Transfer {
public_spend_key: PublicKey,
public_view_key: PublicViewKey,
amount: Amount,
) -> anyhow::Result<(TransferProof, Amount)>;
) -> anyhow::Result<Amount>;
}
#[async_trait]
pub trait WatchForTransfer {
async fn watch_for_transfer(
&self,
public_spend_key: PublicKey,
public_view_key: PublicViewKey,
transfer_proof: TransferProof,
amount: Amount,
expected_confirmations: u32,
) -> Result<(), InsufficientFunds>;
}
#[async_trait]
pub trait WatchForTransferImproved {
async fn watch_for_transfer_improved(
&self,
address: Address,
amount: Amount,
private_view_key: PrivateViewKey,
) -> Result<(), InsufficientFunds>;
);
}
#[derive(Debug, Clone, Copy, thiserror::Error)]

View file

@ -4,10 +4,10 @@ use backoff::{backoff::Constant as ConstantBackoff, future::FutureOperation as _
use futures::TryFutureExt;
use monero::{Address, Network, PrivateKey};
use monero_harness::rpc::wallet;
use std::{str::FromStr, time::Duration};
use std::time::Duration;
use xmr_btc::monero::{
Address, Amount, CreateWalletForOutput, InsufficientFunds, Network, PrivateKey, PrivateViewKey,
PublicKey, PublicViewKey, Transfer, TransferProof, TxHash, WatchForTransfer, WatchForTransferImproved,
Amount, CreateWalletForOutput, PrivateViewKey, PublicKey, PublicViewKey, Transfer,
WatchForTransfer,
};
pub struct Wallet {
@ -33,7 +33,7 @@ impl Transfer for Wallet {
public_spend_key: PublicKey,
public_view_key: PublicViewKey,
amount: Amount,
) -> Result<(TransferProof, Amount)> {
) -> Result<Amount> {
let destination_address =
Address::standard(Network::Mainnet, public_spend_key, public_view_key.into());
@ -42,12 +42,7 @@ impl Transfer for Wallet {
.transfer(0, amount.as_piconero(), &destination_address.to_string())
.await?;
let tx_hash = TxHash(res.tx_hash);
let tx_key = PrivateKey::from_str(&res.tx_key)?;
let fee = Amount::from_piconero(res.fee);
Ok((TransferProof::new(tx_hash, tx_key), fee))
Ok(Amount::from_piconero(res.fee))
}
}
@ -79,67 +74,11 @@ impl CreateWalletForOutput for Wallet {
#[async_trait]
impl WatchForTransfer for Wallet {
async fn watch_for_transfer(
&self,
public_spend_key: PublicKey,
public_view_key: PublicViewKey,
transfer_proof: TransferProof,
expected_amount: Amount,
expected_confirmations: u32,
) -> Result<(), InsufficientFunds> {
enum Error {
TxNotFound,
InsufficientConfirmations,
InsufficientFunds { expected: Amount, actual: Amount },
}
let address = Address::standard(Network::Mainnet, public_spend_key, public_view_key.into());
let res = (|| async {
// NOTE: Currently, this is conflating IO errors with the transaction not being
// in the blockchain yet, or not having enough confirmations on it. All these
// errors warrant a retry, but the strategy should probably differ per case
let proof = self
.inner
.check_tx_key(
&String::from(transfer_proof.tx_hash()),
&transfer_proof.tx_key().to_string(),
&address.to_string(),
)
.await
.map_err(|_| backoff::Error::Transient(Error::TxNotFound))?;
if proof.received != expected_amount.as_piconero() {
return Err(backoff::Error::Permanent(Error::InsufficientFunds {
expected: expected_amount,
actual: Amount::from_piconero(proof.received),
}));
}
if proof.confirmations < expected_confirmations {
return Err(backoff::Error::Transient(Error::InsufficientConfirmations));
}
Ok(proof)
})
.retry(ConstantBackoff::new(Duration::from_secs(1)))
.await;
if let Err(Error::InsufficientFunds { expected, actual }) = res {
return Err(InsufficientFunds { expected, actual });
};
Ok(())
}
}
#[async_trait]
impl WatchForTransferImproved for Wallet {
async fn watch_for_transfer_improved(
&self,
address: Address,
expected_amount: Amount,
private_view_key: PrivateViewKey,
) -> Result<(), InsufficientFunds> {
) {
let address = address.to_string();
let private_view_key = PrivateKey::from(private_view_key).to_string();
let load_address = || {
@ -148,11 +87,13 @@ impl WatchForTransferImproved for Wallet {
.map_err(backoff::Error::Transient)
};
// QUESTION: Should we really retry every error?
load_address
.retry(ConstantBackoff::new(Duration::from_secs(1)))
.await
.expect("transient error is never returned");
// QUESTION: Should we retry this error at all?
let refresh = || self.watch_only.refresh().map_err(backoff::Error::Transient);
refresh
@ -160,25 +101,24 @@ impl WatchForTransferImproved for Wallet {
.await
.expect("transient error is never returned");
let get_balance = || {
self.watch_only
let check_balance = || async {
let balance = self
.watch_only
.get_balance(0)
.map_err(backoff::Error::Transient)
.await
.map_err(|_| backoff::Error::Transient("io"))?;
let balance = Amount::from_piconero(balance);
if balance != expected_amount {
return Err(backoff::Error::Transient("insufficient funds"));
}
Ok(())
};
let balance = get_balance
check_balance
.retry(ConstantBackoff::new(Duration::from_secs(1)))
.await
.expect("transient error is never returned");
let balance = Amount::from_piconero(balance);
if balance != expected_amount {
return Err(InsufficientFunds {
expected: expected_amount,
actual: balance,
});
}
Ok(())
}
}

View file

@ -16,20 +16,18 @@ use monero_harness::Monero;
use rand::rngs::OsRng;
use std::{convert::TryInto, sync::Arc};
use testcontainers::clients::Cli;
use tokio::sync::Mutex;
use tracing::info;
use xmr_btc::{
alice::{self, ReceiveBitcoinRedeemEncsig},
bitcoin::{self, BroadcastSignedTransaction, EncryptedSignature, SignTxLock},
bob::{self, ReceiveTransferProof},
monero::{CreateWalletForOutput, Transfer, TransferProof},
bob,
monero::{CreateWalletForOutput, Transfer},
};
/// Time given to Bob to get the Bitcoin lock transaction included in a block.
const BITCOIN_TX_LOCK_TIMEOUT: u64 = 5;
type AliceNetwork = Network<EncryptedSignature>;
type BobNetwork = Network<TransferProof>;
#[derive(Debug)]
struct Network<M> {
@ -46,13 +44,6 @@ impl<M> Network<M> {
}
}
#[async_trait]
impl ReceiveTransferProof for BobNetwork {
async fn receive_transfer_proof(&mut self) -> TransferProof {
self.receiver.next().await.unwrap()
}
}
#[async_trait]
impl ReceiveBitcoinRedeemEncsig for AliceNetwork {
async fn receive_bitcoin_redeem_encsig(&mut self) -> EncryptedSignature {
@ -101,10 +92,7 @@ impl Default for BobBehaviour {
}
async fn swap_as_alice(
network: Arc<Mutex<AliceNetwork>>,
// FIXME: It would be more intuitive to have a single network/transport struct instead of
// splitting into two, but Rust ownership rules make this tedious
mut sender: Sender<TransferProof>,
network: AliceNetwork,
monero_wallet: Arc<harness::wallet::monero::Wallet>,
bitcoin_wallet: Arc<harness::wallet::bitcoin::Wallet>,
behaviour: AliceBehaviour,
@ -130,11 +118,9 @@ async fn swap_as_alice(
public_view_key,
}) => {
if behaviour.lock_xmr {
let (transfer_proof, _) = monero_wallet
let _ = monero_wallet
.transfer(public_spend_key, public_view_key, amount)
.await?;
sender.send(transfer_proof).await?;
}
}
GeneratorState::Yielded(alice::Action::RedeemBtc(tx)) => {
@ -168,7 +154,6 @@ async fn swap_as_alice(
}
async fn swap_as_bob(
network: Arc<Mutex<BobNetwork>>,
mut sender: Sender<EncryptedSignature>,
monero_wallet: Arc<harness::wallet::monero::Wallet>,
bitcoin_wallet: Arc<harness::wallet::bitcoin::Wallet>,
@ -176,7 +161,6 @@ async fn swap_as_bob(
state: bob::State2,
) -> Result<()> {
let mut action_generator = bob::action_generator(
network,
monero_wallet.clone(),
bitcoin_wallet.clone(),
state,
@ -274,19 +258,16 @@ async fn on_chain_happy_path() {
let bob_monero_wallet = Arc::new(bob_node.monero_wallet);
let (alice_network, bob_sender) = Network::<EncryptedSignature>::new();
let (bob_network, alice_sender) = Network::<TransferProof>::new();
try_join(
swap_as_alice(
Arc::new(Mutex::new(alice_network)),
alice_sender,
alice_network,
alice_monero_wallet.clone(),
alice_bitcoin_wallet.clone(),
AliceBehaviour::default(),
alice,
),
swap_as_bob(
Arc::new(Mutex::new(bob_network)),
bob_sender,
bob_monero_wallet.clone(),
bob_bitcoin_wallet.clone(),
@ -371,12 +352,10 @@ async fn on_chain_both_refund_if_alice_never_redeems() {
let bob_monero_wallet = Arc::new(bob_node.monero_wallet);
let (alice_network, bob_sender) = Network::<EncryptedSignature>::new();
let (bob_network, alice_sender) = Network::<TransferProof>::new();
try_join(
swap_as_alice(
Arc::new(Mutex::new(alice_network)),
alice_sender,
alice_network,
alice_monero_wallet.clone(),
alice_bitcoin_wallet.clone(),
AliceBehaviour {
@ -386,7 +365,6 @@ async fn on_chain_both_refund_if_alice_never_redeems() {
alice,
),
swap_as_bob(
Arc::new(Mutex::new(bob_network)),
bob_sender,
bob_monero_wallet.clone(),
bob_bitcoin_wallet.clone(),
@ -468,18 +446,15 @@ async fn on_chain_alice_punishes_if_bob_never_acts_after_fund() {
let bob_monero_wallet = Arc::new(bob_node.monero_wallet);
let (alice_network, bob_sender) = Network::<EncryptedSignature>::new();
let (bob_network, alice_sender) = Network::<TransferProof>::new();
let alice_swap = swap_as_alice(
Arc::new(Mutex::new(alice_network)),
alice_sender,
alice_network,
alice_monero_wallet.clone(),
alice_bitcoin_wallet.clone(),
AliceBehaviour::default(),
alice,
);
let bob_swap = swap_as_bob(
Arc::new(Mutex::new(bob_network)),
bob_sender,
bob_monero_wallet.clone(),
bob_bitcoin_wallet.clone(),