From 87e5dd8b53fe70ca52f22428cb8dc6ac531a8c70 Mon Sep 17 00:00:00 2001 From: Lorenzo Tucci Date: Sat, 12 Nov 2022 20:08:31 +0100 Subject: [PATCH] saving to wip --- Cargo.lock | 1 + swap/Cargo.toml | 1 + swap/src/api.rs | 63 ++++++++++++++++++++++++++++++++- swap/src/bin/swap.rs | 41 ++++++++------------- swap/src/cli/command.rs | 2 +- swap/src/{rpc/mod.rs => rpc.rs} | 21 +++++++---- swap/src/rpc/methods.rs | 42 ++++++++++++++++++++++ 7 files changed, 136 insertions(+), 35 deletions(-) rename swap/src/{rpc/mod.rs => rpc.rs} (54%) create mode 100644 swap/src/rpc/methods.rs diff --git a/Cargo.lock b/Cargo.lock index 506f812c..33235e01 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4146,6 +4146,7 @@ dependencies = [ "hyper", "itertools", "jsonrpsee", + "jsonrpsee-core", "libp2p", "monero", "monero-harness", diff --git a/swap/Cargo.toml b/swap/Cargo.toml index a91425ca..fe3cc9aa 100644 --- a/swap/Cargo.toml +++ b/swap/Cargo.toml @@ -32,6 +32,7 @@ futures = { version = "0.3", default-features = false } hex = "0.4" itertools = "0.10" jsonrpsee = { version = "0.15.1", features = [ "server"] } +jsonrpsee-core = "0.15.1" libp2p = { version = "0.42.2", default-features = false, features = [ "tcp-tokio", "yamux", "mplex", "dns-tokio", "noise", "request-response", "websocket", "ping", "rendezvous", "identify" ] } monero = { version = "0.12", features = [ "serde_support" ] } monero-rpc = { path = "../monero-rpc" } diff --git a/swap/src/api.rs b/swap/src/api.rs index 090c8831..3bc79907 100644 --- a/swap/src/api.rs +++ b/swap/src/api.rs @@ -56,7 +56,68 @@ pub struct Params { } impl InternalApi { - pub async fn call() -> Result<()> { + pub async fn call(self) -> Result<()> { + let opts = &self.opts; + let params = self.params; + match self.cmd { + Command::BuyXmr => { } + Command::History => { + cli::tracing::init(opts.debug, opts.json, opts.data_dir.join("logs"), None)?; + + let db = open_db(opts.data_dir.join("sqlite")).await?; + let swaps = db.all().await?; + + if opts.json { + for (swap_id, state) in swaps { + let state: BobState = state.try_into()?; + tracing::info!(swap_id=%swap_id.to_string(), state=%state.to_string(), "Read swap state from database"); + } + } else { + let mut table = Table::new(); + + table.set_header(vec!["SWAP ID", "STATE"]); + + for (swap_id, state) in swaps { + let state: BobState = state.try_into()?; + table.add_row(vec![swap_id.to_string(), state.to_string()]); + } + + println!("{}", table); + } + } + Command::Config => { } + Command::WithdrawBtc => { } + Command::StartDaemon => { + let handle = rpc::run_server(params.server_address.unwrap()).await?; + loop {} + } + Command::Balance => { + cli::tracing::init(opts.debug, opts.json, opts.data_dir.join("logs"), None)?; + + let seed = Seed::from_file_or_generate(opts.data_dir.as_path()) + .context("Failed to read in seed file")?; + let bitcoin_wallet = init_bitcoin_wallet( + params.bitcoin_electrum_rpc_url.unwrap(), + &seed, + opts.data_dir.clone(), + opts.env_config, + params.bitcoin_target_block.unwrap(), + ) + .await?; + + let bitcoin_balance = bitcoin_wallet.balance().await?; + tracing::info!( + balance = %bitcoin_balance, + "Checked Bitcoin balance", + ); + } + Command::Resume => { } + Command::Cancel => { } + Command::Refund => { } + Command::ListSellers => { } + Command::ExportBitcoinWallet => { } + Command::MoneroRecovery => { } + } Ok(()) } } diff --git a/swap/src/bin/swap.rs b/swap/src/bin/swap.rs index 1a3f6541..49cda947 100644 --- a/swap/src/bin/swap.rs +++ b/swap/src/bin/swap.rs @@ -12,38 +12,25 @@ #![forbid(unsafe_code)] #![allow(non_snake_case)] -use anyhow::{bail, Context, Result}; -use comfy_table::Table; -use jsonrpsee::http_server::{HttpServerHandle}; -use qrcode::render::unicode; -use qrcode::QrCode; -use std::cmp::min; -use std::convert::TryInto; +use anyhow::Result; use std::env; -use std::future::Future; -use std::path::PathBuf; -use std::sync::Arc; -use std::time::Duration; -use std::net::SocketAddr; -use swap::bitcoin::TxLock; -use swap::cli::command::{parse_args_and_apply_defaults, Options, Command, ParseResult}; -use swap::cli::{list_sellers, EventLoop, SellerStatus}; +use swap::cli::command::{parse_args_and_apply_defaults, ParseResult}; use swap::common::check_latest_version; -use swap::database::open_db; -use swap::env::Config; -use swap::libp2p_ext::MultiAddrExt; -use swap::network::quote::{BidQuote, ZeroQuoteReceived}; -use swap::network::swarm; -use swap::protocol::bob; -use swap::protocol::bob::{BobState, Swap}; -use swap::seed::Seed; -use swap::rpc; -use swap::{bitcoin, cli, monero}; -use url::Url; -use uuid::Uuid; #[tokio::main] async fn main() -> Result<()> { + let api = match parse_args_and_apply_defaults(env::args_os())? { + ParseResult::InternalApi(api) => *api, + ParseResult::PrintAndExitZero { message } => { + println!("{}", message); + std::process::exit(0); + } + }; + + if let Err(e) = check_latest_version(env!("CARGO_PKG_VERSION")).await { + eprintln!("{}", e); + } + api.call().await?; Ok(()) } diff --git a/swap/src/cli/command.rs b/swap/src/cli/command.rs index d4e129fb..1fdaef12 100644 --- a/swap/src/cli/command.rs +++ b/swap/src/cli/command.rs @@ -26,7 +26,7 @@ const DEFAULT_ELECTRUM_RPC_URL: &str = "ssl://blockstream.info:700"; pub const DEFAULT_ELECTRUM_RPC_URL_TESTNET: &str = "ssl://electrum.blockstream.info:60002"; const DEFAULT_BITCOIN_CONFIRMATION_TARGET: usize = 3; -const DEFAULT_BITCOIN_CONFIRMATION_TARGET_TESTNET: usize = 1; +pub const DEFAULT_BITCOIN_CONFIRMATION_TARGET_TESTNET: usize = 1; const DEFAULT_TOR_SOCKS5_PORT: &str = "9050"; diff --git a/swap/src/rpc/mod.rs b/swap/src/rpc.rs similarity index 54% rename from swap/src/rpc/mod.rs rename to swap/src/rpc.rs index d83827ff..599450e4 100644 --- a/swap/src/rpc/mod.rs +++ b/swap/src/rpc.rs @@ -1,16 +1,25 @@ use std::net::SocketAddr; use jsonrpsee::http_server::{RpcModule, HttpServerBuilder, HttpServerHandle}; +use thiserror::Error; + +pub mod methods; + +#[derive(Debug, Error)] +pub enum Error { + #[error("example")] + ExampleError, +} pub async fn run_server(server_address: SocketAddr) -> anyhow::Result<(SocketAddr, HttpServerHandle)> { let server = HttpServerBuilder::default().build(server_address).await?; - let mut module = RpcModule::new(()); - module.register_async_method("balance", |_, _| get_balance())?; + let mut modules = RpcModule::new(()); + { + modules.merge(methods::register_modules()) + .unwrap() + } let addr = server.local_addr()?; - let server_handle = server.start(module)?; + let server_handle = server.start(modules)?; Ok((addr, server_handle)) } -async fn get_balance() -> Result<&'static str, jsonrpsee::core::Error> { - Ok("hey") -} diff --git a/swap/src/rpc/methods.rs b/swap/src/rpc/methods.rs new file mode 100644 index 00000000..a9267d5f --- /dev/null +++ b/swap/src/rpc/methods.rs @@ -0,0 +1,42 @@ +use jsonrpsee::http_server::{RpcModule}; +use crate::api::{InternalApi, Params}; +use crate::env::{Config, GetConfig, Testnet}; +use crate::fs::system_data_dir; +use url::Url; +use crate::cli::command::{Command, Options}; +use std::str::FromStr; +use crate::cli::command::{DEFAULT_ELECTRUM_RPC_URL_TESTNET, DEFAULT_BITCOIN_CONFIRMATION_TARGET_TESTNET}; +use crate::rpc::Error; + + +pub fn register_modules() -> RpcModule<()> { + let mut module = RpcModule::new(()); + module + .register_async_method("get_bitcoin_balance", |_, _| async { + get_bitcoin_balance().await.map_err(|err| jsonrpsee_core::Error::Custom(err.to_string())) + }) + .unwrap(); + module + +} + +async fn get_bitcoin_balance() -> anyhow::Result<(), Error> { + let api = InternalApi { + opts: Options { + env_config: Testnet::get_config(), + debug: false, + json: true, + data_dir: system_data_dir().unwrap().join("cli") + + }, + params: Params { + bitcoin_electrum_rpc_url: Some(Url::from_str(DEFAULT_ELECTRUM_RPC_URL_TESTNET).unwrap()), + bitcoin_target_block: Some(DEFAULT_BITCOIN_CONFIRMATION_TARGET_TESTNET), + ..Default::default() + }, + cmd: Command::Balance, + }; + api.call().await; + Ok(()) + +}