diff --git a/shell/_swap-cli b/shell/_swap-cli index 5567259b3..d4a4dc6db 100644 --- a/shell/_swap-cli +++ b/shell/_swap-cli @@ -265,7 +265,7 @@ _arguments "${_arguments_options[@]}" \ '--ctl-socket=[ZMQ socket name/address for daemon control interface]:CTL_SOCKET:_files' \ '-h[Print help information]' \ '--help[Print help information]' \ -':coin -- The coin funding required needs to be checked against:' \ +':blockchain -- The blockchain funding required needs to be checked against:' \ && ret=0 ;; (sweep-bitcoin-address) @@ -334,7 +334,7 @@ _swap-cli_commands() { 'revoke-offer:Revoke offer accepts an offer and revokes it within the runtime' \ 'abort-swap:Abort a swap if it has not locked yet' \ 'progress:Request swap progress report' \ -'needs-funding:Returns addresses and amounts that require funding for coin' \ +'needs-funding:Returns addresses and amounts that require funding for blockchain' \ 'sweep-bitcoin-address:Attempts to sweep any funds on a given bitcoin funding address' \ 'sweep-monero-address:Attempts to sweep any funds on a given monero funding address' \ 'help:Print this message or the help of the given subcommand(s)' \ diff --git a/shell/_swap-cli.ps1 b/shell/_swap-cli.ps1 index 8b8f18414..b0256ff61 100644 --- a/shell/_swap-cli.ps1 +++ b/shell/_swap-cli.ps1 @@ -46,7 +46,7 @@ Register-ArgumentCompleter -Native -CommandName 'swap-cli' -ScriptBlock { [CompletionResult]::new('revoke-offer', 'revoke-offer', [CompletionResultType]::ParameterValue, 'Revoke offer accepts an offer and revokes it within the runtime') [CompletionResult]::new('abort-swap', 'abort-swap', [CompletionResultType]::ParameterValue, 'Abort a swap if it has not locked yet') [CompletionResult]::new('progress', 'progress', [CompletionResultType]::ParameterValue, 'Request swap progress report') - [CompletionResult]::new('needs-funding', 'needs-funding', [CompletionResultType]::ParameterValue, 'Returns addresses and amounts that require funding for coin') + [CompletionResult]::new('needs-funding', 'needs-funding', [CompletionResultType]::ParameterValue, 'Returns addresses and amounts that require funding for blockchain') [CompletionResult]::new('sweep-bitcoin-address', 'sweep-bitcoin-address', [CompletionResultType]::ParameterValue, 'Attempts to sweep any funds on a given bitcoin funding address') [CompletionResult]::new('sweep-monero-address', 'sweep-monero-address', [CompletionResultType]::ParameterValue, 'Attempts to sweep any funds on a given monero funding address') [CompletionResult]::new('help', 'help', [CompletionResultType]::ParameterValue, 'Print this message or the help of the given subcommand(s)') diff --git a/shell/swap-cli.bash b/shell/swap-cli.bash index 1371c451b..5b8f8b7cf 100644 --- a/shell/swap-cli.bash +++ b/shell/swap-cli.bash @@ -568,7 +568,7 @@ _swap-cli() { return 0 ;; swap__cli__needs__funding) - opts="-h -d -T -m -x --help --data-dir --tor-proxy --msg-socket --ctl-socket " + opts="-h -d -T -m -x --help --data-dir --tor-proxy --msg-socket --ctl-socket " if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") ) return 0 diff --git a/src/cli/command.rs b/src/cli/command.rs index a3b791c35..15e13fc6d 100644 --- a/src/cli/command.rs +++ b/src/cli/command.rs @@ -27,7 +27,7 @@ use internet2::addr::{InetSocketAddr, NodeAddr}; use microservices::shell::Exec; use farcaster_core::{ - blockchain::Network, + blockchain::{Blockchain, Network}, negotiation::PublicOffer, role::{SwapRole, TradeRole}, swap::SwapId, @@ -35,10 +35,7 @@ use farcaster_core::{ use strict_encoding::ReadExt; use super::Command; -use crate::{ - rpc::{request, Client, Request}, - syncerd::Coin, -}; +use crate::rpc::{request, Client, Request}; use crate::{Error, LogStyle, ServiceId}; impl Exec for Command { @@ -253,8 +250,8 @@ impl Exec for Command { } } - Command::NeedsFunding { coin } => { - runtime.request(ServiceId::Farcasterd, Request::NeedsFunding(coin))?; + Command::NeedsFunding { blockchain } => { + runtime.request(ServiceId::Farcasterd, Request::NeedsFunding(blockchain))?; runtime.report_response_or_fail()?; } diff --git a/src/cli/opts.rs b/src/cli/opts.rs index 434c3801a..77e2f3c24 100644 --- a/src/cli/opts.rs +++ b/src/cli/opts.rs @@ -24,8 +24,6 @@ use farcaster_core::{ swap::{btcxmr::PublicOffer, SwapId}, }; -use crate::syncerd::Coin; - /// Command-line tool for working with Farcaster node #[derive(Parser, Clone, PartialEq, Eq, Debug)] #[clap(name = "swap-cli", bin_name = "swap-cli", author, version)] @@ -227,11 +225,11 @@ pub enum Command { follow: bool, }, - /// Returns addresses and amounts that require funding for coin. - #[display("needs-funding<{coin}>")] + /// Returns addresses and amounts that require funding for blockchain. + #[display("needs-funding<{blockchain}>")] NeedsFunding { - /// The coin funding required needs to be checked against. - coin: Coin, + /// The blockchain funding required needs to be checked against. + blockchain: Blockchain, }, /// Attempts to sweep any funds on a given bitcoin funding address diff --git a/src/databased/runtime.rs b/src/databased/runtime.rs index fc2484ffc..72f0c312c 100644 --- a/src/databased/runtime.rs +++ b/src/databased/runtime.rs @@ -2,8 +2,8 @@ use crate::databased::runtime::request::{ Address, OfferStatus, OfferStatusPair, OfferStatusSelector, }; use crate::farcaster_core::consensus::Encodable; -use crate::syncerd::opts::Coin; use crate::walletd::runtime::{CheckpointWallet, Wallet}; +use farcaster_core::blockchain::Blockchain; use farcaster_core::swap::btcxmr::PublicOffer; use farcaster_core::swap::SwapId; use lmdb::{Cursor, Transaction as LMDBTransaction}; @@ -302,7 +302,7 @@ impl Runtime { } } - Request::GetAddresses(Coin::Bitcoin) => { + Request::GetAddresses(Blockchain::Bitcoin) => { let addresses = self.database.get_all_bitcoin_addresses()?; endpoints.send_to( ServiceBus::Ctl, @@ -347,7 +347,7 @@ impl Runtime { } } - Request::GetAddresses(Coin::Monero) => { + Request::GetAddresses(Blockchain::Monero) => { let addresses = self.database.get_all_monero_addresses()?; endpoints.send_to( ServiceBus::Ctl, diff --git a/src/farcasterd/runtime.rs b/src/farcasterd/runtime.rs index c852c4f43..17cd58ebb 100644 --- a/src/farcasterd/runtime.rs +++ b/src/farcasterd/runtime.rs @@ -27,7 +27,6 @@ use crate::{ }, service::Endpoints, swapd::get_swap_id, - syncerd::opts::Coin, walletd::NodeSecrets, }; use amplify::Wrapper; @@ -67,7 +66,7 @@ use internet2::{ use microservices::esb::{self, Handler}; use farcaster_core::{ - blockchain::Network, + blockchain::{Blockchain, Network}, negotiation::{OfferId, PublicOfferId}, swap::SwapId, }; @@ -214,19 +213,19 @@ impl Stats { fn incr_initiated(&mut self) { self.initialized += 1; } - fn incr_awaiting_funding(&mut self, coin: &Coin) { - match coin { - Coin::Monero => self.awaiting_funding_xmr += 1, - Coin::Bitcoin => self.awaiting_funding_btc += 1, + fn incr_awaiting_funding(&mut self, blockchain: &Blockchain) { + match blockchain { + Blockchain::Monero => self.awaiting_funding_xmr += 1, + Blockchain::Bitcoin => self.awaiting_funding_btc += 1, } } - fn incr_funded(&mut self, coin: &Coin) { - match coin { - Coin::Monero => { + fn incr_funded(&mut self, blockchain: &Blockchain) { + match blockchain { + Blockchain::Monero => { self.funded_xmr += 1; self.awaiting_funding_xmr -= 1; } - Coin::Bitcoin => { + Blockchain::Bitcoin => { self.funded_btc += 1; self.awaiting_funding_btc -= 1; } @@ -379,7 +378,7 @@ impl Runtime { .drain() .filter_map( |( - (coin, network), + (blockchain, network), Syncer { mut clients, service_id, @@ -388,14 +387,14 @@ impl Runtime { clients.remove(&client_service_id); if !clients.is_empty() { Some(( - (coin, network), + (blockchain, network), Syncer { clients, service_id, }, )) } else { - let service_id = ServiceId::Syncer(coin, network); + let service_id = ServiceId::Syncer(blockchain, network); info!("Terminating {}", &service_id); if endpoints .send_to( @@ -409,7 +408,7 @@ impl Runtime { None } else { Some(( - (coin, network), + (blockchain, network), Syncer { clients, service_id: Some(service_id), @@ -419,7 +418,7 @@ impl Runtime { } }, ) - .collect::>() + .collect::>() .into(); Ok(()) } @@ -601,12 +600,12 @@ impl Runtime { ); } } - ServiceId::Syncer(coin, network) - if !self.syncers.service_online(&(*coin, *network)) + ServiceId::Syncer(blockchain, network) + if !self.syncers.service_online(&(*blockchain, *network)) && self.spawning_services.contains_key(&source) => { if let Some(Syncer { service_id, .. }) = - self.syncers.inner().get_mut(&(*coin, *network)) + self.syncers.inner().get_mut(&(*blockchain, *network)) { *service_id = Some(source.clone()); info!( @@ -619,7 +618,7 @@ impl Runtime { endpoints.send_to( ServiceBus::Ctl, source, - ServiceId::Syncer(*coin, *network), + ServiceId::Syncer(*blockchain, *network), request, )?; } @@ -675,14 +674,14 @@ impl Runtime { )); // notify this swapd about its syncers that are up and // running. if syncer not ready, then swapd will be notified - // on the ServiceId::Syncer(coin, network) Hello pattern. in + // on the ServiceId::Syncer(blockchain, network) Hello pattern. in // sum, if syncer is up, send msg immediately else wait for // syncer to say hello, and then dispatch msg let init_swap_req = Request::MakeSwap(swap_params.clone()); - if self - .syncers - .pair_ready((Coin::Bitcoin, *network), (Coin::Monero, *network)) - { + if self.syncers.pair_ready( + (Blockchain::Bitcoin, *network), + (Blockchain::Monero, *network), + ) { endpoints.send_to( ServiceBus::Ctl, self.identity(), @@ -693,8 +692,8 @@ impl Runtime { let xs = self .pending_swap_init .entry(( - ServiceId::Syncer(Coin::Bitcoin, *network), - ServiceId::Syncer(Coin::Monero, *network), + ServiceId::Syncer(Blockchain::Bitcoin, *network), + ServiceId::Syncer(Blockchain::Monero, *network), )) .or_insert(vec![]); xs.push((init_swap_req, swap_params.swap_id)); @@ -717,10 +716,10 @@ impl Runtime { ))), )); let init_swap_req = Request::TakeSwap(swap_params.clone()); - if self - .syncers - .pair_ready((Coin::Bitcoin, *network), (Coin::Monero, *network)) - { + if self.syncers.pair_ready( + (Blockchain::Bitcoin, *network), + (Blockchain::Monero, *network), + ) { endpoints.send_to( ServiceBus::Ctl, self.identity(), @@ -731,8 +730,8 @@ impl Runtime { let xs = self .pending_swap_init .entry(( - ServiceId::Syncer(Coin::Bitcoin, *network), - ServiceId::Syncer(Coin::Monero, *network), + ServiceId::Syncer(Blockchain::Bitcoin, *network), + ServiceId::Syncer(Blockchain::Monero, *network), )) .or_insert(vec![]); xs.push((init_swap_req, swap_params.swap_id)); @@ -832,7 +831,7 @@ impl Runtime { ServiceId::Farcasterd, &mut self.spawning_services, &mut self.syncers, - Coin::Bitcoin, + Blockchain::Bitcoin, network, swap_id, &self.config, @@ -841,7 +840,7 @@ impl Runtime { ServiceId::Farcasterd, &mut self.spawning_services, &mut self.syncers, - Coin::Monero, + Blockchain::Monero, network, swap_id, &self.config, @@ -1101,7 +1100,7 @@ impl Runtime { ServiceId::Farcasterd, &mut self.spawning_services, &mut self.syncers, - Coin::Bitcoin, + Blockchain::Bitcoin, public_offer.offer.network, swap_id, &self.config, @@ -1110,7 +1109,7 @@ impl Runtime { ServiceId::Farcasterd, &mut self.spawning_services, &mut self.syncers, - Coin::Monero, + Blockchain::Monero, public_offer.offer.network, swap_id, &self.config, @@ -1468,7 +1467,7 @@ impl Runtime { address, amount, }) => { - self.stats.incr_awaiting_funding(&Coin::Bitcoin); + self.stats.incr_awaiting_funding(&Blockchain::Bitcoin); let network = match address.network { bitcoin::Network::Bitcoin => Network::Mainnet, bitcoin::Network::Testnet => Network::Testnet, @@ -1546,7 +1545,7 @@ impl Runtime { address, amount, }) => { - self.stats.incr_awaiting_funding(&Coin::Monero); + self.stats.incr_awaiting_funding(&Blockchain::Monero); let network = match address.network { monero::Network::Mainnet => Network::Mainnet, monero::Network::Stagenet => Network::Testnet, @@ -1603,48 +1602,50 @@ impl Runtime { } }, - Request::FundingCompleted(coin) => { + Request::FundingCompleted(blockchain) => { let swapid = get_swap_id(&source)?; - if match coin { - Coin::Bitcoin => self.funding_btc.remove(&get_swap_id(&source)?).is_some(), - Coin::Monero => self.funding_xmr.remove(&get_swap_id(&source)?).is_some(), + if match blockchain { + Blockchain::Bitcoin => { + self.funding_btc.remove(&get_swap_id(&source)?).is_some() + } + Blockchain::Monero => self.funding_xmr.remove(&get_swap_id(&source)?).is_some(), } { - self.stats.incr_funded(&coin); + self.stats.incr_funded(&blockchain); info!( "{} | Your {} funding completed", swapid.bright_blue_italic(), - coin.bright_green_bold() + blockchain.bright_green_bold() ); } } - Request::FundingCanceled(coin) => { + Request::FundingCanceled(blockchain) => { let swapid = get_swap_id(&source)?; - match coin { - Coin::Bitcoin => { + match blockchain { + Blockchain::Bitcoin => { if self.funding_btc.remove(&get_swap_id(&source)?).is_some() { self.stats.incr_funding_bitcoin_canceled(); info!( "{} | Your {} funding was canceled", swapid.bright_blue_italic(), - coin.bright_green_bold() + blockchain.bright_green_bold() ); } } - Coin::Monero => { + Blockchain::Monero => { if self.funding_xmr.remove(&get_swap_id(&source)?).is_some() { self.stats.incr_funding_monero_canceled(); info!( "{} | Your {} funding was canceled", swapid.bright_blue_italic(), - coin.bright_green_bold() + blockchain.bright_green_bold() ); } } }; } - Request::NeedsFunding(Coin::Monero) => { + Request::NeedsFunding(Blockchain::Monero) => { let len = self.funding_xmr.len(); let res = self .funding_xmr @@ -1673,7 +1674,7 @@ impl Runtime { Request::String(res), )?; } - Request::NeedsFunding(Coin::Bitcoin) => { + Request::NeedsFunding(Blockchain::Bitcoin) => { let len = self.funding_btc.len(); let res = self .funding_btc @@ -1705,7 +1706,7 @@ impl Runtime { Request::SweepMoneroAddress(sweep_xmr_address) => { // TODO: remove once conversion is implemented in farcaster core Network type - let coin = Coin::Monero; + let blockchain = Blockchain::Monero; let network = match sweep_xmr_address.destination_address.network { monero::Network::Mainnet => Network::Mainnet, monero::Network::Stagenet => Network::Testnet, @@ -1723,18 +1724,19 @@ impl Runtime { self.syncer_task_counter += 1; self.syncer_tasks.insert(id, source.clone()); - let k = (coin, network); - let s = ServiceId::Syncer(coin, network); + let k = (blockchain, network); + let s = ServiceId::Syncer(blockchain, network); if !self.syncers.service_online(&k) && !self.spawning_services.contains_key(&s) { let mut args = vec![ - "--coin".to_string(), - coin.to_string(), + "--blockchain".to_string(), + blockchain.to_string(), "--network".to_string(), network.to_string(), ]; args.append( - &mut syncer_servers_args(&self.config, coin, network) - .or(syncer_servers_args(&self.config, coin, Network::Local))?, + &mut syncer_servers_args(&self.config, blockchain, network).or( + syncer_servers_args(&self.config, blockchain, Network::Local), + )?, ); info!("launching syncer with: {:?}", args); launch("syncerd", args)?; @@ -1755,7 +1757,7 @@ impl Runtime { endpoints.send_to( ServiceBus::Ctl, ServiceId::Farcasterd, - ServiceId::Syncer(coin, network), + ServiceId::Syncer(blockchain, network), request, )?; } @@ -1763,7 +1765,7 @@ impl Runtime { Request::SweepBitcoinAddress(sweep_bitcoin_address) => { // remove once conversion is implemented in farcaster core Network type - let coin = Coin::Bitcoin; + let blockchain = Blockchain::Bitcoin; let network = match sweep_bitcoin_address.source_address.network { bitcoin::Network::Bitcoin => Network::Mainnet, bitcoin::Network::Testnet => Network::Testnet, @@ -1782,16 +1784,16 @@ impl Runtime { self.syncer_task_counter += 1; self.syncer_tasks.insert(id, source.clone()); - let k = (coin, network); - let s = ServiceId::Syncer(coin, network); + let k = (blockchain, network); + let s = ServiceId::Syncer(blockchain, network); if !self.syncers.service_online(&k) && !self.spawning_services.contains_key(&s) { let mut args = vec![ - "--coin".to_string(), - coin.to_string(), + "--blockchain".to_string(), + blockchain.to_string(), "--network".to_string(), network.to_string(), ]; - args.append(&mut syncer_servers_args(&self.config, coin, network)?); + args.append(&mut syncer_servers_args(&self.config, blockchain, network)?); info!("launching syncer with: {:?}", args); launch("syncerd", args)?; self.spawning_services.insert(s, ServiceId::Farcasterd); @@ -1811,7 +1813,7 @@ impl Runtime { endpoints.send_to( ServiceBus::Ctl, source, - ServiceId::Syncer(coin, network), + ServiceId::Syncer(blockchain, network), request, )?; } @@ -1852,12 +1854,12 @@ impl Runtime { .syncers .inner() .drain() - .filter_map(|((coin, network), mut xs)| { + .filter_map(|((blockchain, network), mut xs)| { xs.clients.remove(&client_service_id); if !xs.clients.is_empty() { - Some(((coin, network), xs)) + Some(((blockchain, network), xs)) } else { - let service_id = ServiceId::Syncer(coin, network); + let service_id = ServiceId::Syncer(blockchain, network); info!("Terminating {}", service_id); if endpoints .send_to( @@ -1870,11 +1872,11 @@ impl Runtime { { None } else { - Some(((coin, network), xs)) + Some(((blockchain, network), xs)) } } }) - .collect::>() + .collect::>() .into(); } @@ -2072,21 +2074,21 @@ fn syncers_up( source: ServiceId, spawning_services: &mut HashMap, syncers: &mut Syncers, - coin: Coin, + blockchain: Blockchain, network: Network, swap_id: SwapId, config: &Config, ) -> Result<(), Error> { - let k = (coin, network); - let s = ServiceId::Syncer(coin, network); + let k = (blockchain, network); + let s = ServiceId::Syncer(blockchain, network); if !syncers.service_online(&k) && !spawning_services.contains_key(&s) { let mut args = vec![ - "--coin".to_string(), - coin.to_string(), + "--blockchain".to_string(), + blockchain.to_string(), "--network".to_string(), network.to_string(), ]; - args.append(&mut syncer_servers_args(config, coin, network)?); + args.append(&mut syncer_servers_args(config, blockchain, network)?); info!("launching syncer with: {:?}", args); launch("syncerd", args)?; syncers.inner().insert( @@ -2154,14 +2156,18 @@ fn launch_swapd( /// Return the list of needed arguments for a syncer given a config and a network. /// This function only register the minimal set of URLs needed for the blockchain to work. -fn syncer_servers_args(config: &Config, coin: Coin, net: Network) -> Result, Error> { +fn syncer_servers_args( + config: &Config, + blockchain: Blockchain, + net: Network, +) -> Result, Error> { match config.get_syncer_servers(net) { - Some(servers) => match coin { - Coin::Bitcoin => Ok(vec![ + Some(servers) => match blockchain { + Blockchain::Bitcoin => Ok(vec![ "--electrum-server".to_string(), servers.electrum_server, ]), - Coin::Monero => { + Blockchain::Monero => { let mut args: Vec = vec![ "--monero-daemon".to_string(), servers.monero_daemon, @@ -2246,10 +2252,10 @@ pub fn launch( }) } #[derive(Default, From)] -struct Syncers(HashMap<(Coin, Network), Syncer>); +struct Syncers(HashMap<(Blockchain, Network), Syncer>); impl Syncers { - pub fn inner(&mut self) -> &mut HashMap<(Coin, Network), Syncer> { + pub fn inner(&mut self) -> &mut HashMap<(Blockchain, Network), Syncer> { &mut self.0 } pub fn syncer_services_len(&self) -> usize { @@ -2258,13 +2264,13 @@ impl Syncers { .filter(|Syncer { service_id, .. }| service_id.is_some()) .count() } - pub fn service_online(&self, key: &(Coin, Network)) -> bool { + pub fn service_online(&self, key: &(Blockchain, Network)) -> bool { self.0 .get(key) .map(|Syncer { service_id, .. }| service_id.is_some()) .unwrap_or(false) } - pub fn pair_ready(&self, coin0: (Coin, Network), coin1: (Coin, Network)) -> bool { + pub fn pair_ready(&self, coin0: (Blockchain, Network), coin1: (Blockchain, Network)) -> bool { SyncerPair::new(&self, coin0, coin1) .map(|syncer_pair| syncer_pair.ready()) .unwrap_or(false) @@ -2288,8 +2294,8 @@ impl<'a> SyncerPair<'a> { } fn new( ss: &'a Syncers, - arbitrating_ix: (Coin, Network), - accordant_ix: (Coin, Network), + arbitrating_ix: (Blockchain, Network), + accordant_ix: (Blockchain, Network), ) -> Option { let arbitrating_syncer = ss.0.get(&arbitrating_ix)?; let accordant_syncer = ss.0.get(&accordant_ix)?; @@ -2302,9 +2308,10 @@ impl<'a> SyncerPair<'a> { fn normalize_syncer_services_pair(source: &ServiceId) -> (ServiceId, ServiceId) { match source { - ServiceId::Syncer(Coin::Monero, network) | ServiceId::Syncer(Coin::Bitcoin, network) => ( - ServiceId::Syncer(Coin::Bitcoin, *network), - ServiceId::Syncer(Coin::Monero, *network), + ServiceId::Syncer(Blockchain::Monero, network) + | ServiceId::Syncer(Blockchain::Bitcoin, network) => ( + ServiceId::Syncer(Blockchain::Bitcoin, *network), + ServiceId::Syncer(Blockchain::Monero, *network), ), _ => unreachable!("Not Bitcoin nor Monero syncers"), } diff --git a/src/rpc/request.rs b/src/rpc/request.rs index 7c4194e3f..cc5df1def 100644 --- a/src/rpc/request.rs +++ b/src/rpc/request.rs @@ -25,7 +25,7 @@ use crate::{ farcasterd, syncerd::{ types::{Event, Task}, - Coin, SweepMoneroAddress, + SweepMoneroAddress, }, }; use amplify::{Holder, ToYamlString, Wrapper}; @@ -57,7 +57,7 @@ use bitcoin::{ }; use farcaster_core::{ bitcoin::BitcoinSegwitV0, - blockchain::FeePriority, + blockchain::{Blockchain, FeePriority}, crypto::dleq::DLEQProof, monero::Monero, protocol::message::Abort, @@ -569,7 +569,7 @@ pub enum Request { #[api(type = 1109)] #[display("needs_funding({0})")] - NeedsFunding(Coin), + NeedsFunding(Blockchain), #[api(type = 1110)] #[display("write_text")] @@ -577,11 +577,11 @@ pub enum Request { #[api(type = 1111)] #[display("funding_completed({0})")] - FundingCompleted(Coin), + FundingCompleted(Blockchain), #[api(type = 1112)] #[display("funding_canceled")] - FundingCanceled(Coin), + FundingCanceled(Blockchain), // #[api(type = 1203)] // #[display("channel_funding({0})", alt = "{0:#}")] @@ -648,7 +648,7 @@ pub enum Request { #[api(type = 1312)] #[display("get_addresses")] - GetAddresses(Coin), + GetAddresses(Blockchain), #[api(type = 1313)] #[display("bitcoin_address_list({0})")] diff --git a/src/service.rs b/src/service.rs index d258939e8..8e9435c51 100644 --- a/src/service.rs +++ b/src/service.rs @@ -14,7 +14,6 @@ use crate::rpc::request::{Failure, Progress, Request}; use crate::rpc::ServiceBus; -use crate::syncerd::opts::Coin; use std::convert::TryInto; use std::fmt::{self, Display, Formatter}; use std::str::FromStr; @@ -32,7 +31,10 @@ use microservices::node::TryService; use strict_encoding::{strict_deserialize, strict_serialize}; use strict_encoding::{StrictDecode, StrictEncode}; -use farcaster_core::{blockchain::Network, swap::SwapId}; +use farcaster_core::{ + blockchain::{Blockchain, Network}, + swap::SwapId, +}; use crate::opts::Opts; use crate::Error; @@ -129,7 +131,7 @@ pub enum ServiceId { Client(u64), #[display("{0} ({1}) syncer")] - Syncer(Coin, Network), + Syncer(Blockchain, Network), #[display("walletd")] Wallet, diff --git a/src/swapd/runtime.rs b/src/swapd/runtime.rs index d32b3c6ba..6cf4ce50e 100644 --- a/src/swapd/runtime.rs +++ b/src/swapd/runtime.rs @@ -21,9 +21,8 @@ use crate::{ rpc::request::Outcome, rpc::request::{BitcoinFundingInfo, FundingInfo, MoneroFundingInfo}, syncerd::{ - opts::Coin, Abort, GetTx, HeightChanged, SweepAddress, SweepAddressAddendum, - SweepMoneroAddress, SweepSuccess, TaskId, TaskTarget, TransactionRetrieved, WatchHeight, - XmrAddressAddendum, + Abort, GetTx, HeightChanged, SweepAddress, SweepAddressAddendum, SweepMoneroAddress, + SweepSuccess, TaskId, TaskTarget, TransactionRetrieved, WatchHeight, XmrAddressAddendum, }, }; use std::{ @@ -67,7 +66,7 @@ use farcaster_core::{ fee::SatPerVByte, segwitv0::LockTx, segwitv0::SegwitV0, timelock::CSVTimelock, Bitcoin, BitcoinSegwitV0, }, - blockchain::{self, FeeStrategy}, + blockchain::{self, Blockchain, FeeStrategy}, consensus::{self, Encodable as FarEncodable}, crypto::{CommitmentEngine, SharedKeyId, TaggedElement}, monero::{Monero, SHARED_VIEW_KEY_ID}, @@ -156,8 +155,8 @@ pub fn run( lock_tx_confs: None, cancel_tx_confs: None, network, - bitcoin_syncer: ServiceId::Syncer(Coin::Bitcoin, network), - monero_syncer: ServiceId::Syncer(Coin::Monero, network), + bitcoin_syncer: ServiceId::Syncer(Blockchain::Bitcoin, network), + monero_syncer: ServiceId::Syncer(Blockchain::Monero, network), monero_amount, bitcoin_amount, awaiting_funding: false, @@ -916,7 +915,8 @@ impl Runtime { ); let acc_confs_needs = self.temporal_safety.sweep_monero_thr - self.temporal_safety.xmr_finality_thr; - let sweep_block = self.syncer_state.height(Coin::Monero) + acc_confs_needs as u64; + let sweep_block = + self.syncer_state.height(Blockchain::Monero) + acc_confs_needs as u64; info!( "{} | Tx {} needs {}, and has {} {}", self.swap_id.bright_blue_italic(), @@ -928,7 +928,7 @@ impl Runtime { info!( "{} | {} reaches your address {} around block {}", self.swap_id.bright_blue_italic(), - Coin::Monero.bright_white_bold(), + Blockchain::Monero.bright_white_bold(), destination_address.bright_yellow_bold(), sweep_block.bright_blue_bold(), ); @@ -1097,7 +1097,7 @@ impl Runtime { match &event { Event::HeightChanged(HeightChanged { height, .. }) => { self.syncer_state - .handle_height_change(*height, Coin::Monero); + .handle_height_change(*height, Blockchain::Monero); } Event::AddressTransaction(AddressTransaction { id, @@ -1149,7 +1149,7 @@ impl Runtime { ServiceBus::Ctl, self.identity(), ServiceId::Farcasterd, - Request::FundingCompleted(Coin::Monero), + Request::FundingCompleted(Blockchain::Monero), )?; self.syncer_state.awaiting_funding = false; } @@ -1261,7 +1261,9 @@ impl Runtime { Event::TransactionConfirmations(TransactionConfirmations { confirmations: Some(confirmations), .. - }) if self.temporal_safety.final_tx(*confirmations, Coin::Monero) + }) if self + .temporal_safety + .final_tx(*confirmations, Blockchain::Monero) && self.state.b_core_arb() && !self.state.cancel_seen() && self.pending_requests().contains_key(&source) @@ -1297,7 +1299,7 @@ impl Runtime { }) if self.syncer_state.tasks.watched_txs.contains_key(id) && !self .temporal_safety - .final_tx(confirmations.unwrap_or(0), Coin::Monero) => + .final_tx(confirmations.unwrap_or(0), Blockchain::Monero) => { self.syncer_state.handle_tx_confs( id, @@ -1338,7 +1340,7 @@ impl Runtime { ServiceBus::Ctl, self.identity(), ServiceId::Farcasterd, - Request::FundingCompleted(Coin::Monero), + Request::FundingCompleted(Blockchain::Monero), )?; } SwapRole::Bob => { @@ -1346,7 +1348,7 @@ impl Runtime { ServiceBus::Ctl, self.identity(), ServiceId::Farcasterd, - Request::FundingCompleted(Coin::Bitcoin), + Request::FundingCompleted(Blockchain::Bitcoin), )?; } } @@ -1403,7 +1405,7 @@ impl Runtime { match &event { Event::HeightChanged(HeightChanged { height, .. }) => { self.syncer_state - .handle_height_change(*height, Coin::Bitcoin); + .handle_height_change(*height, Blockchain::Bitcoin); } Event::AddressTransaction(AddressTransaction { id, amount, tx, .. }) if self.syncer_state.tasks.watched_addrs.get(id).is_some() => @@ -1425,7 +1427,7 @@ impl Runtime { ServiceBus::Ctl, self.identity(), ServiceId::Farcasterd, - Request::FundingCompleted(Coin::Bitcoin), + Request::FundingCompleted(Blockchain::Bitcoin), )?; // If the bitcoin amount does not match the expected funding amount, abort the swap let amount = bitcoin::Amount::from_sat(*amount); @@ -1526,7 +1528,9 @@ impl Runtime { id, confirmations: Some(confirmations), .. - }) if self.temporal_safety.final_tx(*confirmations, Coin::Bitcoin) + }) if self + .temporal_safety + .final_tx(*confirmations, Blockchain::Bitcoin) && self.syncer_state.tasks.watched_txs.get(id).is_some() => { self.syncer_state.handle_tx_confs( @@ -1686,7 +1690,7 @@ impl Runtime { ServiceBus::Ctl, self.identity(), ServiceId::Farcasterd, - Request::FundingCanceled(Coin::Monero), + Request::FundingCanceled(Blockchain::Monero), )? } @@ -1739,7 +1743,7 @@ impl Runtime { ServiceBus::Ctl, self.identity(), ServiceId::Farcasterd, - Request::FundingCanceled(Coin::Monero), + Request::FundingCanceled(Blockchain::Monero), )?; self.syncer_state.awaiting_funding = false; } @@ -1775,7 +1779,9 @@ impl Runtime { self.txs.remove(&TxLabel::Punish); } TxLabel::Buy - if self.temporal_safety.final_tx(*confirmations, Coin::Bitcoin) + if self + .temporal_safety + .final_tx(*confirmations, Blockchain::Bitcoin) && self.state.a_refundsig() => { // FIXME: swap ends here for alice @@ -1960,7 +1966,7 @@ impl Runtime { ServiceBus::Ctl, self.identity(), ServiceId::Farcasterd, - Request::FundingCanceled(Coin::Bitcoin), + Request::FundingCanceled(Blockchain::Bitcoin), )?; self.abort_swap(endpoints)?; } @@ -2378,7 +2384,7 @@ impl Runtime { self.pending_requests = PendingRequests(pending_requests); self.txs = txs.clone(); trace!("Watch height bitcoin"); - let watch_height_bitcoin = self.syncer_state.watch_height(Coin::Bitcoin); + let watch_height_bitcoin = self.syncer_state.watch_height(Blockchain::Bitcoin); endpoints.send_to( ServiceBus::Ctl, self.identity(), @@ -2387,7 +2393,7 @@ impl Runtime { )?; trace!("Watch height monero"); - let watch_height_monero = self.syncer_state.watch_height(Coin::Monero); + let watch_height_monero = self.syncer_state.watch_height(Blockchain::Monero); endpoints.send_to( ServiceBus::Ctl, self.identity(), diff --git a/src/swapd/syncer_client.rs b/src/swapd/syncer_client.rs index 1c60e6ba6..ff12f7581 100644 --- a/src/swapd/syncer_client.rs +++ b/src/swapd/syncer_client.rs @@ -2,7 +2,7 @@ use crate::{ rpc::ServiceBus, service::{Endpoints, LogStyle}, syncerd::{ - Abort, AddressAddendum, Boolean, BroadcastTransaction, BtcAddressAddendum, Coin, GetTx, + Abort, AddressAddendum, Boolean, BroadcastTransaction, BtcAddressAddendum, GetTx, SweepAddress, SweepAddressAddendum, SweepBitcoinAddress, SweepMoneroAddress, TaskTarget, TransactionBroadcasted, WatchAddress, WatchEstimateFee, WatchHeight, WatchTransaction, XmrAddressAddendum, @@ -10,7 +10,7 @@ use crate::{ Error, }; use bitcoin::{consensus::Decodable, Script, Txid}; -use farcaster_core::{swap::SwapId, transaction::TxLabel}; +use farcaster_core::{blockchain::Blockchain, swap::SwapId, transaction::TxLabel}; use std::collections::{HashMap, HashSet}; use crate::{ @@ -58,25 +58,25 @@ pub struct SyncerState { pub btc_fee_estimate_sat_per_kvb: Option, } impl SyncerState { - pub fn task_lifetime(&self, coin: Coin) -> u64 { - let height = self.height(coin); + pub fn task_lifetime(&self, blockchain: Blockchain) -> u64 { + let height = self.height(blockchain); if height > 0 { height + 500 } else { u64::MAX } } - pub fn syncer(&self, coin: Coin) -> &ServiceId { - match coin { - Coin::Bitcoin => &self.bitcoin_syncer, - Coin::Monero => &self.monero_syncer, + pub fn syncer(&self, blockchain: Blockchain) -> &ServiceId { + match blockchain { + Blockchain::Bitcoin => &self.bitcoin_syncer, + Blockchain::Monero => &self.monero_syncer, } } - pub fn is_syncer(&self, coin: Coin, source: &ServiceId) -> bool { - self.syncer(coin) == source + pub fn is_syncer(&self, blockchain: Blockchain, source: &ServiceId) -> bool { + self.syncer(blockchain) == source } pub fn any_syncer(&self, source: &ServiceId) -> bool { - self.is_syncer(Coin::Bitcoin, source) || self.is_syncer(Coin::Monero, source) + self.is_syncer(Blockchain::Bitcoin, source) || self.is_syncer(Blockchain::Monero, source) } pub fn bitcoin_syncer(&self) -> ServiceId { self.bitcoin_syncer.clone() @@ -84,19 +84,19 @@ impl SyncerState { pub fn monero_syncer(&self) -> ServiceId { self.monero_syncer.clone() } - pub fn height(&self, coin: Coin) -> u64 { - match coin { - Coin::Bitcoin => self.bitcoin_height, - Coin::Monero => self.monero_height, + pub fn height(&self, blockchain: Blockchain) -> u64 { + match blockchain { + Blockchain::Bitcoin => self.bitcoin_height, + Blockchain::Monero => self.monero_height, } } - pub fn handle_height_change(&mut self, new_height: u64, coin: Coin) { - let height = match coin { - Coin::Bitcoin => &mut self.bitcoin_height, - Coin::Monero => &mut self.monero_height, + pub fn handle_height_change(&mut self, new_height: u64, blockchain: Blockchain) { + let height = match blockchain { + Blockchain::Bitcoin => &mut self.bitcoin_height, + Blockchain::Monero => &mut self.monero_height, }; if &new_height > height { - debug!("{} new height {}", coin, &new_height); + debug!("{} new height {}", blockchain, &new_height); *height = new_height; } else { warn!("block height did not increment, maybe syncer sends multiple events"); @@ -113,7 +113,7 @@ impl SyncerState { let id = self.tasks.new_taskid(); let task = Task::WatchEstimateFee(WatchEstimateFee { id, - lifetime: self.task_lifetime(Coin::Bitcoin), + lifetime: self.task_lifetime(Blockchain::Bitcoin), }); self.tasks.tasks.insert(id, task.clone()); task @@ -131,7 +131,7 @@ impl SyncerState { ); let task = Task::WatchTransaction(WatchTransaction { id, - lifetime: self.task_lifetime(Coin::Bitcoin), + lifetime: self.task_lifetime(Blockchain::Bitcoin), hash: txid.to_vec(), confirmation_bound: self.confirmation_bound, }); @@ -153,7 +153,7 @@ impl SyncerState { debug!("Watching transaction {} with {}", hex::encode(&hash), id); let task = Task::WatchTransaction(WatchTransaction { id, - lifetime: self.task_lifetime(Coin::Monero), + lifetime: self.task_lifetime(Blockchain::Monero), hash, confirmation_bound: self.confirmation_bound, }); @@ -174,7 +174,7 @@ impl SyncerState { } pub fn watch_addr_btc(&mut self, script_pubkey: Script, tx_label: TxLabel) -> Task { let id = self.tasks.new_taskid(); - let from_height = self.from_height(Coin::Bitcoin, 6); + let from_height = self.from_height(Blockchain::Bitcoin, 6); self.tasks.watched_addrs.insert(id, tx_label); info!( "{} | Watching {} transaction with scriptPubkey: {}", @@ -189,7 +189,7 @@ impl SyncerState { }; let task = Task::WatchAddress(WatchAddress { id, - lifetime: self.task_lifetime(Coin::Bitcoin), + lifetime: self.task_lifetime(Blockchain::Bitcoin), addendum: AddressAddendum::Bitcoin(addendum), include_tx: Boolean::True, }); @@ -200,8 +200,8 @@ impl SyncerState { pub fn is_watched_addr(&self, tx_label: &TxLabel) -> bool { self.tasks.watched_addrs.values().any(|tx| tx == tx_label) } - pub fn from_height(&self, coin: Coin, delta: u64) -> u64 { - let height = self.height(coin); + pub fn from_height(&self, blockchain: Blockchain, delta: u64) -> u64 { + let height = self.height(blockchain); let delta = if height > delta { delta } else { height }; height - delta } @@ -227,7 +227,7 @@ impl SyncerState { ); let viewpair = monero::ViewPair { spend, view }; let address = monero::Address::from_viewpair(self.network.into(), &viewpair); - let from_height = from_height.unwrap_or(self.from_height(Coin::Monero, 20)); + let from_height = from_height.unwrap_or(self.from_height(Blockchain::Monero, 20)); let addendum = XmrAddressAddendum { spend_key: spend, view_key: view, @@ -248,7 +248,7 @@ impl SyncerState { let watch_addr = WatchAddress { id, - lifetime: self.task_lifetime(Coin::Monero), + lifetime: self.task_lifetime(Blockchain::Monero), addendum: AddressAddendum::Monero(addendum), include_tx: Boolean::False, }; @@ -267,7 +267,7 @@ impl SyncerState { ) -> Task { let id = self.tasks.new_taskid(); self.tasks.sweeping_addr = Some(id); - let lifetime = self.task_lifetime(Coin::Monero); + let lifetime = self.task_lifetime(Blockchain::Monero); let addendum = SweepAddressAddendum::Monero(SweepMoneroAddress { source_view_key, source_spend_key, @@ -286,12 +286,12 @@ impl SyncerState { task } - pub fn watch_height(&mut self, coin: Coin) -> Task { + pub fn watch_height(&mut self, blockchain: Blockchain) -> Task { let id = self.tasks.new_taskid(); - trace!("Watch height {}", coin); + trace!("Watch height {}", blockchain); let task = Task::WatchHeight(WatchHeight { id, - lifetime: self.task_lifetime(coin), + lifetime: self.task_lifetime(blockchain), }); self.tasks.tasks.insert(id, task.clone()); task @@ -299,7 +299,7 @@ impl SyncerState { pub fn sweep_btc(&mut self, sweep_bitcoin_address: SweepBitcoinAddress, retry: bool) -> Task { let id = self.tasks.new_taskid(); self.tasks.sweeping_addr = Some(id); - let lifetime = self.task_lifetime(Coin::Bitcoin); + let lifetime = self.task_lifetime(Blockchain::Bitcoin); let addendum = SweepAddressAddendum::Bitcoin(sweep_bitcoin_address); let sweep_task = SweepAddress { id, @@ -424,7 +424,7 @@ impl SyncerState { self.bitcoin_syncer(), Request::SyncerTask(task), )?; - let watch_height_btc_task = self.watch_height(Coin::Bitcoin); + let watch_height_btc_task = self.watch_height(Blockchain::Bitcoin); endpoints.send_to( ServiceBus::Ctl, identity.clone(), @@ -432,7 +432,7 @@ impl SyncerState { Request::SyncerTask(watch_height_btc_task), )?; // assumes xmr syncer will be up as well at this point - let watch_height_xmr_task = self.watch_height(Coin::Monero); + let watch_height_xmr_task = self.watch_height(Blockchain::Monero); endpoints.send_to( ServiceBus::Ctl, identity, diff --git a/src/swapd/temporal_safety.rs b/src/swapd/temporal_safety.rs index 251d04a21..182974be1 100644 --- a/src/swapd/temporal_safety.rs +++ b/src/swapd/temporal_safety.rs @@ -1,4 +1,5 @@ -use crate::{syncerd::Coin, Error}; +use crate::Error; +use farcaster_core::blockchain::Blockchain; use strict_encoding::{StrictDecode, StrictEncode}; pub type BlockHeight = u32; @@ -36,35 +37,35 @@ impl TemporalSafety { } } /// returns whether tx is final given the finality threshold set for the chain - pub fn final_tx(&self, confs: u32, coin: Coin) -> bool { - let finality_thr = match coin { - Coin::Bitcoin => self.btc_finality_thr, - Coin::Monero => self.xmr_finality_thr, + pub fn final_tx(&self, confs: u32, blockchain: Blockchain) -> bool { + let finality_thr = match blockchain { + Blockchain::Bitcoin => self.btc_finality_thr, + Blockchain::Monero => self.xmr_finality_thr, }; confs >= finality_thr } /// lock must be final, cancel cannot be raced, add + 1 to offset initial lock confirmation pub fn stop_funding_before_cancel(&self, lock_confirmations: u32) -> bool { - self.final_tx(lock_confirmations, Coin::Bitcoin) + self.final_tx(lock_confirmations, Blockchain::Bitcoin) && lock_confirmations > (self.cancel_timelock - self.race_thr + 1) } /// lock must be final, valid after lock_minedblock + cancel_timelock pub fn valid_cancel(&self, lock_confirmations: u32) -> bool { - self.final_tx(lock_confirmations, Coin::Bitcoin) + self.final_tx(lock_confirmations, Blockchain::Bitcoin) && lock_confirmations >= self.cancel_timelock } /// lock must be final, but buy shall not be raced with cancel pub fn safe_buy(&self, lock_confirmations: u32) -> bool { - self.final_tx(lock_confirmations, Coin::Bitcoin) + self.final_tx(lock_confirmations, Blockchain::Bitcoin) && lock_confirmations <= (self.cancel_timelock - self.race_thr) } /// cancel must be final, but refund shall not be raced with punish pub fn safe_refund(&self, cancel_confirmations: u32) -> bool { - self.final_tx(cancel_confirmations, Coin::Bitcoin) + self.final_tx(cancel_confirmations, Blockchain::Bitcoin) && cancel_confirmations <= (self.punish_timelock - self.race_thr) } pub fn valid_punish(&self, cancel_confirmations: u32) -> bool { - self.final_tx(cancel_confirmations, Coin::Bitcoin) + self.final_tx(cancel_confirmations, Blockchain::Bitcoin) && cancel_confirmations >= self.punish_timelock } } diff --git a/src/syncerd/bitcoin_syncer.rs b/src/syncerd/bitcoin_syncer.rs index 9408209dc..2ca5da300 100644 --- a/src/syncerd/bitcoin_syncer.rs +++ b/src/syncerd/bitcoin_syncer.rs @@ -4,7 +4,7 @@ use crate::internet2::Encrypt; use crate::internet2::TypedEnum; use crate::rpc::request::SyncerdBridgeEvent; use crate::rpc::Request; -use crate::syncerd::opts::{Coin, Opts}; +use crate::syncerd::opts::Opts; use crate::syncerd::runtime::SyncerdTask; use crate::syncerd::runtime::Synclet; use crate::syncerd::syncer_state::AddressTx; @@ -35,7 +35,7 @@ use electrum_client::{raw_client::RawClient, GetHistoryRes}; use electrum_client::{Client, ElectrumApi}; use farcaster_core::bitcoin::segwitv0::signature_hash; use farcaster_core::bitcoin::transaction::TxInRef; -use farcaster_core::blockchain::Network; +use farcaster_core::blockchain::{Blockchain, Network}; use farcaster_core::consensus; use internet2::zeromq::{Connection, ZmqSocketType}; use internet2::PlainTranscoder; @@ -1046,7 +1046,7 @@ impl Synclet for BitcoinSyncer { ) = tokio::sync::mpsc::channel(200); let state = Arc::new(Mutex::new(SyncerState::new( event_tx.clone(), - Coin::Bitcoin, + Blockchain::Bitcoin, ))); run_syncerd_task_receiver( diff --git a/src/syncerd/mod.rs b/src/syncerd/mod.rs index 31a4b9e4e..0b3fc4e7b 100644 --- a/src/syncerd/mod.rs +++ b/src/syncerd/mod.rs @@ -22,6 +22,6 @@ pub mod opts; pub mod runtime; #[cfg(feature = "shell")] -pub use opts::{Coin, Opts}; +pub use opts::Opts; pub use runtime::run; pub use types::*; diff --git a/src/syncerd/monero_syncer.rs b/src/syncerd/monero_syncer.rs index 796c74907..1377cbd07 100644 --- a/src/syncerd/monero_syncer.rs +++ b/src/syncerd/monero_syncer.rs @@ -1,3 +1,4 @@ +use crate::error::{Error, SyncerError}; use crate::internet2::DuplexConnection; use crate::internet2::Encrypt; use crate::internet2::TypedEnum; @@ -15,11 +16,7 @@ use crate::syncerd::Event; use crate::syncerd::TaskTarget; use crate::syncerd::TransactionBroadcasted; use crate::syncerd::XmrAddressAddendum; -use crate::{ - error::{Error, SyncerError}, - syncerd::opts::Coin, -}; -use farcaster_core::blockchain::Network; +use farcaster_core::blockchain::{Blockchain, Network}; use internet2::zeromq::{Connection, ZmqSocketType}; use internet2::PlainTranscoder; use monero::Hash; @@ -811,8 +808,10 @@ impl Synclet for MoneroSyncer { TokioSender, TokioReceiver, ) = tokio::sync::mpsc::channel(120); - let state = - Arc::new(Mutex::new(SyncerState::new(event_tx.clone(), Coin::Monero))); + let state = Arc::new(Mutex::new(SyncerState::new( + event_tx.clone(), + Blockchain::Monero, + ))); run_syncerd_task_receiver( receive_task_channel, diff --git a/src/syncerd/opts.rs b/src/syncerd/opts.rs index 676dcd3d9..ab9b6d460 100644 --- a/src/syncerd/opts.rs +++ b/src/syncerd/opts.rs @@ -12,9 +12,8 @@ // along with this software. // If not, see . -use farcaster_core::blockchain::Network; +use farcaster_core::blockchain::{Blockchain, Network}; use std::str::FromStr; -use strict_encoding::{StrictDecode, StrictEncode}; /// Syncer blockchain management daemon; part of Farcaster Node /// @@ -28,9 +27,9 @@ pub struct Opts { #[clap(flatten)] pub shared: crate::opts::Opts, - /// Which coin this syncer should target - #[clap(long, parse(try_from_str = Coin::from_str))] - pub coin: Coin, + /// Which blockchain this syncer should target + #[clap(long, parse(try_from_str = Blockchain::from_str))] + pub blockchain: Blockchain, /// Blockchain networks to use (Mainnet, Testnet, Local) #[clap( @@ -64,32 +63,6 @@ pub struct Opts { pub monero_wallet_dir_path: Option, } -#[derive(Parser, Display, Copy, Clone, Hash, PartialEq, Eq, Debug, StrictEncode, StrictDecode)] -#[display(Debug)] -pub enum Coin { - /// Launches a bitcoin syncer - Bitcoin, - /// Launches a monero syncer - Monero, -} - -#[derive(Error, Debug, Display)] -#[display("invalid coin")] -pub enum SyncerCoinError { - InvalidCoin, -} - -impl FromStr for Coin { - type Err = SyncerCoinError; - fn from_str(input: &str) -> Result { - match input { - "Bitcoin" | "bitcoin" => Ok(Coin::Bitcoin), - "Monero" | "monero" => Ok(Coin::Monero), - _ => Err(SyncerCoinError::InvalidCoin), - } - } -} - impl Opts { pub fn process(&mut self) { self.shared.process(); diff --git a/src/syncerd/runtime.rs b/src/syncerd/runtime.rs index b6fa4c423..765981fce 100644 --- a/src/syncerd/runtime.rs +++ b/src/syncerd/runtime.rs @@ -15,10 +15,10 @@ use crate::service::Endpoints; use crate::syncerd::bitcoin_syncer::BitcoinSyncer; use crate::syncerd::monero_syncer::MoneroSyncer; -use crate::syncerd::opts::{Coin, Opts}; +use crate::syncerd::opts::Opts; use crate::syncerd::runtime::request::Progress; use amplify::Wrapper; -use farcaster_core::blockchain::Network; +use farcaster_core::blockchain::{Blockchain, Network}; use std::collections::{HashMap, HashSet}; use std::convert::TryFrom; use std::ffi::OsStr; @@ -60,10 +60,10 @@ pub struct SyncerdTask { } pub fn run(config: ServiceConfig, opts: Opts) -> Result<(), Error> { - let coin = opts.coin; + let blockchain = opts.blockchain; let network = opts.network; - info!("Creating new {} ({}) syncer", &coin, &network); + info!("Creating new {} ({}) syncer", &blockchain, &network); let (tx, rx): (Sender, Receiver) = std::sync::mpsc::channel(); let tx_event = ZMQ_CONTEXT.socket(zmq::PAIR)?; @@ -71,13 +71,13 @@ pub fn run(config: ServiceConfig, opts: Opts) -> Result<(), Error> { rx_event.bind("inproc://syncerdbridge")?; tx_event.connect("inproc://syncerdbridge")?; - let syncer: Box = match coin { - Coin::Monero => Box::new(MoneroSyncer::new()), - Coin::Bitcoin => Box::new(BitcoinSyncer::new()), + let syncer: Box = match blockchain { + Blockchain::Monero => Box::new(MoneroSyncer::new()), + Blockchain::Bitcoin => Box::new(BitcoinSyncer::new()), }; let mut runtime = Runtime { - identity: ServiceId::Syncer(coin, network), + identity: ServiceId::Syncer(blockchain, network), started: SystemTime::now(), tasks: none!(), syncer, diff --git a/src/syncerd/syncer_state.rs b/src/syncerd/syncer_state.rs index f0b5fb0f3..43a891478 100644 --- a/src/syncerd/syncer_state.rs +++ b/src/syncerd/syncer_state.rs @@ -1,6 +1,8 @@ -use crate::farcaster_core::{blockchain::Network, consensus::Decodable}; +use crate::farcaster_core::{ + blockchain::{Blockchain, Network}, + consensus::Decodable, +}; use crate::rpc::request::SyncerdBridgeEvent; -use crate::syncerd::opts::Coin; use crate::syncerd::runtime::SyncerdTask; use crate::syncerd::{TaskId, TaskTarget}; use crate::Error; @@ -38,7 +40,7 @@ impl TaskCounter { } pub struct SyncerState { - coin: Coin, + blockchain: Blockchain, block_height: u64, block_hash: Vec, tasks_sources: HashMap, @@ -79,7 +81,7 @@ pub fn create_set(xs: Vec) -> HashSet { } impl SyncerState { - pub fn new(tx_event: TokioSender, id: Coin) -> Self { + pub fn new(tx_event: TokioSender, blockchain: Blockchain) -> Self { Self { block_height: 0, block_hash: vec![0], @@ -93,7 +95,7 @@ impl SyncerState { sweep_addresses: HashMap::new(), tx_event, task_count: TaskCounter(0), - coin: id, + blockchain, subscribed_addresses: HashSet::new(), fee_estimation: None, } @@ -403,20 +405,20 @@ impl SyncerState { self.block_hash = block; info!( "{} incremented height {}", - self.coin.bright_white_bold(), + self.blockchain.bright_white_bold(), &h.bright_blue_bold() ); } (h, b) if h == self.block_height && b != &self.block_hash => { self.block_hash = block; - info!("{} new chain tip", self.coin.bright_white_bold()); + info!("{} new chain tip", self.blockchain.bright_white_bold()); } (h, b) if h < self.block_height && b != &self.block_hash => { self.block_height = h; self.block_hash = block; warn!( "{} height decreased {}, new chain tip", - self.coin.bright_white_bold(), + self.blockchain.bright_white_bold(), &h.bright_blue_bold() ); } @@ -787,7 +789,7 @@ async fn syncer_state_transaction() { TokioSender, TokioReceiver, ) = tokio::sync::mpsc::channel(120); - let mut state = SyncerState::new(event_tx.clone(), Coin::Bitcoin); + let mut state = SyncerState::new(event_tx.clone(), Blockchain::Bitcoin); let transaction_task_one = WatchTransaction { id: TaskId(0), @@ -805,7 +807,7 @@ async fn syncer_state_transaction() { id: TaskId(0), lifetime: 4, }; - let source1 = ServiceId::Syncer(Coin::Bitcoin, Network::Mainnet); + let source1 = ServiceId::Syncer(Blockchain::Bitcoin, Network::Mainnet); state.watch_transaction(transaction_task_one.clone(), source1.clone()); state @@ -876,7 +878,7 @@ async fn syncer_state_transaction() { assert_eq!(state.unseen_transactions.len(), 2); assert!(event_rx.try_recv().is_ok()); - let source2 = ServiceId::Syncer(Coin::Monero, Network::Mainnet); + let source2 = ServiceId::Syncer(Blockchain::Monero, Network::Mainnet); state.watch_transaction(transaction_task_two.clone(), source2.clone()); state .abort(TaskTarget::TaskId(TaskId(0)), source2.clone(), true) @@ -903,7 +905,7 @@ async fn syncer_state_addresses() { TokioSender, TokioReceiver, ) = tokio::sync::mpsc::channel(120); - let mut state = SyncerState::new(event_tx.clone(), Coin::Bitcoin); + let mut state = SyncerState::new(event_tx.clone(), Blockchain::Bitcoin); let address = bitcoin::Address::from_str("32BkaQeAVcd65Vn7pjEziohf5bCiryNQov").unwrap(); let addendum = AddressAddendum::Bitcoin(BtcAddressAddendum { address: Some(address.clone()), @@ -922,7 +924,7 @@ async fn syncer_state_addresses() { addendum: addendum.clone(), include_tx: Boolean::False, }; - let source1 = ServiceId::Syncer(Coin::Bitcoin, Network::Mainnet); + let source1 = ServiceId::Syncer(Blockchain::Bitcoin, Network::Mainnet); state.watch_address(address_task_two.clone(), source1.clone()); state @@ -1019,7 +1021,7 @@ async fn syncer_state_addresses() { assert!(event_rx.try_recv().is_ok()); assert!(event_rx.try_recv().is_ok()); - let source2 = ServiceId::Syncer(Coin::Monero, Network::Testnet); + let source2 = ServiceId::Syncer(Blockchain::Monero, Network::Testnet); state.watch_address(address_task_two.clone(), source2.clone()); state .abort(TaskTarget::TaskId(TaskId(0)), source2.clone(), true) @@ -1060,7 +1062,7 @@ async fn syncer_state_sweep_addresses() { TokioSender, TokioReceiver, ) = tokio::sync::mpsc::channel(120); - let mut state = SyncerState::new(event_tx.clone(), Coin::Monero); + let mut state = SyncerState::new(event_tx.clone(), Blockchain::Monero); let sweep_task = SweepAddress { id: TaskId(0), lifetime: 11, @@ -1082,7 +1084,7 @@ async fn syncer_state_sweep_addresses() { minimum_balance: monero::Amount::from_pico(1), }), }; - let source1 = ServiceId::Syncer(Coin::Monero, Network::Mainnet); + let source1 = ServiceId::Syncer(Blockchain::Monero, Network::Mainnet); state.sweep_address(sweep_task.clone(), source1.clone()); assert_eq!(state.lifetimes.len(), 1); @@ -1114,7 +1116,7 @@ async fn syncer_state_height() { TokioSender, TokioReceiver, ) = tokio::sync::mpsc::channel(120); - let mut state = SyncerState::new(event_tx.clone(), Coin::Bitcoin); + let mut state = SyncerState::new(event_tx.clone(), Blockchain::Bitcoin); let height_task = WatchHeight { id: TaskId(0), lifetime: 0, @@ -1123,7 +1125,7 @@ async fn syncer_state_height() { id: TaskId(0), lifetime: 3, }; - let source1 = ServiceId::Syncer(Coin::Bitcoin, Network::Mainnet); + let source1 = ServiceId::Syncer(Blockchain::Bitcoin, Network::Mainnet); state .watch_height(height_task.clone(), source1.clone()) @@ -1165,7 +1167,7 @@ async fn syncer_state_height() { assert_eq!(state.watch_height.len(), 1); assert!(event_rx.try_recv().is_err()); - let source2 = ServiceId::Syncer(Coin::Monero, Network::Mainnet); + let source2 = ServiceId::Syncer(Blockchain::Monero, Network::Mainnet); state .watch_height(another_height_task.clone(), source2.clone()) .await; diff --git a/tests/bitcoin.rs b/tests/bitcoin.rs index 47958e176..723b703ff 100644 --- a/tests/bitcoin.rs +++ b/tests/bitcoin.rs @@ -2,9 +2,9 @@ use amplify::map; use bitcoin::hashes::Hash; use bitcoincore_rpc::{Client, RpcApi}; use clap::Parser; -use farcaster_core::blockchain::Network; +use farcaster_core::blockchain::{Blockchain, Network}; use farcaster_node::syncerd::bitcoin_syncer::BitcoinSyncer; -use farcaster_node::syncerd::opts::{Coin, Opts}; +use farcaster_node::syncerd::opts::Opts; use farcaster_node::syncerd::runtime::SyncerdTask; use farcaster_node::syncerd::types::{ Abort, AddressAddendum, Boolean, BroadcastTransaction, BtcAddressAddendum, GetTx, SweepAddress, @@ -29,7 +29,7 @@ extern crate log; mod utils; -const SOURCE1: ServiceId = ServiceId::Syncer(Coin::Bitcoin, Network::Local); +const SOURCE1: ServiceId = ServiceId::Syncer(Blockchain::Bitcoin, Network::Local); /* These tests need to run serially, otherwise we cannot verify events based on the @@ -1032,7 +1032,7 @@ fn create_bitcoin_syncer( let conf = config::TestConfig::parse(); let opts = Opts::parse_from(vec!["syncerd"].into_iter().chain(vec![ - "--coin", + "--blockchain", "Bitcoin", "--electrum-server", &format!("{}", conf.electrs), diff --git a/tests/monero.rs b/tests/monero.rs index 35e36ef19..fd54c8f6c 100644 --- a/tests/monero.rs +++ b/tests/monero.rs @@ -1,7 +1,7 @@ use clap::Parser; -use farcaster_core::blockchain::Network; +use farcaster_core::blockchain::{Blockchain, Network}; use farcaster_node::syncerd::monero_syncer::MoneroSyncer; -use farcaster_node::syncerd::opts::{Coin, Opts}; +use farcaster_node::syncerd::opts::Opts; use farcaster_node::syncerd::runtime::SyncerdTask; use farcaster_node::syncerd::types::{ Abort, AddressAddendum, Boolean, BroadcastTransaction, Task, WatchAddress, WatchHeight, @@ -30,8 +30,8 @@ extern crate log; mod utils; -const SOURCE1: ServiceId = ServiceId::Syncer(Coin::Bitcoin, Network::Local); -const SOURCE2: ServiceId = ServiceId::Syncer(Coin::Monero, Network::Local); +const SOURCE1: ServiceId = ServiceId::Syncer(Blockchain::Bitcoin, Network::Local); +const SOURCE2: ServiceId = ServiceId::Syncer(Blockchain::Monero, Network::Local); /* We test for the following scenarios in the block height tests: @@ -799,7 +799,7 @@ fn create_monero_syncer( vec!["syncerd"] .into_iter() .chain(vec![ - "--coin", + "--blockchain", "Monero", "--monero-daemon", &format!("{}", conf.monero.daemon),