Skip to content

Commit

Permalink
feat(lsp): be able to provide liquitidy to other nodes
Browse files Browse the repository at this point in the history
This commit allows our node to act as a server to provide
liquidity to other nodes.
  • Loading branch information
Harshit933 committed Jul 31, 2024
1 parent bf9692e commit b621c4d
Show file tree
Hide file tree
Showing 13 changed files with 593 additions and 142 deletions.
56 changes: 56 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lampo-common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ crossbeam-channel = "0.5.8"
anyhow = "1.0.70"
colored = "1.9"
log = { version = "0.4", features = ["std"] }
chrono = { version = "0.4", features = ["std"], default-features = false }
chrono = { version = "0.4", features = ["std", "clock"], default-features = false }
serde_json = "1.0"
serde = "1.0"
hex = "0.4.3"
15 changes: 15 additions & 0 deletions lampo-common/src/conf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ pub struct LampoConf {
pub log_level: String,
pub alias: Option<String>,
pub announce_addr: Option<String>,
// Should be something like liquidity=consumer, liquidity=provider or none
pub liquidity: Option<String>,
}

impl Default for LampoConf {
Expand Down Expand Up @@ -51,6 +53,7 @@ impl Default for LampoConf {
log_file: None,
alias: None,
announce_addr: None,
liquidity: None,
}
}
}
Expand Down Expand Up @@ -133,6 +136,16 @@ impl LampoConf {

Ok(conf)
}

// These functions should be called when we get something like
// liquidity=consumer of liquidity=provider inside lampo.conf
pub fn configure_as_liquidity_consumer(&mut self) {
self.liquidity = Some("Consumer".to_string())
}

pub fn configure_as_liquidity_provider(&mut self) {
self.liquidity = Some("Provider".to_string())
}
}

