From aeeffccda2c9cac9548eb19df2c36431212c397e Mon Sep 17 00:00:00 2001 From: Lorenzo Tucci Date: Mon, 5 Dec 2022 20:11:58 +0100 Subject: [PATCH] moving methods to api and validating addresses for rpc --- swap/src/api.rs | 26 +++--------- swap/src/api/request.rs | 49 +++++++++++++++------- swap/src/cli/command.rs | 9 ++-- swap/src/rpc/methods.rs | 91 ++++++++++++++++++++++++++--------------- 4 files changed, 101 insertions(+), 74 deletions(-) diff --git a/swap/src/api.rs b/swap/src/api.rs index 0b752fbd..7347f500 100644 --- a/swap/src/api.rs +++ b/swap/src/api.rs @@ -1,36 +1,19 @@ pub mod request; -use crate::bitcoin::{Amount, TxLock}; use crate::cli::command::{Bitcoin, Monero, Tor}; -use crate::cli::{list_sellers, EventLoop, SellerStatus}; use crate::database::open_db; use crate::env::{Config as EnvConfig, GetConfig, Mainnet, Testnet}; use crate::fs::system_data_dir; -use crate::libp2p_ext::MultiAddrExt; -use crate::network::quote::{BidQuote, ZeroQuoteReceived}; use crate::network::rendezvous::XmrBtcNamespace; -use crate::network::swarm; -use crate::protocol::bob::{BobState, Swap}; -use crate::protocol::{bob, Database}; +use crate::protocol::Database; use crate::seed::Seed; -use crate::{bitcoin, cli, monero, rpc}; -use anyhow::{bail, Context as AnyContext, Result}; -use comfy_table::Table; -use libp2p::core::Multiaddr; -use qrcode::render::unicode; -use qrcode::QrCode; -use serde::ser::{Serialize, SerializeStruct, Serializer}; -use serde_json::json; -use std::cmp::min; -use std::convert::TryInto; +use crate::{bitcoin, cli, monero}; +use anyhow::{Context as AnyContext, Result}; use std::fmt; -use std::future::Future; use std::net::SocketAddr; use std::path::PathBuf; use std::sync::Arc; -use std::time::Duration; use url::Url; use std::sync::Once; -use uuid::Uuid; static START: Once = Once::new(); @@ -43,7 +26,7 @@ pub struct Config { seed: Option, debug: bool, json: bool, - is_testnet: bool, + pub is_testnet: bool, } pub struct Context { @@ -134,6 +117,7 @@ impl Context { Ok(init) } + } impl fmt::Debug for Context { diff --git a/swap/src/api/request.rs b/swap/src/api/request.rs index 372840ea..9bfe1504 100644 --- a/swap/src/api/request.rs +++ b/swap/src/api/request.rs @@ -1,35 +1,23 @@ use crate::bitcoin::{Amount, TxLock}; -use crate::cli::command::{Bitcoin, Monero, Tor}; use crate::cli::{list_sellers, EventLoop, SellerStatus}; -use crate::database::open_db; -use crate::env::{Config as EnvConfig, GetConfig, Mainnet, Testnet}; -use crate::fs::system_data_dir; use crate::libp2p_ext::MultiAddrExt; use crate::network::quote::{BidQuote, ZeroQuoteReceived}; -use crate::network::rendezvous::XmrBtcNamespace; use crate::network::swarm; use crate::protocol::bob::{BobState, Swap}; -use crate::protocol::{bob, Database}; -use crate::seed::Seed; +use crate::protocol::bob; use crate::{bitcoin, cli, monero, rpc}; use anyhow::{bail, Context as AnyContext, Result}; -use comfy_table::Table; use libp2p::core::Multiaddr; use qrcode::render::unicode; use qrcode::QrCode; -use serde::ser::{Serialize, SerializeStruct, Serializer}; use serde_json::json; use std::cmp::min; use std::convert::TryInto; -use std::fmt; use std::future::Future; -use std::net::SocketAddr; -use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; -use url::Url; use uuid::Uuid; -use crate::api::{Config, Context}; +use crate::api::Context; #[derive(PartialEq, Debug)] @@ -53,9 +41,12 @@ pub struct Params { pub enum Method { BuyXmr, History, + RawHistory, Config, WithdrawBtc, Balance, + GetSeller, + SwapStartDate, Resume, Cancel, Refund, @@ -137,6 +128,7 @@ impl Request { tracing::info!(%amount, %fees, "Determined swap amount"); context.db.insert_peer_id(swap_id, seller_peer_id).await?; + context .db .insert_monero_address(swap_id, monero_receive_address) @@ -178,6 +170,35 @@ impl Request { } json!({ "swaps": vec }) } + Method::RawHistory => { + let raw_history = context.db.raw_all().await?; + json!({ + "raw_history": raw_history + }) + } + Method::GetSeller => { + let swap_id = self.params.swap_id.unwrap(); + let peerId = context.db.get_peer_id(swap_id).await?; + + let addresses = context.db.get_addresses(peerId).await?; + + json!({ + "peerId": peerId.to_base58(), + "addresses": addresses + }) + } + Method::SwapStartDate => { + let swap_id = self.params.swap_id.unwrap(); + + let start_date = context + .db + .get_swap_start_date(swap_id) + .await?; + + json!({ + "start_date": start_date, + }) + } Method::Config => { // tracing::info!(path=%data_dir.display(), "Data directory"); // tracing::info!(path=%format!("{}/logs", data_dir.display()), diff --git a/swap/src/cli/command.rs b/swap/src/cli/command.rs index ac7f60c6..42848820 100644 --- a/swap/src/cli/command.rs +++ b/swap/src/cli/command.rs @@ -1,13 +1,10 @@ -use crate::api::{Context, Config}; +use crate::api::Context; use crate::api::request::{Request, Params, Method}; use crate::bitcoin::{Amount, bitcoin_address}; use crate::monero::monero_address; -use crate::fs::system_data_dir; -use crate::{env, monero}; -use anyhow::{bail, Context as AnyContext, Result}; -use bitcoin::{Address, AddressType}; +use crate::monero; +use anyhow::Result; use libp2p::core::Multiaddr; -use serde::Serialize; use std::ffi::OsString; use std::net::SocketAddr; use std::path::PathBuf; diff --git a/swap/src/rpc/methods.rs b/swap/src/rpc/methods.rs index ab1c5046..d0887450 100644 --- a/swap/src/rpc/methods.rs +++ b/swap/src/rpc/methods.rs @@ -1,11 +1,11 @@ use crate::api::{Context}; use crate::api::request::{Params, Request, Method}; //use crate::rpc::Error; -use anyhow::{Error, Result}; +use anyhow::Result; use crate::{bitcoin, monero}; +use crate::{bitcoin::bitcoin_address, monero::monero_address}; use jsonrpsee::http_server::RpcModule; use libp2p::core::Multiaddr; -use serde_json::json; use std::collections::HashMap; use std::str::FromStr; use std::sync::Arc; @@ -24,12 +24,8 @@ pub fn register_modules(context: Arc) -> RpcModule> { }) .unwrap(); module - .register_async_method("raw_get_history", |_, context| async move { - context - .db - .raw_all() - .await - .map_err(|err| jsonrpsee_core::Error::Custom(err.to_string())) + .register_async_method("get_raw_history", |_, context| async move { + get_raw_history(&context).await }) .unwrap(); module @@ -41,22 +37,7 @@ pub fn register_modules(context: Arc) -> RpcModule> { })?) .map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?; - let peerId = context - .db - .get_peer_id(swap_id) - .await - .map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?; - - let addresses = context - .db - .get_addresses(peerId) - .await - .map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?; - - Ok(json!({ - "peerId": peerId.to_base58(), - "addresses": addresses - })) + get_seller(swap_id, &context).await }) .unwrap(); module @@ -68,15 +49,7 @@ pub fn register_modules(context: Arc) -> RpcModule> { })?) .map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?; - let start_date = context - .db - .get_swap_start_date(swap_id) - .await - .map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?; - - Ok(json!({ - "start_date": start_date, - })) + get_swap_start_date(swap_id, &context).await }) .unwrap(); module @@ -111,6 +84,7 @@ pub fn register_modules(context: Arc) -> RpcModule> { jsonrpsee_core::Error::Custom("Does not contain address".to_string()) })?) .map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?; + let withdraw_address = bitcoin_address::validate(withdraw_address, context.config.is_testnet)?; withdraw_btc(withdraw_address, amount, &context).await }) @@ -128,6 +102,8 @@ pub fn register_modules(context: Arc) -> RpcModule> { ) .map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?; + let bitcoin_change_address = bitcoin_address::validate(bitcoin_change_address, context.config.is_testnet)?; + let monero_receive_address = monero::Address::from_str( params.get("monero_receive_address").ok_or_else(|| { jsonrpsee_core::Error::Custom( @@ -137,6 +113,8 @@ pub fn register_modules(context: Arc) -> RpcModule> { ) .map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?; + let monero_receive_address = monero_address::validate(monero_receive_address, context.config.is_testnet)?; + let seller = Multiaddr::from_str(params.get("seller").ok_or_else(|| { jsonrpsee_core::Error::Custom("Does not contain seller".to_string()) })?) @@ -188,6 +166,53 @@ async fn get_history(context: &Arc) -> Result) -> Result { + let request = Request { + params: Params::default(), + cmd: Method::RawHistory, + }; + let history = request.call(Arc::clone(context)) + .await + .map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?; + + Ok(history) +} + +async fn get_seller( + swap_id: Uuid, + context: &Arc +) -> Result { + let request = Request { + params: Params { + swap_id: Some(swap_id), + ..Default::default() + }, + cmd: Method::GetSeller, + }; + let result = request.call(Arc::clone(context)) + .await + .map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?; + + Ok(result) +} + +async fn get_swap_start_date( + swap_id: Uuid, + context: &Arc +) -> Result { + let request = Request { + params: Params { + swap_id: Some(swap_id), + ..Default::default() + }, + cmd: Method::SwapStartDate, + }; + let result = request.call(Arc::clone(context)) + .await + .map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?; + + Ok(result) +} async fn resume_swap( swap_id: Uuid,