Skip to content

Commit

Permalink
Merge pull request #1263 from getlipa/feature/major-refactor-config
Browse files Browse the repository at this point in the history
Implement `Config` module
  • Loading branch information
danielgranhao authored Nov 18, 2024
2 parents 6f8fbfe + 0349f09 commit f1a6e77
Show file tree
Hide file tree
Showing 21 changed files with 648 additions and 545 deletions.
15 changes: 9 additions & 6 deletions examples/node/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,10 +323,10 @@ pub(crate) fn poll_for_user_input(node: &LightningNode, log_file_path: &str) {
Err(message) => println!("{}", format!("{message:#}").red()),
},
"foreground" => {
node.foreground();
node.config().foreground();
}
"background" => {
node.background();
node.config().background();
}
"closechannels" => {
if let Err(message) = node.close_all_channels_with_current_lsp() {
Expand Down Expand Up @@ -694,15 +694,16 @@ fn get_exchange_rate(node: &LightningNode) {
}

fn list_currency_codes(node: &LightningNode) {
let codes = node.list_currency_codes();
let codes = node.config().list_currencies();
println!("Supported currencies: {codes:?}");
}

fn change_currency(node: &LightningNode, words: &mut dyn Iterator<Item = &str>) -> Result<()> {
let fiat_currency = words
.next()
.ok_or(anyhow!("Fiat currency code is required"))?;
node.change_fiat_currency(String::from(fiat_currency))?;
node.config()
.set_fiat_currency(String::from(fiat_currency))?;
Ok(())
}

Expand All @@ -724,7 +725,7 @@ fn change_timezone(node: &LightningNode, words: &mut dyn Iterator<Item = &str>)
tz_config.timezone_utc_offset_secs
);
println!(" Timezone id: {}", tz_config.timezone_id);
node.change_timezone_config(tz_config);
node.config().set_timezone_config(tz_config);
Ok(())
}

Expand Down Expand Up @@ -1656,7 +1657,9 @@ fn set_feature_flag(node: &LightningNode, words: &mut dyn Iterator<Item = &str>)
.next()
.ok_or(anyhow!("<enabled> is required"))?
.parse()?;
node.set_feature_flag(feature, enabled).map_err(Into::into)
node.config()
.set_feature_flag(feature, enabled)
.map_err(Into::into)
}

