moving methods to api and validating addresses for rpc

This commit is contained in:
Lorenzo Tucci 2022-12-05 20:11:58 +01:00
parent a26822d85b
commit aeeffccda2
No known key found for this signature in database
GPG key ID: D98C4FA2CDF590A0
4 changed files with 101 additions and 74 deletions

View file

@ -1,36 +1,19 @@
pub mod request; pub mod request;
use crate::bitcoin::{Amount, TxLock};
use crate::cli::command::{Bitcoin, Monero, Tor}; use crate::cli::command::{Bitcoin, Monero, Tor};
use crate::cli::{list_sellers, EventLoop, SellerStatus};
use crate::database::open_db; use crate::database::open_db;
use crate::env::{Config as EnvConfig, GetConfig, Mainnet, Testnet}; use crate::env::{Config as EnvConfig, GetConfig, Mainnet, Testnet};
use crate::fs::system_data_dir; 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::rendezvous::XmrBtcNamespace;
use crate::network::swarm; use crate::protocol::Database;
use crate::protocol::bob::{BobState, Swap};
use crate::protocol::{bob, Database};
use crate::seed::Seed; use crate::seed::Seed;
use crate::{bitcoin, cli, monero, rpc}; use crate::{bitcoin, cli, monero};
use anyhow::{bail, Context as AnyContext, Result}; use anyhow::{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::fmt;
use std::future::Future;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration;
use url::Url; use url::Url;
use std::sync::Once; use std::sync::Once;
use uuid::Uuid;
static START: Once = Once::new(); static START: Once = Once::new();
@ -43,7 +26,7 @@ pub struct Config {
seed: Option<Seed>, seed: Option<Seed>,
debug: bool, debug: bool,
json: bool, json: bool,
is_testnet: bool, pub is_testnet: bool,
} }
pub struct Context { pub struct Context {
@ -134,6 +117,7 @@ impl Context {
Ok(init) Ok(init)
} }
} }
impl fmt::Debug for Context { impl fmt::Debug for Context {

View file

@ -1,35 +1,23 @@
use crate::bitcoin::{Amount, TxLock}; use crate::bitcoin::{Amount, TxLock};
use crate::cli::command::{Bitcoin, Monero, Tor};
use crate::cli::{list_sellers, EventLoop, SellerStatus}; 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::libp2p_ext::MultiAddrExt;
use crate::network::quote::{BidQuote, ZeroQuoteReceived}; use crate::network::quote::{BidQuote, ZeroQuoteReceived};
use crate::network::rendezvous::XmrBtcNamespace;
use crate::network::swarm; use crate::network::swarm;
use crate::protocol::bob::{BobState, Swap}; use crate::protocol::bob::{BobState, Swap};
use crate::protocol::{bob, Database}; use crate::protocol::bob;
use crate::seed::Seed;
use crate::{bitcoin, cli, monero, rpc}; use crate::{bitcoin, cli, monero, rpc};
use anyhow::{bail, Context as AnyContext, Result}; use anyhow::{bail, Context as AnyContext, Result};
use comfy_table::Table;
use libp2p::core::Multiaddr; use libp2p::core::Multiaddr;
use qrcode::render::unicode; use qrcode::render::unicode;
use qrcode::QrCode; use qrcode::QrCode;
use serde::ser::{Serialize, SerializeStruct, Serializer};
use serde_json::json; use serde_json::json;
use std::cmp::min; use std::cmp::min;
use std::convert::TryInto; use std::convert::TryInto;
use std::fmt;
use std::future::Future; use std::future::Future;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use url::Url;
use uuid::Uuid; use uuid::Uuid;
use crate::api::{Config, Context}; use crate::api::Context;
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
@ -53,9 +41,12 @@ pub struct Params {
pub enum Method { pub enum Method {
BuyXmr, BuyXmr,
History, History,
RawHistory,
Config, Config,
WithdrawBtc, WithdrawBtc,
Balance, Balance,
GetSeller,
SwapStartDate,
Resume, Resume,
Cancel, Cancel,
Refund, Refund,
@ -137,6 +128,7 @@ impl Request {
tracing::info!(%amount, %fees, "Determined swap amount"); tracing::info!(%amount, %fees, "Determined swap amount");
context.db.insert_peer_id(swap_id, seller_peer_id).await?; context.db.insert_peer_id(swap_id, seller_peer_id).await?;
context context
.db .db
.insert_monero_address(swap_id, monero_receive_address) .insert_monero_address(swap_id, monero_receive_address)
@ -178,6 +170,35 @@ impl Request {
} }
json!({ "swaps": vec }) 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 => { Method::Config => {
// tracing::info!(path=%data_dir.display(), "Data directory"); // tracing::info!(path=%data_dir.display(), "Data directory");
// tracing::info!(path=%format!("{}/logs", data_dir.display()), // tracing::info!(path=%format!("{}/logs", data_dir.display()),

View file

@ -1,13 +1,10 @@
use crate::api::{Context, Config}; use crate::api::Context;
use crate::api::request::{Request, Params, Method}; use crate::api::request::{Request, Params, Method};
use crate::bitcoin::{Amount, bitcoin_address}; use crate::bitcoin::{Amount, bitcoin_address};
use crate::monero::monero_address; use crate::monero::monero_address;
use crate::fs::system_data_dir; use crate::monero;
use crate::{env, monero}; use anyhow::Result;
use anyhow::{bail, Context as AnyContext, Result};
use bitcoin::{Address, AddressType};
use libp2p::core::Multiaddr; use libp2p::core::Multiaddr;
use serde::Serialize;
use std::ffi::OsString; use std::ffi::OsString;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::path::PathBuf; use std::path::PathBuf;

View file

@ -1,11 +1,11 @@
use crate::api::{Context}; use crate::api::{Context};
use crate::api::request::{Params, Request, Method}; use crate::api::request::{Params, Request, Method};
//use crate::rpc::Error; //use crate::rpc::Error;
use anyhow::{Error, Result}; use anyhow::Result;
use crate::{bitcoin, monero}; use crate::{bitcoin, monero};
use crate::{bitcoin::bitcoin_address, monero::monero_address};
use jsonrpsee::http_server::RpcModule; use jsonrpsee::http_server::RpcModule;
use libp2p::core::Multiaddr; use libp2p::core::Multiaddr;
use serde_json::json;
use std::collections::HashMap; use std::collections::HashMap;
use std::str::FromStr; use std::str::FromStr;
use std::sync::Arc; use std::sync::Arc;
@ -24,12 +24,8 @@ pub fn register_modules(context: Arc<Context>) -> RpcModule<Arc<Context>> {
}) })
.unwrap(); .unwrap();
module module
.register_async_method("raw_get_history", |_, context| async move { .register_async_method("get_raw_history", |_, context| async move {
context get_raw_history(&context).await
.db
.raw_all()
.await
.map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))
}) })
.unwrap(); .unwrap();
module module
@ -41,22 +37,7 @@ pub fn register_modules(context: Arc<Context>) -> RpcModule<Arc<Context>> {
})?) })?)
.map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?; .map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?;
let peerId = context get_seller(swap_id, &context).await
.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
}))
}) })
.unwrap(); .unwrap();
module module
@ -68,15 +49,7 @@ pub fn register_modules(context: Arc<Context>) -> RpcModule<Arc<Context>> {
})?) })?)
.map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?; .map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?;
let start_date = context get_swap_start_date(swap_id, &context).await
.db
.get_swap_start_date(swap_id)
.await
.map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?;
Ok(json!({
"start_date": start_date,
}))
}) })
.unwrap(); .unwrap();
module module
@ -111,6 +84,7 @@ pub fn register_modules(context: Arc<Context>) -> RpcModule<Arc<Context>> {
jsonrpsee_core::Error::Custom("Does not contain address".to_string()) jsonrpsee_core::Error::Custom("Does not contain address".to_string())
})?) })?)
.map_err(|err| jsonrpsee_core::Error::Custom(err.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 withdraw_btc(withdraw_address, amount, &context).await
}) })
@ -128,6 +102,8 @@ pub fn register_modules(context: Arc<Context>) -> RpcModule<Arc<Context>> {
) )
.map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?; .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( let monero_receive_address = monero::Address::from_str(
params.get("monero_receive_address").ok_or_else(|| { params.get("monero_receive_address").ok_or_else(|| {
jsonrpsee_core::Error::Custom( jsonrpsee_core::Error::Custom(
@ -137,6 +113,8 @@ pub fn register_modules(context: Arc<Context>) -> RpcModule<Arc<Context>> {
) )
.map_err(|err| jsonrpsee_core::Error::Custom(err.to_string()))?; .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(|| { let seller = Multiaddr::from_str(params.get("seller").ok_or_else(|| {
jsonrpsee_core::Error::Custom("Does not contain seller".to_string()) jsonrpsee_core::Error::Custom("Does not contain seller".to_string())
})?) })?)
@ -188,6 +166,53 @@ async fn get_history(context: &Arc<Context>) -> Result<serde_json::Value, jsonrp
Ok(history) Ok(history)
} }
async fn get_raw_history(context: &Arc<Context>) -> Result<serde_json::Value, jsonrpsee_core::Error> {
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<Context>
) -> Result<serde_json::Value, jsonrpsee_core::Error> {
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<Context>
) -> Result<serde_json::Value, jsonrpsee_core::Error> {
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( async fn resume_swap(
swap_id: Uuid, swap_id: Uuid,