Skip to content
This repository was archived by the owner on Jan 6, 2025. It is now read-only.

Restructure crate #48

Merged
merged 6 commits into from
Nov 28, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
2 changes: 2 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,5 @@ jobs:
run: rustup component add rustfmt && cargo fmt --all -- --check
- name: Test on Rust ${{ matrix.toolchain }}
run: cargo test
- name: Test on Rust ${{ matrix.toolchain }} with LSPS1 support
run: RUSTFLAGS="--cfg lsps1" cargo test
12 changes: 7 additions & 5 deletions src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@
//! [`LiquidityManager::get_and_clear_pending_events`] to receive events.
//!
//! [`LiquidityManager::get_and_clear_pending_events`]: crate::LiquidityManager::get_and_clear_pending_events
/// [`crate::LiquidityManager::get_and_clear_pending_events()`] to receive events.
use crate::channel_request;
use crate::jit_channel;

#[cfg(lsps1)]
use crate::lsps1;
use crate::lsps2;
use std::collections::VecDeque;
use std::sync::{Condvar, Mutex};

Expand Down Expand Up @@ -61,7 +62,8 @@ impl EventQueue {
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
/// An LSPS2 (JIT Channel) protocol event.
LSPS2(jit_channel::LSPS2Event),
LSPS2(lsps2::LSPS2Event),
/// An LSPS1 protocol event.
LSPS1(channel_request::event::Event),
#[cfg(lsps1)]
LSPS1(lsps1::event::Event),
}
13 changes: 5 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,11 @@
#![allow(clippy::drop_non_drop)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

mod channel_request;
pub mod events;
pub mod jit_channel;
mod transport;
mod lsps0;
#[cfg(lsps1)]
mod lsps1;
pub mod lsps2;
mod utils;

