parent
f22729c5da
commit
e7504de76c
@ -0,0 +1,125 @@
|
||||
use anyhow::{bail, Result};
|
||||
use libp2p::{
|
||||
request_response::{
|
||||
handler::RequestProtocol, ProtocolSupport, RequestResponse, RequestResponseConfig,
|
||||
RequestResponseEvent, RequestResponseMessage,
|
||||
},
|
||||
swarm::{NetworkBehaviourAction, NetworkBehaviourEventProcess, PollParameters},
|
||||
NetworkBehaviour,
|
||||
};
|
||||
use rand::rngs::OsRng;
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
task::{Context, Poll},
|
||||
time::Duration,
|
||||
};
|
||||
use tracing::error;
|
||||
|
||||
use crate::network::request_response::{AliceToBob, BobToAlice, Codec, Protocol};
|
||||
use xmr_btc::{alice::State0, bob};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum OutEvent {
|
||||
Msg(bob::Message0),
|
||||
}
|
||||
|
||||
/// A `NetworkBehaviour` that represents getting the amounts of an XMR/BTC swap.
|
||||
#[derive(NetworkBehaviour)]
|
||||
#[behaviour(out_event = "OutEvent", poll_method = "poll")]
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub struct Message0 {
|
||||
rr: RequestResponse<Codec>,
|
||||
#[behaviour(ignore)]
|
||||
events: VecDeque<OutEvent>,
|
||||
#[behaviour(ignore)]
|
||||
state: Option<State0>,
|
||||
}
|
||||
|
||||
impl Message0 {
|
||||
pub fn new(timeout: Duration) -> Self {
|
||||
let mut config = RequestResponseConfig::default();
|
||||
config.set_request_timeout(timeout);
|
||||
|
||||
Self {
|
||||
rr: RequestResponse::new(
|
||||
Codec::default(),
|
||||
vec![(Protocol, ProtocolSupport::Full)],
|
||||
config,
|
||||
),
|
||||
events: Default::default(),
|
||||
state: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_state(&mut self, state: State0) -> Result<()> {
|
||||
if self.state.is_some() {
|
||||
bail!("Trying to set state a second time");
|
||||
}
|
||||
self.state = Some(state);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn poll(
|
||||
&mut self,
|
||||
_: &mut Context<'_>,
|
||||
_: &mut impl PollParameters,
|
||||
) -> Poll<NetworkBehaviourAction<RequestProtocol<Codec>, OutEvent>> {
|
||||
if let Some(event) = self.events.pop_front() {
|
||||
return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event));
|
||||
}
|
||||
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkBehaviourEventProcess<RequestResponseEvent<BobToAlice, AliceToBob>> for Message0 {
|
||||
fn inject_event(&mut self, event: RequestResponseEvent<BobToAlice, AliceToBob>) {
|
||||
match event {
|
||||
RequestResponseEvent::Message {
|
||||
peer: _,
|
||||
message:
|
||||
RequestResponseMessage::Request {
|
||||
request,
|
||||
request_id: _,
|
||||
channel,
|
||||
},
|
||||
} => match request {
|
||||
BobToAlice::Message0(msg) => {
|
||||
let response = match self.state {
|
||||
None => panic!("No state, did you forget to set it?"),
|
||||
Some(state) => {
|
||||
// TODO: Get OsRng from somewhere?
|
||||
AliceToBob::Message0(state.next_message(&mut OsRng))
|
||||
}
|
||||
};
|
||||
self.rr.send_response(channel, response);
|
||||
self.events.push_back(OutEvent::Msg(msg));
|
||||
}
|
||||
_ => panic!("unexpected request"),
|
||||
},
|
||||
RequestResponseEvent::Message {
|
||||
peer: _,
|
||||
message:
|
||||
RequestResponseMessage::Response {
|
||||
response: _,
|
||||
request_id: _,
|
||||
},
|
||||
} => panic!("unexpected response"),
|
||||
RequestResponseEvent::InboundFailure {
|
||||
peer: _,
|
||||
request_id: _,
|
||||
error,
|
||||
} => {
|
||||
error!("Inbound failure: {:?}", error);
|
||||
}
|
||||
RequestResponseEvent::OutboundFailure {
|
||||
peer: _,
|
||||
request_id: _,
|
||||
error,
|
||||
} => {
|
||||
error!("Outbound failure: {:?}", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1 +1,114 @@
|
||||
pub use bitcoin::Amount;
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use backoff::{future::FutureOperation as _, ExponentialBackoff};
|
||||
use bitcoin::{util::psbt::PartiallySignedTransaction, Address, Amount, Transaction, Txid};
|
||||
use bitcoin_harness::bitcoind_rpc::PsbtBase64;
|
||||
use reqwest::Url;
|
||||
use xmr_btc::{
|
||||
bitcoin::{
|
||||
BroadcastSignedTransaction, BuildTxLockPsbt, SignTxLock, TxLock, WatchForRawTransaction,
|
||||
},
|
||||
MedianTime,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Wallet(pub bitcoin_harness::Wallet);
|
||||
|
||||
impl Wallet {
|
||||
pub async fn new(name: &str, url: &Url) -> Result<Self> {
|
||||
let wallet = bitcoin_harness::Wallet::new(name, url.clone()).await?;
|
||||
|
||||
Ok(Self(wallet))
|
||||
}
|
||||
|
||||
pub async fn balance(&self) -> Result<Amount> {
|
||||
let balance = self.0.balance().await?;
|
||||
Ok(balance)
|
||||
}
|
||||
|
||||
pub async fn new_address(&self) -> Result<Address> {
|
||||
self.0.new_address().await.map_err(Into::into)
|
||||
}
|
||||
|
||||
pub async fn transaction_fee(&self, txid: Txid) -> Result<Amount> {
|
||||
let fee = self
|
||||
.0
|
||||
.get_wallet_transaction(txid)
|
||||
.await
|
||||
.map(|res| bitcoin::Amount::from_btc(-res.fee))??;
|
||||
|
||||
// FIXME: Handle re-export of bitcoin::Amount correctly.
|
||||
let fee = Amount::from_sat(fee.as_sat());
|
||||
Ok(fee)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BuildTxLockPsbt for Wallet {
|
||||
async fn build_tx_lock_psbt(
|
||||
&self,
|
||||
output_address: Address,
|
||||
output_amount: Amount,
|
||||
) -> Result<PartiallySignedTransaction> {
|
||||
let psbt = self.0.fund_psbt(output_address, output_amount).await?;
|
||||
let as_hex = base64::decode(psbt)?;
|
||||
|
||||
let psbt = bitcoin::consensus::deserialize(&as_hex)?;
|
||||
|
||||
Ok(psbt)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl SignTxLock for Wallet {
|
||||
async fn sign_tx_lock(&self, tx_lock: TxLock) -> Result<Transaction> {
|
||||
let psbt = PartiallySignedTransaction::from(tx_lock);
|
||||
|
||||
let psbt = bitcoin::consensus::serialize(&psbt);
|
||||
let as_base64 = base64::encode(psbt);
|
||||
|
||||
let psbt = self.0.wallet_process_psbt(PsbtBase64(as_base64)).await?;
|
||||
let PsbtBase64(signed_psbt) = PsbtBase64::from(psbt);
|
||||
|
||||
let as_hex = base64::decode(signed_psbt)?;
|
||||
let psbt: PartiallySignedTransaction = bitcoin::consensus::deserialize(&as_hex)?;
|
||||
|
||||
let tx = psbt.extract_tx();
|
||||
|
||||
Ok(tx)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BroadcastSignedTransaction for Wallet {
|
||||
async fn broadcast_signed_transaction(&self, transaction: Transaction) -> Result<Txid> {
|
||||
let txid = self.0.send_raw_transaction(transaction).await?;
|
||||
Ok(txid)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl WatchForRawTransaction for Wallet {
|
||||
async fn watch_for_raw_transaction(&self, txid: Txid) -> Transaction {
|
||||
(|| async { Ok(self.0.get_raw_transaction(txid).await?) })
|
||||
.retry(ExponentialBackoff {
|
||||
max_elapsed_time: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.expect("transient errors to be retried")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl MedianTime for Wallet {
|
||||
async fn median_time(&self) -> u32 {
|
||||
(|| async { Ok(self.0.median_time().await?) })
|
||||
.retry(ExponentialBackoff {
|
||||
max_elapsed_time: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.expect("transient errors to be retried")
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,97 @@
|
||||
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::error;
|
||||
|
||||
use crate::network::request_response::{AliceToBob, BobToAlice, Codec, Protocol};
|
||||
use xmr_btc::{alice, bob};
|
||||
|
||||
#[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 Message0 {
|
||||
rr: RequestResponse<Codec>,
|
||||
#[behaviour(ignore)]
|
||||
events: VecDeque<OutEvent>,
|
||||
}
|
||||
|
||||
impl Message0 {
|
||||
pub fn new(timeout: Duration) -> Self {
|
||||
let mut config = RequestResponseConfig::default();
|
||||
config.set_request_timeout(timeout);
|
||||
|
||||
Self {
|
||||
rr: RequestResponse::new(
|
||||
Codec::default(),
|
||||
vec![(Protocol, ProtocolSupport::Full)],
|
||||
config,
|
||||
),
|
||||
events: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send(&mut self, alice: PeerId, msg: bob::Message0) {
|
||||
let msg = BobToAlice::Message0(msg);
|
||||
let _id = self.rr.send_request(&alice, msg);
|
||||
}
|
||||
|
||||
fn poll(
|
||||
&mut self,
|
||||
_: &mut Context<'_>,
|
||||
_: &mut impl PollParameters,
|
||||
) -> Poll<NetworkBehaviourAction<RequestProtocol<Codec>, OutEvent>> {
|
||||
if let Some(event) = self.events.pop_front() {
|
||||
return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event));
|
||||
}
|
||||
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkBehaviourEventProcess<RequestResponseEvent<BobToAlice, AliceToBob>> for Message0 {
|
||||
fn inject_event(&mut self, event: RequestResponseEvent<BobToAlice, AliceToBob>) {
|
||||
match event {
|
||||
RequestResponseEvent::Message {
|
||||
peer: _,
|
||||
message: RequestResponseMessage::Request { .. },
|
||||
} => panic!("Bob should never get a request from Alice"),
|
||||
RequestResponseEvent::Message {
|
||||
peer: _,
|
||||
message:
|
||||
RequestResponseMessage::Response {
|
||||
response,
|
||||
request_id: _,
|
||||
},
|
||||
} => match response {
|
||||
AliceToBob::Message0(msg) => self.events.push_back(OutEvent::Msg(msg)),
|
||||
},
|
||||
|
||||
RequestResponseEvent::InboundFailure { .. } => {
|
||||
panic!("Bob should never get a request from Alice, so should never get an InboundFailure");
|
||||
}
|
||||
RequestResponseEvent::OutboundFailure {
|
||||
peer: _,
|
||||
request_id: _,
|
||||
error,
|
||||
} => {
|
||||
error!("Outbound failure: {:?}", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,30 +1,27 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
use serde::{de::Error, Deserialize, Deserializer, Serializer};
|
||||
|
||||
#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Amount(u64);
|
||||
use xmr_btc::monero::Amount;
|
||||
|
||||
impl Amount {
|
||||
/// Create an [Amount] with piconero precision and the given number of
|
||||
/// piconeros.
|
||||
///
|
||||
/// A piconero (a.k.a atomic unit) is equal to 1e-12 XMR.
|
||||
pub fn from_piconero(amount: u64) -> Self {
|
||||
Amount(amount)
|
||||
}
|
||||
pub fn as_piconero(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
pub mod amount_serde {
|
||||
use super::*;
|
||||
use std::str::FromStr;
|
||||
|
||||
impl From<Amount> for u64 {
|
||||
fn from(from: Amount) -> u64 {
|
||||
from.0
|
||||
pub fn serialize<S>(value: &Amount, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(&value.as_piconero().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Amount {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{} piconeros", self.0)
|
||||
pub fn deserialize<'de, D>(deserializer: D) -> Result<Amount, <D as Deserializer<'de>>::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let value = String::deserialize(deserializer)?;
|
||||
let value =
|
||||
u64::from_str(value.as_str()).map_err(<D as Deserializer<'de>>::Error::custom)?;
|
||||
let amount = Amount::from_piconero(value);
|
||||
|
||||
Ok(amount)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in new issue