Skip to content

Commit

Permalink
feat: remove mandatory API key checks
Browse files Browse the repository at this point in the history
  • Loading branch information
hydra-yse committed Jan 4, 2025
1 parent 48c25e5 commit 292dcfc
Show file tree
Hide file tree
Showing 21 changed files with 109 additions and 104 deletions.
2 changes: 1 addition & 1 deletion lib/bindings/src/breez_sdk_liquid.udl
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ dictionary Config {
LiquidNetwork network;
u64 payment_timeout_sec;
u32 zero_conf_min_fee_rate_msat;
string sync_service_url;
string? sync_service_url;
string? breez_api_key;
string? cache_dir;
u64? zero_conf_max_amount_sat;
Expand Down
4 changes: 2 additions & 2 deletions lib/core/src/frb_generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2372,7 +2372,7 @@ impl SseDecode for crate::model::Config {
let mut var_network = <crate::model::LiquidNetwork>::sse_decode(deserializer);
let mut var_paymentTimeoutSec = <u64>::sse_decode(deserializer);
let mut var_zeroConfMinFeeRateMsat = <u32>::sse_decode(deserializer);
let mut var_syncServiceUrl = <String>::sse_decode(deserializer);
let mut var_syncServiceUrl = <Option<String>>::sse_decode(deserializer);
let mut var_zeroConfMaxAmountSat = <Option<u64>>::sse_decode(deserializer);
let mut var_breezApiKey = <Option<String>>::sse_decode(deserializer);
let mut var_externalInputParsers =
Expand Down Expand Up @@ -6779,7 +6779,7 @@ impl SseEncode for crate::model::Config {
<crate::model::LiquidNetwork>::sse_encode(self.network, serializer);
<u64>::sse_encode(self.payment_timeout_sec, serializer);
<u32>::sse_encode(self.zero_conf_min_fee_rate_msat, serializer);
<String>::sse_encode(self.sync_service_url, serializer);
<Option<String>>::sse_encode(self.sync_service_url, serializer);
<Option<u64>>::sse_encode(self.zero_conf_max_amount_sat, serializer);
<Option<String>>::sse_encode(self.breez_api_key, serializer);
<Option<Vec<crate::bindings::ExternalInputParser>>>::sse_encode(
Expand Down
15 changes: 8 additions & 7 deletions lib/core/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use crate::utils;
// Uses f64 for the maximum precision when converting between units
pub const LIQUID_FEE_RATE_SAT_PER_VBYTE: f64 = 0.1;
pub const LIQUID_FEE_RATE_MSAT_PER_VBYTE: f32 = (LIQUID_FEE_RATE_SAT_PER_VBYTE * 1000.0) as f32;
const BREEZ_SYNC_SERVICE_URL: &str = "https://datasync.breez.technology";
pub const BREEZ_SYNC_SERVICE_URL: &str = "https://datasync.breez.technology";

/// Configuration for the Liquid SDK
#[derive(Clone, Debug, Serialize)]
Expand All @@ -50,8 +50,9 @@ pub struct Config {
pub payment_timeout_sec: u64,
/// Zero-conf minimum accepted fee-rate in millisatoshis per vbyte
pub zero_conf_min_fee_rate_msat: u32,
/// The url of the real-time sync service
pub sync_service_url: String,
/// The url of the real-time sync service. Defaults to [BREEZ_SYNC_SERVICE_URL]
/// Setting this field to `None` will disable the serivce
pub sync_service_url: Option<String>,
/// Maximum amount in satoshi to accept zero-conf payments with
/// Defaults to [DEFAULT_ZERO_CONF_MAX_SAT]
pub zero_conf_max_amount_sat: Option<u64>,
Expand All @@ -68,7 +69,7 @@ pub struct Config {
}

impl Config {
pub fn mainnet(breez_api_key: String) -> Self {
pub fn mainnet(breez_api_key: Option<String>) -> Self {
Config {
liquid_electrum_url: "elements-mainnet.breez.technology:50002".to_string(),
bitcoin_electrum_url: "bitcoin-mainnet.blockstream.info:50002".to_string(),
Expand All @@ -78,9 +79,9 @@ impl Config {
network: LiquidNetwork::Mainnet,
payment_timeout_sec: 15,
zero_conf_min_fee_rate_msat: DEFAULT_ZERO_CONF_MIN_FEE_RATE_MAINNET,
sync_service_url: BREEZ_SYNC_SERVICE_URL.to_string(),
sync_service_url: Some(BREEZ_SYNC_SERVICE_URL.to_string()),
zero_conf_max_amount_sat: None,
breez_api_key: Some(breez_api_key),
breez_api_key,
external_input_parsers: None,
use_default_external_input_parsers: true,
}
Expand All @@ -96,7 +97,7 @@ impl Config {
network: LiquidNetwork::Testnet,
payment_timeout_sec: 15,
zero_conf_min_fee_rate_msat: DEFAULT_ZERO_CONF_MIN_FEE_RATE_TESTNET,
sync_service_url: BREEZ_SYNC_SERVICE_URL.to_string(),
sync_service_url: Some(BREEZ_SYNC_SERVICE_URL.to_string()),
zero_conf_max_amount_sat: None,
breez_api_key,
external_input_parsers: None,
Expand Down
5 changes: 2 additions & 3 deletions lib/core/src/persist/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ impl Persister {
let tx = con.transaction_with_behavior(TransactionBehavior::Immediate)?;
self.set_last_derivation_index_inner(&tx, index)?;
tx.commit()?;
self.sync_trigger.try_send(())?;
self.trigger_sync()?;
Ok(())
}

Expand All @@ -151,8 +151,7 @@ impl Persister {
None => None,
};
tx.commit()?;
self.sync_trigger.try_send(())?;

self.trigger_sync()?;
Ok(res)
}
}
Expand Down
18 changes: 7 additions & 11 deletions lib/core/src/persist/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ impl Persister {
true => {
self.commit_outgoing(&tx, &chain_swap.id, RecordType::Chain, updated_fields)?;
tx.commit()?;
self.sync_trigger.try_send(())?;
self.trigger_sync()?;
}
false => {
tx.commit()?;
Expand Down Expand Up @@ -272,11 +272,9 @@ impl Persister {
Some(vec!["accept_zero_conf".to_string()]),
)?;
tx.commit()?;
self.sync_trigger
.try_send(())
.map_err(|err| PaymentError::Generic {
err: format!("Could not trigger manual sync: {err:?}"),
})?;
self.trigger_sync().map_err(|err| PaymentError::Generic {
err: format!("Could not trigger manual sync: {err:?}"),
})?;

Ok(())
}
Expand Down Expand Up @@ -316,11 +314,9 @@ impl Persister {
]),
)?;
tx.commit()?;
self.sync_trigger
.try_send(())
.map_err(|err| PaymentError::Generic {
err: format!("Could not trigger manual sync: {err:?}"),
})?;
self.trigger_sync().map_err(|err| PaymentError::Generic {
err: format!("Could not trigger manual sync: {err:?}"),
})?;

Ok(())
}
Expand Down
13 changes: 6 additions & 7 deletions lib/core/src/persist/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub(crate) mod sync;

use std::collections::{HashMap, HashSet};
use std::ops::Not;
use std::sync::RwLock;
use std::{fs::create_dir_all, path::PathBuf, str::FromStr};

use crate::lightning_invoice::{Bolt11Invoice, Bolt11InvoiceDescription};
Expand All @@ -33,7 +34,7 @@ const DEFAULT_DB_FILENAME: &str = "storage.sql";
pub(crate) struct Persister {
main_db_dir: PathBuf,
network: LiquidNetwork,
sync_trigger: Sender<()>,
pub(crate) sync_trigger: RwLock<Option<Sender<()>>>,
}

/// Builds a WHERE clause that checks if `state` is any of the given arguments
Expand All @@ -52,7 +53,7 @@ impl Persister {
pub fn new(
working_dir: &str,
network: LiquidNetwork,
sync_trigger: Sender<()>,
sync_trigger: Option<Sender<()>>,
) -> Result<Self> {
let main_db_dir = PathBuf::from_str(working_dir)?;
if !main_db_dir.exists() {
Expand All @@ -61,7 +62,7 @@ impl Persister {
Ok(Persister {
main_db_dir,
network,
sync_trigger,
sync_trigger: RwLock::new(sync_trigger),
})
}

Expand Down Expand Up @@ -238,9 +239,8 @@ impl Persister {
}

tx.commit()?;

if trigger_sync {
self.sync_trigger.try_send(())?;
self.trigger_sync()?;
}

Ok(())
Expand Down Expand Up @@ -299,8 +299,7 @@ impl Persister {
None,
)?;
tx.commit()?;

self.sync_trigger.try_send(())?;
self.trigger_sync()?;

Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion lib/core/src/persist/receive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ impl Persister {
true => {
self.commit_outgoing(&tx, &receive_swap.id, RecordType::Receive, updated_fields)?;
tx.commit()?;
self.sync_trigger.try_send(())?;
self.trigger_sync()?;
}
false => {
tx.commit()?;
Expand Down
11 changes: 5 additions & 6 deletions lib/core/src/persist/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ impl Persister {
true => {
self.commit_outgoing(&tx, &send_swap.id, RecordType::Send, updated_fields)?;
tx.commit()?;
self.sync_trigger.try_send(())?;
self.trigger_sync()?;
}
false => {
tx.commit()?;
Expand Down Expand Up @@ -282,11 +282,10 @@ impl Persister {
let updated_fields = get_updated_fields!(preimage);
self.commit_outgoing(&tx, swap_id, RecordType::Send, updated_fields)?;
tx.commit()?;
self.sync_trigger
.try_send(())
.map_err(|err| PaymentError::Generic {
err: format!("Could not trigger manual sync: {err:?}"),
})?;

self.trigger_sync().map_err(|err| PaymentError::Generic {
err: format!("Could not trigger manual sync: {err:?}"),
})?;

Ok(())
}
Expand Down
13 changes: 12 additions & 1 deletion lib/core/src/persist/sync.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::collections::HashMap;
use std::{collections::HashMap, ops::Deref};

use anyhow::Result;
use rusqlite::{
Expand Down Expand Up @@ -249,6 +249,10 @@ impl Persister {
record_type: RecordType,
updated_fields: Option<Vec<String>>,
) -> Result<()> {
if self.sync_trigger.read().unwrap().is_none() {
return Ok(());
}

let record_id = Record::get_id_from_record_type(record_type, data_id);
let updated_fields = updated_fields
.map(|fields| {
Expand Down Expand Up @@ -493,4 +497,11 @@ impl Persister {

Ok(())
}

pub(crate) fn trigger_sync(&self) -> Result<()> {
if let Some(trigger) = self.sync_trigger.read().unwrap().deref() {
return Ok(trigger.try_send(())?);
}
Ok(())
}
}
77 changes: 35 additions & 42 deletions lib/core/src/sdk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ pub struct LiquidSdk {
pub(crate) shutdown_sender: watch::Sender<()>,
pub(crate) shutdown_receiver: watch::Receiver<()>,
pub(crate) send_swap_handler: SendSwapHandler,
pub(crate) sync_service: Arc<SyncService>,
pub(crate) sync_service: Option<Arc<SyncService>>,
pub(crate) receive_swap_handler: ReceiveSwapHandler,
pub(crate) chain_swap_handler: Arc<ChainSwapHandler>,
pub(crate) buy_bitcoin_service: Arc<dyn BuyBitcoinApi>,
Expand Down Expand Up @@ -130,7 +130,7 @@ impl LiquidSdk {
Ok(sdk)
}

fn validate_api_key(api_key: &str) -> Result<()> {
fn validate_breez_api_key(api_key: &str) -> Result<()> {
let api_key_decoded = lwk_wollet::bitcoin::base64::engine::general_purpose::STANDARD
.decode(api_key.as_bytes())
.map_err(|err| anyhow!("Could not base64 decode the Breez API key: {err:?}"))?;
Expand Down Expand Up @@ -160,13 +160,9 @@ impl LiquidSdk {
swapper_proxy_url: Option<String>,
signer: Arc<Box<dyn Signer>>,
) -> Result<Arc<Self>> {
match (config.network, &config.breez_api_key) {
(_, Some(api_key)) => Self::validate_api_key(api_key)?,
(LiquidNetwork::Mainnet, None) => {
return Err(anyhow!("Breez API key must be provided on mainnet."));
}
(LiquidNetwork::Testnet, None) => {}
};
if let Some(breez_api_key) = &config.breez_api_key {
Self::validate_breez_api_key(breez_api_key)?
}

fs::create_dir_all(&config.working_dir)?;
let fingerprint_hex: String =
Expand All @@ -177,12 +173,7 @@ impl LiquidSdk {
&fingerprint_hex,
)?;

let (sync_trigger_tx, sync_trigger_rx) = tokio::sync::mpsc::channel::<()>(30);
let persister = Arc::new(Persister::new(
&working_dir,
config.network,
sync_trigger_tx,
)?);
let persister = Arc::new(Persister::new(&working_dir, config.network, None)?);
persister.init()?;

let liquid_chain_service =
Expand All @@ -204,15 +195,23 @@ impl LiquidSdk {
bitcoin_chain_service.clone(),
)?);

let syncer_client = Box::new(BreezSyncerClient::new(config.breez_api_key.clone()));
let sync_service = Arc::new(SyncService::new(
config.sync_service_url.clone(),
persister.clone(),
recoverer.clone(),
signer.clone(),
syncer_client,
sync_trigger_rx,
));
let mut sync_service = None;
if let Some(sync_service_url) = config.sync_service_url.clone() {
if BREEZ_SYNC_SERVICE_URL == sync_service_url && config.breez_api_key.is_none() {
anyhow::bail!(
"Cannot start the Breez real-time sync service without providing a valid API key. See https://sdk-doc-liquid.breez.technology/guide/getting_started.html#api-key",
);
}

let syncer_client = Box::new(BreezSyncerClient::new(config.breez_api_key.clone()));
sync_service = Some(Arc::new(SyncService::new(
sync_service_url,
persister.clone(),
recoverer.clone(),
signer.clone(),
syncer_client,
)));
}

let event_manager = Arc::new(EventManager::new());
let (shutdown_sender, shutdown_receiver) = watch::channel::<()>(());
Expand Down Expand Up @@ -315,10 +314,9 @@ impl LiquidSdk {
.clone()
.start(reconnect_handler, self.shutdown_receiver.clone())
.await;
self.sync_service
.clone()
.start(self.shutdown_receiver.clone())
.await?;
if let Some(sync_service) = self.sync_service.clone() {
sync_service.start(self.shutdown_receiver.clone()).await?;
}
self.track_new_blocks().await;
self.track_swap_updates().await;

Expand Down Expand Up @@ -929,12 +927,14 @@ impl LiquidSdk {
};
}
Ok(InputType::Bolt11 { invoice }) => {
self.sync_service
.pull()
.await
.map_err(|err| PaymentError::Generic {
err: format!("Could not pull real-time sync changes: {err:?}"),
})?;
if let Some(sync_service) = &self.sync_service {
sync_service
.pull()
.await
.map_err(|err| PaymentError::Generic {
err: format!("Could not pull real-time sync changes: {err:?}"),
})?;
}
self.ensure_send_is_not_self_transfer(&invoice.bolt11)?;
self.validate_bolt11_invoice(&invoice.bolt11)?;

Expand Down Expand Up @@ -2906,14 +2906,7 @@ impl LiquidSdk {
breez_api_key: Option<String>,
) -> Result<Config, SdkError> {
let config = match network {
LiquidNetwork::Mainnet => {
let Some(breez_api_key) = breez_api_key else {
return Err(SdkError::Generic {
err: "Breez API key must be provided on mainnet.".to_string(),
});
};
Config::mainnet(breez_api_key)
}
LiquidNetwork::Mainnet => Config::mainnet(breez_api_key),
LiquidNetwork::Testnet => Config::testnet(breez_api_key),
};
Ok(config)
Expand Down
4 changes: 2 additions & 2 deletions lib/core/src/sync/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,9 @@ pub struct ApiKeyInterceptor {

impl Interceptor for ApiKeyInterceptor {
fn call(&mut self, mut req: Request<()>) -> Result<Request<()>, Status> {
if self.api_key_metadata.clone().is_some() {
if let Some(api_key_metadata) = &self.api_key_metadata {
req.metadata_mut()
.insert("authorization", self.api_key_metadata.clone().unwrap());
.insert("authorization", api_key_metadata.clone());
}
Ok(req)
}
Expand Down
Loading

0 comments on commit 292dcfc

Please sign in to comment.