pub use channel_request::event::Event as LSPS1Event;
pub use transport::message_handler::{
JITChannelsConfig, LiquidityManager, LiquidityProviderConfig,
};
pub use transport::msgs::{RawLSPSMessage, LSPS_MESSAGE_TYPE_ID};
pub use lsps0::message_handler::{JITChannelsConfig, LiquidityManager, LiquidityProviderConfig};
49 changes: 32 additions & 17 deletions src/transport/message_handler.rs → src/lsps0/message_handler.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
#![allow(missing_docs)]
use crate::channel_request::channel_manager::CRManager;
use crate::channel_request::msgs::{
ChannelInfo, OptionsSupported, Order, OrderId, OrderState, Payment,

#[cfg(lsps1)]
use {
crate::lsps1::channel_manager::CRManager,
crate::lsps1::msgs::{ChannelInfo, OptionsSupported, Order, OrderId, OrderState, Payment},
};

use crate::events::{Event, EventQueue};
use crate::jit_channel::channel_manager::JITChannelManager;
use crate::jit_channel::msgs::{OpeningFeeParams, RawOpeningFeeParams};
use crate::transport::msgs::RequestId;
use crate::transport::msgs::{LSPSMessage, RawLSPSMessage, LSPS_MESSAGE_TYPE_ID};
use crate::transport::protocol::LSPS0MessageHandler;
use crate::lsps0::msgs::RequestId;
use crate::lsps0::msgs::{LSPSMessage, RawLSPSMessage, LSPS_MESSAGE_TYPE_ID};
use crate::lsps0::protocol::LSPS0MessageHandler;
use crate::lsps2::channel_manager::JITChannelManager;
use crate::lsps2::msgs::{OpeningFeeParams, RawOpeningFeeParams};

use chrono::Utc;
use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
Expand Down Expand Up @@ -57,10 +60,11 @@ pub(crate) trait ProtocolMessageHandler {
/// to provide liquidity services to clients.
pub struct LiquidityProviderConfig {
/// LSPS1 Configuration
#[cfg(lsps1)]
pub lsps1_config: Option<CRChannelConfig>,
/// Optional configuration for JIT channels
/// should you want to support them.
pub jit_channels: Option<JITChannelsConfig>,
pub lsps2_config: Option<JITChannelsConfig>,
}

/// Configuration options for JIT channels.
Expand All @@ -75,6 +79,7 @@ pub struct JITChannelsConfig {
pub max_payment_size_msat: u64,
}

#[cfg(lsps1)]
pub struct CRChannelConfig {
pub token: Option<String>,
pub max_fees: Option<u64>,
Expand Down Expand Up @@ -135,6 +140,7 @@ pub struct LiquidityManager<
pending_events: Arc<EventQueue>,
request_id_to_method_map: Mutex<HashMap<String, String>>,
lsps0_message_handler: LSPS0MessageHandler<ES>,
#[cfg(lsps1)]
lsps1_message_handler:
Option<CRManager<ES, M, T, F, R, SP, Descriptor, L, RM, CM, OM, CMH, NS>>,
lsps2_message_handler:
Expand Down Expand Up @@ -196,17 +202,18 @@ where {
);

let lsps2_message_handler = provider_config.as_ref().and_then(|config| {
config.jit_channels.as_ref().map(|jit_channels_config| {
config.lsps2_config.as_ref().map(|config| {
JITChannelManager::new(
entropy_source.clone(),
jit_channels_config,
config,
Arc::clone(&pending_messages),
Arc::clone(&pending_events),
Arc::clone(&channel_manager),
)
})
});

#[cfg(lsps1)]
let lsps1_message_handler = provider_config.as_ref().and_then(|config| {
config.lsps1_config.as_ref().map(|lsps1_config| {
CRManager::new(
Expand All @@ -224,6 +231,7 @@ where {
pending_events,
request_id_to_method_map: Mutex::new(HashMap::new()),
lsps0_message_handler,
#[cfg(lsps1)]
lsps1_message_handler,
lsps2_message_handler,
provider_config,
Expand Down Expand Up @@ -261,6 +269,7 @@ where {
pub fn set_peer_manager(
&self, peer_manager: Arc<PeerManager<Descriptor, CM, RM, OM, L, CMH, NS>>,
) {
#[cfg(lsps1)]
if let Some(lsps1_message_handler) = &self.lsps1_message_handler {
lsps1_message_handler.set_peer_manager(peer_manager.clone());
}
Expand All @@ -269,6 +278,7 @@ where {
}
}

#[cfg(lsps1)]
pub fn request_for_info(
&self, counterparty_node_id: PublicKey, channel_id: u128,
) -> Result<(), APIError> {
Expand All @@ -278,6 +288,7 @@ where {
Ok(())
}

#[cfg(lsps1)]
pub fn place_order(
&self, channel_id: u128, counterparty_node_id: &PublicKey, order: Order,
) -> Result<(), APIError> {
Expand All @@ -287,6 +298,7 @@ where {
Ok(())
}

#[cfg(lsps1)]
pub fn send_invoice_for_order(
&self, request_id: RequestId, counterparty_node_id: &PublicKey, payment: Payment,
created_at: chrono::DateTime<Utc>, expires_at: chrono::DateTime<Utc>,
Expand All @@ -303,6 +315,7 @@ where {
Ok(())
}

#[cfg(lsps1)]
pub fn check_order_status(
self, channel_id: u128, counterparty_node_id: &PublicKey, order_id: OrderId,
) -> Result<(), APIError> {
Expand All @@ -312,6 +325,7 @@ where {
Ok(())
}

#[cfg(lsps1)]
pub fn update_order_status(
&self, request_id: RequestId, counterparty_node_id: PublicKey, order_id: OrderId,
order_state: OrderState, channel: Option<ChannelInfo>,
Expand Down Expand Up @@ -341,7 +355,7 @@ where {
///
/// `token` is an optional String that will be provided to the LSP.
/// It can be used by the LSP as an API key, coupon code, or some other way to identify a user.
pub fn jit_channel_create_invoice(
pub fn lsps2_create_invoice(
&self, counterparty_node_id: PublicKey, payment_size_msat: Option<u64>,
token: Option<String>, user_channel_id: u128,
) -> Result<(), APIError> {
Expand All @@ -365,7 +379,7 @@ where {
///
/// Should be called in response to receiving a [`LSPS2Event::GetInfo`] event.
///
/// [`LSPS2Event::GetInfo`]: crate::jit_channel::LSPS2Event::GetInfo
/// [`LSPS2Event::GetInfo`]: crate::lsps2::LSPS2Event::GetInfo
pub fn invalid_token_provided(
&self, counterparty_node_id: PublicKey, request_id: RequestId,
) -> Result<(), APIError> {
Expand All @@ -383,7 +397,7 @@ where {
///
/// Should be called in response to receiving a [`LSPS2Event::GetInfo`] event.
///
/// [`LSPS2Event::GetInfo`]: crate::jit_channel::LSPS2Event::GetInfo
/// [`LSPS2Event::GetInfo`]: crate::lsps2::LSPS2Event::GetInfo
pub fn opening_fee_params_generated(
&self, counterparty_node_id: PublicKey, request_id: RequestId,
opening_fee_params_menu: Vec<RawOpeningFeeParams>,
Expand All @@ -408,7 +422,7 @@ where {
///
/// Should be called in response to receiving a [`LSPS2Event::GetInfoResponse`] event.
///
/// [`LSPS2Event::GetInfoResponse`]: crate::jit_channel::LSPS2Event::GetInfoResponse
/// [`LSPS2Event::GetInfoResponse`]: crate::lsps2::LSPS2Event::GetInfoResponse
pub fn opening_fee_params_selected(
&self, counterparty_node_id: PublicKey, channel_id: u128,
opening_fee_params: OpeningFeeParams,
Expand All @@ -431,7 +445,7 @@ where {
///
/// Should be called in response to receiving a [`LSPS2Event::BuyRequest`] event.
///
/// [`LSPS2Event::BuyRequest`]: crate::jit_channel::LSPS2Event::BuyRequest
/// [`LSPS2Event::BuyRequest`]: crate::lsps2::LSPS2Event::BuyRequest
pub fn invoice_parameters_generated(
&self, counterparty_node_id: PublicKey, request_id: RequestId, scid: u64,
cltv_expiry_delta: u32, client_trusts_lsp: bool,
Expand Down Expand Up @@ -463,7 +477,7 @@ where {
/// Will do nothing if the scid does not match any of the ones we gave out.
///
/// [`Event::HTLCIntercepted`]: lightning::events::Event::HTLCIntercepted
/// [`LSPS2Event::OpenChannel`]: crate::jit_channel::LSPS2Event::OpenChannel
/// [`LSPS2Event::OpenChannel`]: crate::lsps2::LSPS2Event::OpenChannel
pub fn htlc_intercepted(
&self, scid: u64, intercept_id: InterceptId, expected_outbound_amount_msat: u64,
) -> Result<(), APIError> {
Expand Down Expand Up @@ -508,6 +522,7 @@ where {
LSPSMessage::LSPS0(msg) => {
self.lsps0_message_handler.handle_message(msg, sender_node_id)?;
}
#[cfg(lsps1)]
LSPSMessage::LSPS1(msg) => match &self.lsps1_message_handler {
Some(lsps1_message_handler) => {
lsps1_message_handler.handle_message(msg, sender_node_id)?;
Expand Down
File renamed without changes.
23 changes: 17 additions & 6 deletions src/transport/msgs.rs → src/lsps0/msgs.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use crate::channel_request::msgs::{
#[cfg(lsps1)]
use crate::lsps1::msgs::{
LSPS1Message, LSPS1Request, LSPS1Response, LSPS1_CREATE_ORDER_METHOD_NAME,
LSPS1_GET_INFO_METHOD_NAME, LSPS1_GET_ORDER_METHOD_NAME,
};
use crate::jit_channel::msgs::{
use crate::lsps2::msgs::{
LSPS2Message, LSPS2Request, LSPS2Response, LSPS2_BUY_METHOD_NAME, LSPS2_GET_INFO_METHOD_NAME,
LSPS2_GET_VERSIONS_METHOD_NAME,
};
Expand Down Expand Up @@ -97,8 +98,9 @@ impl TryFrom<LSPSMessage> for LSPS0Message {
match message {
LSPSMessage::Invalid => Err(()),
LSPSMessage::LSPS0(message) => Ok(message),
LSPSMessage::LSPS2(_) => Err(()),
#[cfg(lsps1)]
LSPSMessage::LSPS1(_) => Err(()),
LSPSMessage::LSPS2(_) => Err(()),
}
}
}
Expand All @@ -113,8 +115,9 @@ impl From<LSPS0Message> for LSPSMessage {
pub enum LSPSMessage {
Invalid,
LSPS0(LSPS0Message),
LSPS2(LSPS2Message),
#[cfg(lsps1)]
LSPS1(LSPS1Message),
LSPS2(LSPS2Message),
}

impl LSPSMessage {
Expand All @@ -131,10 +134,11 @@ impl LSPSMessage {
LSPSMessage::LSPS0(LSPS0Message::Request(request_id, request)) => {
Some((request_id.0.clone(), request.method().to_string()))
}
LSPSMessage::LSPS2(LSPS2Message::Request(request_id, request)) => {
#[cfg(lsps1)]
LSPSMessage::LSPS1(LSPS1Message::Request(request_id, request)) => {
Some((request_id.0.clone(), request.method().to_string()))
}
LSPSMessage::LSPS1(LSPS1Message::Request(request_id, request)) => {
LSPSMessage::LSPS2(LSPS2Message::Request(request_id, request)) => {
Some((request_id.0.clone(), request.method().to_string()))
}
_ => None,
Expand Down Expand Up @@ -175,6 +179,7 @@ impl Serialize for LSPSMessage {
}
}
}
#[cfg(lsps1)]
LSPSMessage::LSPS1(LSPS1Message::Request(request_id, request)) => {
jsonrpc_object.serialize_field(JSONRPC_ID_FIELD_KEY, &request_id.0)?;
jsonrpc_object.serialize_field(JSONRPC_METHOD_FIELD_KEY, request.method())?;
Expand All @@ -191,6 +196,7 @@ impl Serialize for LSPSMessage {
}
}
}
#[cfg(lsps1)]
LSPSMessage::LSPS1(LSPS1Message::Response(request_id, response)) => {
jsonrpc_object.serialize_field(JSONRPC_ID_FIELD_KEY, &request_id.0)?;

Expand Down Expand Up @@ -319,6 +325,7 @@ impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> {
LSPS0Request::ListProtocols(ListProtocolsRequest {}),
)))
}
#[cfg(lsps1)]
LSPS1_GET_INFO_METHOD_NAME => {
let request = serde_json::from_value(params.unwrap_or(json!({})))
.map_err(de::Error::custom)?;
Expand All @@ -327,6 +334,7 @@ impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> {
LSPS1Request::GetInfo(request),
)))
}
#[cfg(lsps1)]
LSPS1_CREATE_ORDER_METHOD_NAME => {
let request = serde_json::from_value(params.unwrap_or(json!({})))
.map_err(de::Error::custom)?;
Expand All @@ -335,6 +343,7 @@ impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> {
LSPS1Request::CreateOrder(request),
)))
}
#[cfg(lsps1)]
LSPS1_GET_ORDER_METHOD_NAME => {
let request = serde_json::from_value(params.unwrap_or(json!({})))
.map_err(de::Error::custom)?;
Expand Down Expand Up @@ -403,6 +412,7 @@ impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> {
Err(de::Error::custom("Received invalid lsps2.get_versions response."))
}
}
#[cfg(lsps1)]
LSPS1_CREATE_ORDER_METHOD_NAME => {
if let Some(error) = error {
Ok(LSPSMessage::LSPS1(LSPS1Message::Response(
Expand All @@ -420,6 +430,7 @@ impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> {
Err(de::Error::custom("Received invalid JSON-RPC object: one of method, result, or error required"))
}
}
#[cfg(lsps1)]
LSPS1_GET_ORDER_METHOD_NAME => {
if let Some(error) = error {
Ok(LSPSMessage::LSPS1(LSPS1Message::Response(
Expand Down
4 changes: 2 additions & 2 deletions src/transport/protocol.rs → src/lsps0/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use lightning::util::logger::Level;
use std::ops::Deref;
use std::sync::{Arc, Mutex};

use crate::transport::message_handler::ProtocolMessageHandler;
use crate::transport::msgs::{
use crate::lsps0::message_handler::ProtocolMessageHandler;
use crate::lsps0::msgs::{
LSPS0Message, LSPS0Request, LSPS0Response, LSPSMessage, ListProtocolsRequest,
ListProtocolsResponse, RequestId, ResponseError,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ use lightning::util::errors::APIError;
use lightning::util::logger::{Level, Logger};

use crate::events::EventQueue;
use crate::transport::message_handler::{CRChannelConfig, ProtocolMessageHandler};
use crate::transport::msgs::{LSPSMessage, RequestId};
use crate::lsps0::message_handler::{CRChannelConfig, ProtocolMessageHandler};
use crate::lsps0::msgs::{LSPSMessage, RequestId};
use crate::utils;
use crate::{events::Event, transport::msgs::ResponseError};
use crate::{events::Event, lsps0::msgs::ResponseError};

use super::msgs::{
ChannelInfo, CreateOrderRequest, CreateOrderResponse, GetInfoRequest, GetInfoResponse,
Expand Down
2 changes: 1 addition & 1 deletion src/channel_request/event.rs → src/lsps1/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use bitcoin::secp256k1::PublicKey;

use super::msgs::{ChannelInfo, OptionsSupported, Order, OrderId, Payment};
use crate::transport::msgs::RequestId;
use crate::lsps0::msgs::RequestId;

/// An "Event" which you should probably take some action in response to.
#[derive(Clone, Debug, PartialEq, Eq)]
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion src/channel_request/msgs.rs → src/lsps1/msgs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::convert::TryFrom;

use serde::{Deserialize, Serialize};

use crate::transport::msgs::{LSPSMessage, RequestId, ResponseError};
use crate::lsps0::msgs::{LSPSMessage, RequestId, ResponseError};

pub(crate) const LSPS1_GET_INFO_METHOD_NAME: &str = "lsps1.get_info";
pub(crate) const LSPS1_CREATE_ORDER_METHOD_NAME: &str = "lsps1.create_order";
Expand Down
File renamed without changes.
Loading