impl TryFrom<String> for LampoConf {
Expand Down Expand Up @@ -220,6 +233,7 @@ impl TryFrom<String> for LampoConf {
let log_file = conf.get_conf("log-file").unwrap_or(None);
let alias = conf.get_conf("alias").unwrap_or(None);
let announce_addr = conf.get_conf("announce-addr").unwrap_or(None);
let liquidity = conf.get_conf("liquidity").unwrap_or(None);

Ok(Self {
inner: Some(conf),
Expand All @@ -237,6 +251,7 @@ impl TryFrom<String> for LampoConf {
log_level: level,
alias,
announce_addr,
liquidity,
})
}
}
Expand Down
1 change: 1 addition & 0 deletions lampo-common/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,5 +64,6 @@ impl<T: Clone> Subscriber<T> {
pub enum Event {
Lightning(LightningEvent),
OnChain(OnChainEvent),
Liquidity(String),
Inventory,
}
4 changes: 4 additions & 0 deletions lampo-common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,7 @@ pub mod btc_rpc {
pub mempoolminfee: f32,
}
}

pub mod chrono {
pub use chrono::*;
}
4 changes: 2 additions & 2 deletions lampo-common/src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::time::SystemTime;
// FIXME: this is not async we should modify it
use std::fs::File;

use chrono::prelude::*;
use crate::chrono::prelude::*;
use colored::*;

pub use log::{Level, Log, Metadata, Record, SetLoggerError};
Expand Down Expand Up @@ -53,7 +53,7 @@ impl Log for Logger {
writeln!(
stream,
"{} {}",
DateTime::from(SystemTime::now())
DateTime::<Utc>::from(SystemTime::now())
.to_rfc3339_opts(SecondsFormat::Millis, true)
.white(),
message,
Expand Down
1 change: 1 addition & 0 deletions lampod-cli/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ impl TryInto<LampoConf> for LampoCliArgs {

let path = self.data_dir.unwrap_or(conf.root_path);
// FIXME: this override the full configuration, we should merge the two
// FIXME: Make this configurable
conf = LampoConf::new(Some(path), Some(conf.network), None)?;
conf.prepare_dirs()?;

Expand Down
30 changes: 26 additions & 4 deletions lampod/src/actions/handler.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//! Handler module implementation that
use std::borrow::Borrow;

Check warning on line 2 in lampod/src/actions/handler.rs

View workflow job for this annotation

GitHub Actions / Build (stable)

unused import: `std::borrow::Borrow`

Check warning on line 2 in lampod/src/actions/handler.rs

View workflow job for this annotation

GitHub Actions / Build (stable)

unused import: `std::borrow::Borrow`

Check warning on line 2 in lampod/src/actions/handler.rs

View workflow job for this annotation

GitHub Actions / Build (stable)

unused import: `std::borrow::Borrow`
use std::cell::RefCell;
use std::sync::Arc;

Expand All @@ -19,22 +20,22 @@ use crate::chain::{LampoChainManager, WalletManager};
use crate::command::Command;
use crate::handler::external_handler::ExternalHandler;
use crate::ln::events::PeerEvents;
use crate::ln::liquidity::LampoLiquidityManager;
use crate::ln::{LampoChannelManager, LampoInventoryManager, LampoPeerManager};
use crate::{async_run, LampoDaemon};

use super::{Handler, InventoryHandler};

// TODO: Add a LampoLiquidity object here as we need to call, LampoLiquidity should contain LiquidityManager
// If configured, users must forward the [`Event::HTLCIntercepted`] event parameters to [`LSPS2ServiceHandler::htlc_intercepted`]
/// and the [`Event::ChannelReady`] event parameters to [`LSPS2ServiceHandler::channel_ready`].
pub struct LampoHandler {
channel_manager: Arc<LampoChannelManager>,
peer_manager: Arc<LampoPeerManager>,
inventory_manager: Arc<LampoInventoryManager>,
wallet_manager: Arc<dyn WalletManager>,
chain_manager: Arc<LampoChainManager>,
external_handlers: RefCell<Vec<Arc<dyn ExternalHandler>>>,
#[allow(dead_code)]
// Question: How about Option<Arc<Mutex<LampoLiquidityManager>>>
liquidity_manager: Option<RefCell<LampoLiquidityManager>>,
// Do this inside liquidity
emitter: Emitter<Event>,
subscriber: Subscriber<Event>,
}
Expand All @@ -53,6 +54,7 @@ impl LampoHandler {
wallet_manager: lampod.wallet_manager(),
chain_manager: lampod.onchain_manager(),
external_handlers: RefCell::new(Vec::new()),
liquidity_manager: lampod.liquidity.clone(),
emitter,
subscriber,
}
Expand Down Expand Up @@ -142,6 +144,10 @@ impl Handler for LampoHandler {
counterparty_node_id,
channel_type,
} => {
let liquidity_manager = self.liquidity_manager.clone();
if let Some(ref liq_manager) = liquidity_manager {
let _ = liquidity_manager.unwrap().borrow().channel_ready(user_channel_id, &channel_id, &counterparty_node_id);
}
log::info!("channel ready with node `{counterparty_node_id}`, and channel type {channel_type}");
self.emit(Event::Lightning(LightningEvent::ChannelReady {
counterparty_node_id,
Expand Down Expand Up @@ -287,6 +293,22 @@ impl Handler for LampoHandler {
self.emit(Event::Lightning(hop));
Ok(())
},
ldk::events::Event::HTLCIntercepted { intercept_id, requested_next_hop_scid, payment_hash, inbound_amount_msat, expected_outbound_amount_msat } => {
// TODO: Emit this event
log::info!("Intecepted an HTLC");
let liquidity_manager = self.liquidity_manager.clone();
if liquidity_manager.is_some() {
liquidity_manager.unwrap().borrow().htlc_intercepted(requested_next_hop_scid, intercept_id, expected_outbound_amount_msat, payment_hash)?;
}

Ok(())
},
ldk::events::Event::HTLCHandlingFailed { prev_channel_id, failed_next_destination } => {
todo!()
}
ldk::events::Event::PaymentForwarded { prev_channel_id, next_channel_id, prev_user_channel_id, next_user_channel_id, total_fee_earned_msat, skimmed_fee_msat, claim_from_onchain_tx, outbound_amount_forwarded_msat } => {
todo!()
}
_ => Err(error::anyhow!("unexpected ldk event: {:?}", event)),
}
}
Expand Down
Loading

0 comments on commit b621c4d

Please sign in to comment.