fn hide_failed_swap(node: &LightningNode, words: &mut dyn Iterator<Item = &str>) -> Result<()> {
Expand Down
4 changes: 2 additions & 2 deletions examples/node/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use uniffi_lipalightninglib::{
mnemonic_to_secret, recover_lightning_node, BreezSdkConfig, LightningNode, MaxRoutingFeeConfig,
ReceiveLimitsConfig, RemoteServicesConfig,
};
use uniffi_lipalightninglib::{Config, TzConfig};
use uniffi_lipalightninglib::{LightningNodeConfig, TzConfig};

use crate::environment::{Environment, EnvironmentCode};
use log::Level;
Expand Down Expand Up @@ -53,7 +53,7 @@ fn main() {
.unwrap();
}

let config = Config {
let config = LightningNodeConfig {
seed,
default_fiat_currency: "EUR".to_string(),
local_persistence_path: base_dir.clone(),
Expand Down
8 changes: 4 additions & 4 deletions examples/notification_handler/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ use std::collections::HashSet;
use std::env;
use std::time::Duration;
use uniffi_lipalightninglib::{
handle_notification, mnemonic_to_secret, BreezSdkConfig, Config, MaxRoutingFeeConfig,
NotificationToggles, ReceiveLimitsConfig, RemoteServicesConfig, TzConfig,
handle_notification, mnemonic_to_secret, BreezSdkConfig, LightningNodeConfig,
MaxRoutingFeeConfig, NotificationToggles, ReceiveLimitsConfig, RemoteServicesConfig, TzConfig,
};

static BASE_DIR: &str = ".3l_node";
Expand Down Expand Up @@ -112,15 +112,15 @@ fn map_environment_code(code: &str) -> EnvironmentCode {
}
}

fn get_config() -> Config {
fn get_config() -> LightningNodeConfig {
let base_dir = format!("{BASE_DIR}_{}", ENVIRONMENT.as_str());

let environment_code = map_environment_code(ENVIRONMENT.as_str());
let environment = Environment::load(environment_code);

let seed = read_seed_from_env();

Config {
LightningNodeConfig {
seed,
default_fiat_currency: "EUR".to_string(),
local_persistence_path: base_dir.clone(),
Expand Down
115 changes: 69 additions & 46 deletions src/activities.rs
Original file line number Diff line number Diff line change
@@ -1,53 +1,33 @@
use crate::amount::{AsSats, ToAmount};
use crate::async_runtime::Handle;
use crate::config::WithTimezone;
use crate::data_store::{CreatedInvoice, DataStore};
use crate::data_store::CreatedInvoice;
use crate::errors::Result;
use crate::locker::Locker;
use crate::node_config::WithTimezone;
use crate::support::Support;
use crate::util::unix_timestamp_to_system_time;
use crate::{
fill_payout_fee, filter_out_and_log_corrupted_activities,
filter_out_and_log_corrupted_payments, Activity, ChannelCloseInfo, ChannelCloseState, Config,
filter_out_and_log_corrupted_payments, Activity, ChannelCloseInfo, ChannelCloseState,
IncomingPaymentInfo, InvoiceDetails, ListActivitiesResponse, OutgoingPaymentInfo, PaymentInfo,
PaymentState, ReverseSwapInfo, RuntimeErrorCode, SwapInfo, UserPreferences,
PaymentState, ReverseSwapInfo, RuntimeErrorCode, SwapInfo,
};
use breez_sdk_core::{
parse_invoice, BreezServices, ClosedChannelPaymentDetails, ListPaymentsRequest, PaymentDetails,
PaymentStatus, PaymentTypeFilter,
parse_invoice, ClosedChannelPaymentDetails, ListPaymentsRequest, PaymentDetails, PaymentStatus,
PaymentTypeFilter,
};
use perro::{invalid_input, permanent_failure, MapToError, OptionToError};
use std::cmp::{min, Reverse};
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use std::sync::Arc;
use std::time::SystemTime;

pub struct Activities {
rt_handle: Handle,
sdk: Arc<BreezServices>,
data_store: Arc<Mutex<DataStore>>,
user_preferences: Arc<Mutex<UserPreferences>>,
config: Config,
support: Arc<Support>,
}

impl Activities {
pub(crate) fn new(
rt_handle: Handle,
sdk: Arc<BreezServices>,
data_store: Arc<Mutex<DataStore>>,
user_preferences: Arc<Mutex<UserPreferences>>,
config: Config,
support: Arc<Support>,
) -> Self {
Self {
rt_handle,
sdk,
data_store,
user_preferences,
config,
support,
}
pub(crate) fn new(support: Arc<Support>) -> Self {
Self { support }
}

/// List the latest activities
Expand All @@ -72,8 +52,10 @@ impl Activities {
offset: None,
};
let breez_activities = self
.rt_handle
.block_on(self.sdk.list_payments(list_payments_request))
.support
.rt
.handle()
.block_on(self.support.sdk.list_payments(list_payments_request))
.map_to_runtime_error(RuntimeErrorCode::NodeUnavailable, "Failed to list payments")?
.into_iter()
.map(|p| self.activity_from_breez_payment(p))
Expand All @@ -82,6 +64,7 @@ impl Activities {

// Query created invoices, filter out ones which are in the breez db.
let created_invoices = self
.support
.data_store
.lock_unwrap()
.retrieve_created_invoices(number_of_completed_activities)?;
Expand All @@ -103,15 +86,23 @@ impl Activities {
completed_activities.truncate(number_of_completed_activities as usize);

if let Some(in_progress_swap) = self
.rt_handle
.block_on(self.sdk.in_progress_swap())
.support
.rt
.handle()
.block_on(self.support.sdk.in_progress_swap())
.map_to_runtime_error(
RuntimeErrorCode::NodeUnavailable,
"Failed to get in-progress swap",
)?
{
let created_at = unix_timestamp_to_system_time(in_progress_swap.created_at as u64)
.with_timezone(self.user_preferences.lock_unwrap().clone().timezone_config);
.with_timezone(
self.support
.user_preferences
.lock_unwrap()
.clone()
.timezone_config,
);

pending_activities.push(Activity::Swap {
incoming_payment_info: None,
Expand Down Expand Up @@ -145,8 +136,10 @@ impl Activities {
/// Requires network: **no**
pub fn get(&self, hash: String) -> Result<Activity> {
if let Some(activity) = self
.rt_handle
.block_on(self.sdk.payment_by_hash(hash.clone()))
.support
.rt
.handle()
.block_on(self.support.sdk.payment_by_hash(hash.clone()))
.map_to_runtime_error(
RuntimeErrorCode::NodeUnavailable,
"Failed to get payment by hash",
Expand All @@ -155,6 +148,7 @@ impl Activities {
{
Ok(activity?)
} else if let Some(incoming_payment_info) = self
.support
.data_store
.lock_unwrap()
.retrieve_created_invoice_by_hash(&hash)?
Expand Down Expand Up @@ -194,8 +188,10 @@ impl Activities {
}
false
};
self.rt_handle
.block_on(self.sdk.list_payments(list_payments_request))
self.support
.rt
.handle()
.block_on(self.support.sdk.list_payments(list_payments_request))
.map_to_runtime_error(RuntimeErrorCode::NodeUnavailable, "Failed to list payments")?
.into_iter()
.find(is_swap_with_id)
Expand Down Expand Up @@ -262,7 +258,8 @@ impl Activities {
pub fn set_personal_note(&self, payment_hash: String, note: String) -> Result<()> {
let note = Some(note.trim().to_string()).filter(|s| !s.is_empty());

self.data_store
self.support
.data_store
.lock_unwrap()
.update_personal_note(&payment_hash, note.as_deref())
}
Expand Down Expand Up @@ -316,6 +313,7 @@ impl Activities {
}
};
let local_payment_data = self
.support
.data_store
.lock_unwrap()
.retrieve_payment_info(&payment_details.payment_hash)?;
Expand All @@ -331,7 +329,11 @@ impl Activities {
),
None => (
self.support.get_exchange_rate(),
self.user_preferences.lock_unwrap().timezone_config.clone(),
self.support
.user_preferences
.lock_unwrap()
.timezone_config
.clone(),
None,
None,
None,
Expand All @@ -347,7 +349,11 @@ impl Activities {
personal_note,
received_on,
received_lnurl_comment,
&self.config.remote_services_config.lipa_lightning_domain,
&self
.support
.node_config
.remote_services_config
.lipa_lightning_domain,
)?;
let offer_kind = fill_payout_fee(
offer,
Expand All @@ -373,7 +379,11 @@ impl Activities {
personal_note,
received_on,
received_lnurl_comment,
&self.config.remote_services_config.lipa_lightning_domain,
&self
.support
.node_config
.remote_services_config
.lipa_lightning_domain,
)?;
Ok(Activity::Swap {
incoming_payment_info: Some(incoming_payment_info),
Expand All @@ -394,7 +404,11 @@ impl Activities {
&exchange_rate,
tz_config,
personal_note,
&self.config.remote_services_config.lipa_lightning_domain,
&self
.support
.node_config
.remote_services_config
.lipa_lightning_domain,
)?;
Ok(Activity::ReverseSwap {
outgoing_payment_info,
Expand All @@ -408,7 +422,11 @@ impl Activities {
personal_note,
received_on,
received_lnurl_comment,
&self.config.remote_services_config.lipa_lightning_domain,
&self
.support
.node_config
.remote_services_config
.lipa_lightning_domain,
)?;
Ok(Activity::IncomingPayment {
incoming_payment_info,
Expand All @@ -419,7 +437,11 @@ impl Activities {
&exchange_rate,
tz_config,
personal_note,
&self.config.remote_services_config.lipa_lightning_domain,
&self
.support
.node_config
.remote_services_config
.lipa_lightning_domain,
)?;
Ok(Activity::OutgoingPayment {
outgoing_payment_info,
Expand All @@ -439,7 +461,7 @@ impl Activities {
.as_msats()
.to_amount_up(&self.support.get_exchange_rate());

let user_preferences = self.user_preferences.lock_unwrap();
let user_preferences = self.support.user_preferences.lock_unwrap();

let time = unix_timestamp_to_system_time(breez_payment.payment_time as u64)
.with_timezone(user_preferences.timezone_config.clone());
Expand Down Expand Up @@ -483,6 +505,7 @@ impl Activities {
};

let local_payment_data = self
.support
.data_store
.lock_unwrap()
.retrieve_payment_info(&invoice_details.payment_hash)?
Expand Down
Loading

0 comments on commit f1a6e77

Please sign in to comment.