Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only subscribe on connect/reconnect, remove refresh interval #69

Merged
merged 2 commits into from
Mar 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions controller/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,6 @@ where
/// Arguments for listen command
pub struct ListenArgs {
pub method: String,
pub interval: Option<u64>,
}

pub fn listen<L, C, K>(
Expand Down Expand Up @@ -165,7 +164,6 @@ where
wallet.clone(),
keychain_mask.clone(),
epicbox_config.clone(),
args.interval,
);
warn!("try to reconnect to epicbox");
match listener {
Expand Down Expand Up @@ -196,7 +194,6 @@ where
};

debug!("{}", args.method.clone());
debug!("{}", args.interval.unwrap_or(10));

if let Err(e) = res {
return Err(ErrorKind::LibWallet(e.kind(), e.cause_string()).into());
Expand Down
110 changes: 42 additions & 68 deletions impls/src/adapters/epicbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ use std::thread::JoinHandle;

use crate::libwallet::api_impl::foreign;
use crate::libwallet::api_impl::owner;
use epic_wallet_util::epic_core::core::amount_to_hr_string;
use std::net::TcpStream;
use std::string::ToString;
use std::sync::mpsc::{channel, Receiver, Sender};
Expand All @@ -68,8 +69,7 @@ use tungstenite::{Error as ErrorTungstenite, Message};
const CONNECTION_ERR_MSG: &str = "\nCan't connect to the epicbox server!\n\
Check your epic-wallet.toml settings and make sure epicbox domain is correct.\n";
const DEFAULT_INTERVAL: u64 = 10;
const MIN_INTERVAL: u64 = 2;
const MAX_INTERVAL: u64 = 120;
const DEFAULT_CHALLENGE_RAW: &str = "7WUDtkSaKyGRUnQ22rE3QUXChV8DmA6NnunDYP4vheTpc";

/// Epicbox 'plugin' implementation
pub enum CloseReason {
Expand Down Expand Up @@ -117,14 +117,13 @@ impl EpicboxListenChannel {
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
keychain_mask: Arc<Mutex<Option<SecretKey>>>,
epicbox_config: EpicboxConfig,
interval_arg: Option<u64>,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
let (address, sec_key, interval) = {
let (address, sec_key) = {
let a_keychain = keychain_mask.clone();
let a_wallet = wallet.clone();
let mask = a_keychain.lock();
Expand All @@ -144,12 +143,7 @@ impl EpicboxListenChannel {
epicbox_config.epicbox_port,
);

let mut interval = interval_arg;
if interval.is_none() {
interval = epicbox_config.epicbox_listener_interval
}

(address, sec_key, interval)
(address, sec_key)
};
let url = {
let cloned_address = address.clone();
Expand Down Expand Up @@ -187,7 +181,7 @@ impl EpicboxListenChannel {

warn!("Starting epicbox listener for: {}", address);

subscriber.start(controller, interval)
subscriber.start(controller)
}
}
impl EpicboxChannel {
Expand Down Expand Up @@ -261,7 +255,7 @@ where
C: NodeClient + 'static,
K: Keychain + 'static,
{
let (address, sec_key, interval) = {
let (address, sec_key) = {
let a_wallet = wallet.clone();
let mut w_lock = a_wallet.lock();
let lc = w_lock.lc_provider()?;
Expand All @@ -273,14 +267,12 @@ where
.unwrap();
let pub_key = PublicKey::from_secret_key(k.secp(), &sec_key).unwrap();

let interval: Option<u64> = config.epicbox_listener_interval;

let address = EpicboxAddress::new(
pub_key.clone(),
Some(config.epicbox_domain.clone()),
config.epicbox_port,
);
(address, sec_key, interval)
(address, sec_key)
};
let url = {
let cloned_address = address.clone();
Expand Down Expand Up @@ -311,7 +303,7 @@ where
.expect("Could not init epicbox controller!");

csubscriber
.start(controller, interval)
.start(controller)
.expect("Could not start epicbox controller!");
()
});
Expand Down Expand Up @@ -519,21 +511,21 @@ where
let version = slate.version();
let mut slate: Slate = slate.clone().into();

/*if slate.num_participants > slate.participant_data.len() {
println!(
if slate.num_participants > slate.participant_data.len() {
debug!(
"Slate [{}] received from [{}] for [{}] epics",
slate.id.to_string(),
display_from,
from.to_string(),
amount_to_hr_string(slate.amount, false)
);
} else {
println!(
debug!(
"Slate [{}] received back from [{}] for [{}] epics",
slate.id.to_string(),
display_from,
from.to_string(),
amount_to_hr_string(slate.amount, false)
);
};*/
};

if from.address_type() == AddressType::Epicbox {
EpicboxAddress::from_str(&from.to_string()).expect("invalid epicbox address");
Expand All @@ -549,26 +541,26 @@ where
self.publisher
.post_slate(&slate, from, false)
.map_err(|e| {
println!("{}: {}", "ERROR", e);
error!("{}: {}", "ERROR", e);
e
})
.expect("failed posting slate!");
} else {
println!("Slate [{}] finalized successfully", slate.id.to_string());
debug!("Slate [{}] finalized successfully", slate.id.to_string());
}
Ok(())
});

match result {
Ok(()) => {}
Err(e) => println!("{}", e),
Err(e) => error!("{}", e),
}
}

fn on_close(&self, reason: CloseReason) {
match reason {
CloseReason::Normal => {
//println!("Listener for {} stopped", self.name)
debug!("Listener for stopped, normal exit")
}
CloseReason::Abnormal(error) => {
error!("{:?}", error.to_string())
Expand All @@ -577,11 +569,7 @@ where
}
}
pub trait Subscriber {
fn start<P, L, C, K>(
&mut self,
handler: EpicboxController<P, L, C, K>,
interval: Option<u64>,
) -> Result<(), Error>
fn start<P, L, C, K>(&mut self, handler: EpicboxController<P, L, C, K>) -> Result<(), Error>
where
P: Publisher,
L: WalletLCProvider<'static, C, K> + 'static,
Expand All @@ -590,19 +578,15 @@ pub trait Subscriber {
fn stop(&self);
}
impl Subscriber for EpicboxSubscriber {
fn start<P, L, C, K>(
&mut self,
handler: EpicboxController<P, L, C, K>,
interval: Option<u64>,
) -> Result<(), Error>
fn start<P, L, C, K>(&mut self, handler: EpicboxController<P, L, C, K>) -> Result<(), Error>
where
P: Publisher,
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
self.broker
.subscribe(&self.address, &self.secret_key, handler, interval)
.subscribe(&self.address, &self.secret_key, handler)
}

fn stop(&self) {
Expand Down Expand Up @@ -643,7 +627,6 @@ impl EpicboxBroker {
address: &EpicboxAddress,
secret_key: &SecretKey,
handler: EpicboxController<P, L, C, K>,
interval: Option<u64>,
) -> Result<(), Error>
where
P: Publisher,
Expand All @@ -655,15 +638,8 @@ impl EpicboxBroker {
let sender = self.inner.clone();
let mut first_run = true;

// Parse from epicbox config or use default value for the
// time interval between new subscribe calls from the wallet
let mut seconds = interval.unwrap_or(DEFAULT_INTERVAL);
if seconds < MIN_INTERVAL {
seconds = MIN_INTERVAL
} else if seconds > MAX_INTERVAL {
seconds = MAX_INTERVAL
}
let duration = std::time::Duration::from_secs(seconds);
// time interval for sleep in main loop
let duration = std::time::Duration::from_secs(DEFAULT_INTERVAL);

let mut client = EpicboxClient {
sender,
Expand All @@ -674,6 +650,17 @@ impl EpicboxBroker {
tx: self.tx.clone(),
};

let subscribe = DEFAULT_CHALLENGE_RAW;
let signature = sign_challenge(&subscribe, &secret_key)?.to_hex();

let request = ProtocolRequest::Subscribe {
address: client.address.public_key.to_string(),
signature,
};
client
.send(&request)
.expect("Could not send Subscribe request!");

let res = loop {
let err = client.sender.lock().read_message();
let mut new_challenge = false;
Expand Down Expand Up @@ -706,16 +693,17 @@ impl EpicboxBroker {
ProtocolResponse::Challenge { str } => {
client.challenge = Some(str.clone());
client
.challenge_subscribe(&str)
.challenge_send()
.map_err(|_| {
error!("Error attempting to subscribe!");
error!("Error attempting to send Challenge!");
})
.unwrap();

if !first_run {
std::thread::sleep(duration);
} else {
new_challenge = true;
}
new_challenge = true;
}
ProtocolResponse::Slate {
from,
Expand Down Expand Up @@ -773,7 +761,6 @@ impl EpicboxBroker {
.map_err(|_| error!("error attempting challenge!"))
.unwrap();

debug!("Refresh epicbox subscription (interval: {:?})", duration);
if first_run {
std::thread::sleep(duration);
first_run = false;
Expand Down Expand Up @@ -847,31 +834,18 @@ where
C: NodeClient + 'static,
K: Keychain + 'static,
{
fn challenge_subscribe(&self, challenge: &str) -> Result<(), Error> {
let signature = sign_challenge(&challenge, &self.secret_key)?.to_hex();
let request = ProtocolRequest::Subscribe {
address: self.address.public_key.to_string(),
signature,
};

fn challenge_send(&self) -> Result<(), Error> {
let request = ProtocolRequest::Challenge;
self.send(&request)
.expect("could not send subscribe request!");
.expect("could not send Challenge request!");
self.tx.send(true).unwrap();
Ok(())
}

fn new_challenge(&self) -> Result<(), Error> {
let unsubscribe = ProtocolRequest::Unsubscribe {
address: self.address.public_key.to_string(),
};
self.send(&unsubscribe)
.expect("could not send unsubscribe request!");

let request = ProtocolRequest::Challenge;

self.send(&request)
.expect("could not send subscribe request!");

.expect("Could not send Challenge request!");
Ok(())
}

Expand Down
2 changes: 0 additions & 2 deletions src/cmd/wallet_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,15 +352,13 @@ pub fn parse_listen_args(
config.api_listen_port = port.parse().unwrap();
}

let interval = parse_u64_or_none(args.value_of("interval"));
let method = parse_required(args, "method")?;

if args.is_present("no_tor") {
tor_config.use_tor_listener = false;
}
Ok(command::ListenArgs {
method: method.to_owned(),
interval,
})
}

Expand Down