From dfc71390b8ac8ece1fb6d944eb28bd49cd4389cc Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Wed, 8 Jan 2025 16:02:26 +0100 Subject: [PATCH 1/9] Introduce bLIP numbers in `lightning-liquidity` documentation Recently, LSPS0, 1, and 2 were upstreamed as bLIP-50, 51, and 52, respectively. Here, we 1. start linking to the bLIPs instead of the LSP spec repository, which is likely going to be deprecated. 2. start consistently citing the specs as `bLIP-5X / LSPSX` to avoid any confusions and to potentially initiate a process in which the LSP specs will be referred to by their bLIP number rather than their LSPS number (especially given that any upcoming specs by the LSP spec group will directly be drafted as bLIPs going forward). --- lightning-liquidity/README.md | 15 +++++++-------- lightning-liquidity/src/lib.rs | 23 ++++++++++++----------- lightning-liquidity/src/lsps0/client.rs | 14 +++++++------- lightning-liquidity/src/lsps0/event.rs | 4 ++-- lightning-liquidity/src/lsps0/mod.rs | 2 +- lightning-liquidity/src/lsps0/msgs.rs | 21 +++++++++++++-------- lightning-liquidity/src/lsps0/ser.rs | 4 +++- lightning-liquidity/src/lsps0/service.rs | 8 ++++---- lightning-liquidity/src/lsps1/client.rs | 6 +++--- lightning-liquidity/src/lsps1/event.rs | 12 ++++++------ lightning-liquidity/src/lsps1/mod.rs | 2 +- lightning-liquidity/src/lsps1/msgs.rs | 21 ++++++++++++--------- lightning-liquidity/src/lsps1/service.rs | 6 +++--- lightning-liquidity/src/lsps2/client.rs | 8 ++++---- lightning-liquidity/src/lsps2/event.rs | 8 ++++---- lightning-liquidity/src/lsps2/mod.rs | 2 +- lightning-liquidity/src/lsps2/msgs.rs | 8 ++++---- lightning-liquidity/src/lsps2/service.rs | 4 ++-- lightning-liquidity/src/lsps2/utils.rs | 4 ++-- 19 files changed, 91 insertions(+), 81 deletions(-) diff --git a/lightning-liquidity/README.md b/lightning-liquidity/README.md index dd74ba830c2..163f4151341 100644 --- a/lightning-liquidity/README.md +++ b/lightning-liquidity/README.md @@ -1,15 +1,15 @@ # lightning-liquidity -The goal of this crate is to provide types and primitives to integrate a spec-compliant LSP with an LDK-based node. To this end, this crate provides client-side as well as service-side logic to implement the [LSP specifications]. +The goal of this crate is to provide types and primitives to integrate a spec-compliant LSP with an LDK-based node. To this end, this crate provides client-side as well as service-side logic to implement the LSPS specifications. **Note**: Service-side support is currently considered "beta", i.e., not fully ready for production use. Currently the following specifications are supported: -- [LSPS0] defines the transport protocol with the LSP over which the other protocols communicate. -- [LSPS1] allows to order Lightning channels from an LSP. This is useful when the client needs +- [bLIP-50 / LSPS0] defines the transport protocol with the LSP over which the other protocols communicate. +- [bLIP-51 / LSPS1] allows to order Lightning channels from an LSP. This is useful when the client needs inbound Lightning liquidity for which they are willing and able to pay in bitcoin. -- [LSPS2] allows to generate a special invoice for which, when paid, an LSP +- [bLIP-52 / LSPS2] allows to generate a special invoice for which, when paid, an LSP will open a "just-in-time" channel. This is useful for the initial on-boarding of clients as the channel opening fees are deducted from the incoming payment, i.e., no funds are required client-side to initiate this @@ -19,7 +19,6 @@ To get started, you'll want to setup a `LiquidityManager` and configure it to be `LiquidityManager` uses an eventing system to notify the user about important updates to the protocol flow. To this end, you will need to handle events emitted via one of the event handling methods provided by `LiquidityManager`, e.g., `LiquidityManager::next_event`. -[LSP specifications]: https://github.com/BitcoinAndLightningLayerSpecs/lsp -[LSPS0]: https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS0 -[LSPS1]: https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS1 -[LSPS2]: https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS2 +[bLIP-50 / LSPS0]: https://github.com/lightning/blips/blob/master/blip-0050.md +[bLIP-51 / LSPS1]: https://github.com/lightning/blips/blob/master/blip-0051.md +[bLIP-52 / LSPS2]: https://github.com/lightning/blips/blob/master/blip-0052.md diff --git a/lightning-liquidity/src/lib.rs b/lightning-liquidity/src/lib.rs index 520c2009811..3930efa51a2 100644 --- a/lightning-liquidity/src/lib.rs +++ b/lightning-liquidity/src/lib.rs @@ -8,19 +8,21 @@ // licenses. #![crate_name = "lightning_liquidity"] -//! The goal of this crate is to provide types and primitives to integrate a spec-compliant LSP with an LDK-based node. To this end, this crate provides client-side as well as service-side logic to implement the [LSP specifications]. +//! The goal of this crate is to provide types and primitives to integrate a spec-compliant LSP +//! with an LDK-based node. To this end, this crate provides client-side as well as service-side +//! logic to implement the LSPS specifications. //! //! **Note**: Service-side support is currently considered "beta", i.e., not fully ready for //! production use. //! //! Currently the following specifications are supported: -//! - [LSPS0] defines the transport protocol with the LSP over which the other protocols communicate. -//! - [LSPS1] allows to order Lightning channels from an LSP. This is useful when the client needs +//! - [bLIP-50 / LSPS0] defines the transport protocol with the LSP over which the other protocols communicate. +//! - [bLIP-51 / LSPS1] defines a protocol for ordering Lightning channels from an LSP. This is useful when the client needs //! inbound Lightning liquidity for which they are willing and able to pay in bitcoin. -//! - [LSPS2] allows to generate a special invoice for which, when paid, an LSP will open a -//! "just-in-time" channel. This is useful for the initial on-boarding of clients as the channel -//! opening fees are deducted from the incoming payment, i.e., no funds are required client-side to -//! initiate this flow. +//! - [bLIP-52 / LSPS2] defines a protocol for generating a special invoice for which, when paid, +//! an LSP will open a "just-in-time" channel. This is useful for the initial on-boarding of +//! clients as the channel opening fees are deducted from the incoming payment, i.e., no funds are +//! required client-side to initiate this flow. //! //! To get started, you'll want to setup a [`LiquidityManager`] and configure it to be the //! [`CustomMessageHandler`] of your LDK node. You can then for example call @@ -32,10 +34,9 @@ //! protocol flow. To this end, you will need to handle events emitted via one of the event //! handling methods provided by [`LiquidityManager`], e.g., [`LiquidityManager::next_event`]. //! -//! [LSP specifications]: https://github.com/BitcoinAndLightningLayerSpecs/lsp -//! [LSPS0]: https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS0 -//! [LSPS1]: https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS1 -//! [LSPS2]: https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS2 +//! [bLIP-50 / LSPS0]: https://github.com/lightning/blips/blob/master/blip-0050.md +//! [bLIP-51 / LSPS1]: https://github.com/lightning/blips/blob/master/blip-0051.md +//! [bLIP-52 / LSPS2]: https://github.com/lightning/blips/blob/master/blip-0052.md //! [`CustomMessageHandler`]: lightning::ln::peer_handler::CustomMessageHandler //! [`LiquidityManager::next_event`]: crate::LiquidityManager::next_event #![deny(missing_docs)] diff --git a/lightning-liquidity/src/lsps0/client.rs b/lightning-liquidity/src/lsps0/client.rs index ab169bd7efb..651429f2825 100644 --- a/lightning-liquidity/src/lsps0/client.rs +++ b/lightning-liquidity/src/lsps0/client.rs @@ -1,7 +1,7 @@ -//! Contains the main LSPS0 client-side object, [`LSPS0ClientHandler`]. +//! Contains the main bLIP-50 / LSPS0 client-side object, [`LSPS0ClientHandler`]. //! -//! Please refer to the [LSPS0 -//! specifcation](https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS0) for more +//! Please refer to the [bLIP-50 / LSPS0 +//! specifcation](https://github.com/lightning/blips/blob/master/blip-0050.md) for more //! information. use crate::events::{Event, EventQueue}; @@ -22,7 +22,7 @@ use bitcoin::secp256k1::PublicKey; use core::ops::Deref; -/// A message handler capable of sending and handling LSPS0 messages. +/// A message handler capable of sending and handling bLIP-50 / LSPS0 messages. pub struct LSPS0ClientHandler where ES::Target: EntropySource, @@ -43,10 +43,10 @@ where Self { entropy_source, pending_messages, pending_events } } - /// Calls LSPS0's `list_protocols`. + /// Calls bLIP-50 / LSPS0's `list_protocols`. /// - /// Please refer to the [LSPS0 - /// specifcation](https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS0#lsps-specification-support-query) + /// Please refer to the [bLIP-50 / LSPS0 + /// specifcation](https://github.com/lightning/blips/blob/master/blip-0050.md#lsps-specification-support-query) /// for more information. pub fn list_protocols(&self, counterparty_node_id: &PublicKey) { let msg = LSPS0Message::Request( diff --git a/lightning-liquidity/src/lsps0/event.rs b/lightning-liquidity/src/lsps0/event.rs index 163114ddb54..33fe1a8fa7f 100644 --- a/lightning-liquidity/src/lsps0/event.rs +++ b/lightning-liquidity/src/lsps0/event.rs @@ -7,12 +7,12 @@ // You may not use this file except in accordance with one or both of these // licenses. -//! Contains LSPS0 event types +//! Contains bLIP-50 / LSPS0 event types. use crate::prelude::Vec; use bitcoin::secp256k1::PublicKey; -/// An event which an LSPS0 client may want to take some action in response to. +/// An event which an bLIP-50 / LSPS0 client may want to take some action in response to. #[derive(Clone, Debug, PartialEq, Eq)] pub enum LSPS0ClientEvent { /// Information from the LSP about the protocols they support. diff --git a/lightning-liquidity/src/lsps0/mod.rs b/lightning-liquidity/src/lsps0/mod.rs index 4211ef5c2d6..0055112f974 100644 --- a/lightning-liquidity/src/lsps0/mod.rs +++ b/lightning-liquidity/src/lsps0/mod.rs @@ -7,7 +7,7 @@ // You may not use this file except in accordance with one or both of these // licenses. -//! Types and primitives that implement the LSPS0: Transport Layer specification. +//! Types and primitives that implement the bLIP-50 / LSPS0: Transport Layer specification. pub mod client; pub mod event; diff --git a/lightning-liquidity/src/lsps0/msgs.rs b/lightning-liquidity/src/lsps0/msgs.rs index 631cc9206c5..c3cb4fb3725 100644 --- a/lightning-liquidity/src/lsps0/msgs.rs +++ b/lightning-liquidity/src/lsps0/msgs.rs @@ -11,14 +11,16 @@ pub(crate) const LSPS0_LISTPROTOCOLS_METHOD_NAME: &str = "lsps0.list_protocols"; /// A `list_protocols` request. /// -/// Please refer to the [LSPS0 specification](https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS0#lsps-specification-support-query) +/// Please refer to the [bLIP-50 / LSPS0 +/// specification](https://github.com/lightning/blips/blob/master/blip-0050.md#lsps-specification-support-query) /// for more information. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize, Default)] pub struct ListProtocolsRequest {} /// A response to a `list_protocols` request. /// -/// Please refer to the [LSPS0 specification](https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS0#lsps-specification-support-query) +/// Please refer to the [bLIP-50 / LSPS0 +/// specification](https://github.com/lightning/blips/blob/master/blip-0050.md#lsps-specification-support-query) /// for more information. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct ListProtocolsResponse { @@ -26,9 +28,10 @@ pub struct ListProtocolsResponse { pub protocols: Vec, } -/// An LSPS0 protocol request. +/// An bLIP-50 / LSPS0 protocol request. /// -/// Please refer to the [LSPS0 specification](https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS0) +/// Please refer to the [bLIP-50 / LSPS0 +/// specification](https://github.com/lightning/blips/blob/master/blip-0050.md#lsps-specification-support-query) /// for more information. #[derive(Clone, Debug, PartialEq, Eq)] pub enum LSPS0Request { @@ -45,9 +48,10 @@ impl LSPS0Request { } } -/// An LSPS0 protocol request. +/// An bLIP-50 / LSPS0 protocol request. /// -/// Please refer to the [LSPS0 specification](https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS0) +/// Please refer to the [bLIP-50 / LSPS0 +/// specification](https://github.com/lightning/blips/blob/master/blip-0050.md#lsps-specification-support-query) /// for more information. #[derive(Clone, Debug, PartialEq, Eq)] pub enum LSPS0Response { @@ -57,9 +61,10 @@ pub enum LSPS0Response { ListProtocolsError(ResponseError), } -/// An LSPS0 protocol message. +/// An bLIP-50 / LSPS0 protocol message. /// -/// Please refer to the [LSPS0 specification](https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS0) +/// Please refer to the [bLIP-50 / LSPS0 +/// specification](https://github.com/lightning/blips/blob/master/blip-0050.md#lsps-specification-support-query) /// for more information. #[derive(Clone, Debug, PartialEq, Eq)] pub enum LSPS0Message { diff --git a/lightning-liquidity/src/lsps0/ser.rs b/lightning-liquidity/src/lsps0/ser.rs index afac232966a..bb57734ae60 100644 --- a/lightning-liquidity/src/lsps0/ser.rs +++ b/lightning-liquidity/src/lsps0/ser.rs @@ -1,6 +1,8 @@ //! Contains basic data types that allow for the (de-)seralization of LSPS messages in the JSON-RPC 2.0 format. //! -//! Please refer to the [LSPS0 specification](https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS0) for more information. +//! Please refer to the [bLIP-50 / LSPS0 +//! specification](https://github.com/lightning/blips/blob/master/blip-0050.md) for more +//! information. use crate::lsps0::msgs::{ LSPS0Message, LSPS0Request, LSPS0Response, ListProtocolsRequest, diff --git a/lightning-liquidity/src/lsps0/service.rs b/lightning-liquidity/src/lsps0/service.rs index bc52fa11dd9..efd1669f5ac 100644 --- a/lightning-liquidity/src/lsps0/service.rs +++ b/lightning-liquidity/src/lsps0/service.rs @@ -7,10 +7,10 @@ // You may not use this file except in accordance with one or both of these // licenses. -//! Contains the main LSPS0 server-side object, [`LSPS0ServiceHandler`]. +//! Contains the main bLIP-50 / LSPS0 server-side object, [`LSPS0ServiceHandler`]. //! -//! Please refer to the [LSPS0 -//! specifcation](https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS0) for more +//! Please refer to the [bLIP-50 / LSPS0 +//! specifcation](https://github.com/lightning/blips/blob/master/blip-0050.md) for more //! information. use crate::lsps0::msgs::{LSPS0Message, LSPS0Request, LSPS0Response, ListProtocolsResponse}; @@ -24,7 +24,7 @@ use lightning::util::logger::Level; use bitcoin::secp256k1::PublicKey; -/// The main server-side object allowing to send and receive LSPS0 messages. +/// The main server-side object allowing to send and receive bLIP-50 / LSPS0 messages. pub struct LSPS0ServiceHandler { pending_messages: Arc, protocols: Vec, diff --git a/lightning-liquidity/src/lsps1/client.rs b/lightning-liquidity/src/lsps1/client.rs index 75709d512a3..90704e08532 100644 --- a/lightning-liquidity/src/lsps1/client.rs +++ b/lightning-liquidity/src/lsps1/client.rs @@ -7,7 +7,7 @@ // You may not use this file except in accordance with one or both of these // licenses. -//! Contains the main LSPS1 client object, [`LSPS1ClientHandler`]. +//! Contains the main bLIP-51 / LSPS1 client object, [`LSPS1ClientHandler`]. use super::event::LSPS1ClientEvent; use super::msgs::{ @@ -30,7 +30,7 @@ use bitcoin::Address; use core::ops::Deref; -/// Client-side configuration options for LSPS1 channel requests. +/// Client-side configuration options for bLIP-51 / LSPS1 channel requests. #[derive(Clone, Debug)] pub struct LSPS1ClientConfig { /// The maximally allowed channel fees. @@ -44,7 +44,7 @@ struct PeerState { pending_get_order_requests: HashSet, } -/// The main object allowing to send and receive LSPS1 messages. +/// The main object allowing to send and receive bLIP-51 / LSPS1 messages. pub struct LSPS1ClientHandler where ES::Target: EntropySource, diff --git a/lightning-liquidity/src/lsps1/event.rs b/lightning-liquidity/src/lsps1/event.rs index ff4961d49b8..3bdeca477fe 100644 --- a/lightning-liquidity/src/lsps1/event.rs +++ b/lightning-liquidity/src/lsps1/event.rs @@ -7,7 +7,7 @@ // You may not use this file except in accordance with one or both of these // licenses. -//! Contains LSPS1 event types +//! Contains bLIP-51 / LSPS1 event types use super::msgs::OrderId; use super::msgs::{ChannelInfo, LSPS1Options, OrderParameters, PaymentInfo}; @@ -16,7 +16,7 @@ use crate::lsps0::ser::{RequestId, ResponseError}; use bitcoin::secp256k1::PublicKey; -/// An event which an LSPS1 client should take some action in response to. +/// An event which an bLIP-51 / LSPS1 client should take some action in response to. #[derive(Clone, Debug, PartialEq, Eq)] pub enum LSPS1ClientEvent { /// A request previously issued via [`LSPS1ClientHandler::request_supported_options`] @@ -28,7 +28,7 @@ pub enum LSPS1ClientEvent { /// [`LSPS1ClientHandler::request_supported_options`]: crate::lsps1::client::LSPS1ClientHandler::request_supported_options /// [`LSPS1ClientHandler::create_order`]: crate::lsps1::client::LSPS1ClientHandler::create_order SupportedOptionsReady { - /// The identifier of the issued LSPS1 `get_info` request, as returned by + /// The identifier of the issued bLIP-51 / LSPS1 `get_info` request, as returned by /// [`LSPS1ClientHandler::request_supported_options`] /// /// This can be used to track which request this event corresponds to. @@ -45,7 +45,7 @@ pub enum LSPS1ClientEvent { /// /// [`LSPS1ClientHandler::request_supported_options`]: crate::lsps1::client::LSPS1ClientHandler::request_supported_options SupportedOptionsRequestFailed { - /// The identifier of the issued LSPS1 `get_info` request, as returned by + /// The identifier of the issued bLIP-51 / LSPS1 `get_info` request, as returned by /// [`LSPS1ClientHandler::request_supported_options`] /// /// This can be used to track which request this event corresponds to. @@ -68,7 +68,7 @@ pub enum LSPS1ClientEvent { /// /// [`LSPS1ClientHandler::check_order_status`]: crate::lsps1::client::LSPS1ClientHandler::check_order_status OrderCreated { - /// The identifier of the issued LSPS1 `create_order` request, as returned by + /// The identifier of the issued bLIP-51 / LSPS1 `create_order` request, as returned by /// [`LSPS1ClientHandler::create_order`] /// /// This can be used to track which request this event corresponds to. @@ -92,7 +92,7 @@ pub enum LSPS1ClientEvent { /// /// [`LSPS1ClientHandler::check_order_status`]: crate::lsps1::client::LSPS1ClientHandler::check_order_status OrderStatus { - /// The identifier of the issued LSPS1 `get_order` request, as returned by + /// The identifier of the issued bLIP-51 / LSPS1 `get_order` request, as returned by /// [`LSPS1ClientHandler::check_order_status`] /// /// This can be used to track which request this event corresponds to. diff --git a/lightning-liquidity/src/lsps1/mod.rs b/lightning-liquidity/src/lsps1/mod.rs index d04a26b29c1..b068b186610 100644 --- a/lightning-liquidity/src/lsps1/mod.rs +++ b/lightning-liquidity/src/lsps1/mod.rs @@ -7,7 +7,7 @@ // You may not use this file except in accordance with one or both of these // licenses. -//! Types and primitives that implement the LSPS1: Channel Request specification. +//! Types and primitives that implement the bLIP-51 / LSPS1: Channel Request specification. pub mod client; pub mod event; diff --git a/lightning-liquidity/src/lsps1/msgs.rs b/lightning-liquidity/src/lsps1/msgs.rs index 42f10c04772..94e030400a5 100644 --- a/lightning-liquidity/src/lsps1/msgs.rs +++ b/lightning-liquidity/src/lsps1/msgs.rs @@ -1,4 +1,4 @@ -//! Message, request, and other primitive types used to implement LSPS1. +//! Message, request, and other primitive types used to implement bLIP-51 / LSPS1. use crate::lsps0::ser::{ string_amount, u32_fee_rate, unchecked_address, unchecked_address_option, LSPSMessage, @@ -31,8 +31,9 @@ pub struct OrderId(pub String); /// A request made to an LSP to retrieve the supported options. /// -/// Please refer to the [LSPS1 specification](https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS1#1-lsps1info) -/// for more information. +/// Please refer to the [bLIP-51 / LSPS1 +/// specification](https://github.com/lightning/blips/blob/master/blip-0051.md#1-lsps1get_info) for +/// more information. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize, Default)] #[serde(default)] pub struct GetInfoRequest {} @@ -78,7 +79,8 @@ pub struct GetInfoResponse { /// A request made to an LSP to create an order. /// -/// Please refer to the [LSPS1 specification](https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS1#2-lsps1create_order) +/// Please refer to the [bLIP-51 / LSPS1 +/// specification](https://github.com/lightning/blips/blob/master/blip-0051.md#2-lsps1create_order) /// for more information. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct CreateOrderRequest { @@ -92,7 +94,7 @@ pub struct CreateOrderRequest { pub refund_onchain_address: Option
, } -/// An object representing an LSPS1 channel order. +/// An object representing an bLIP-51 / LSPS1 channel order. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct OrderParameters { /// Indicates how many satoshi the LSP will provide on their side. @@ -244,7 +246,8 @@ pub struct ChannelInfo { /// A request made to an LSP to retrieve information about an previously made order. /// -/// Please refer to the [LSPS1 specification](https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS1#21-lsps1get_order) +/// Please refer to the [bLIP-51 / LSPS1 +/// specification](https://github.com/lightning/blips/blob/master/blip-0051.md#21-lsps1get_order) /// for more information. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct GetOrderRequest { @@ -252,7 +255,7 @@ pub struct GetOrderRequest { pub order_id: OrderId, } -/// An enum that captures all the valid JSON-RPC requests in the LSPS1 protocol. +/// An enum that captures all the valid JSON-RPC requests in the bLIP-51 / LSPS1 protocol. #[derive(Clone, Debug, PartialEq, Eq)] pub enum LSPS1Request { /// A request to learn about the options supported by the LSP. @@ -263,7 +266,7 @@ pub enum LSPS1Request { GetOrder(GetOrderRequest), } -/// An enum that captures all the valid JSON-RPC responses in the LSPS1 protocol. +/// An enum that captures all the valid JSON-RPC responses in the bLIP-51 / LSPS1 protocol. #[derive(Clone, Debug, PartialEq, Eq)] pub enum LSPS1Response { /// A successful response to a [`GetInfoRequest`]. @@ -280,7 +283,7 @@ pub enum LSPS1Response { GetOrderError(ResponseError), } -/// An enum that captures all valid JSON-RPC messages in the LSPS1 protocol. +/// An enum that captures all valid JSON-RPC messages in the bLIP-51 / LSPS1 protocol. #[derive(Clone, Debug, PartialEq, Eq)] pub enum LSPS1Message { /// An LSPS1 JSON-RPC request. diff --git a/lightning-liquidity/src/lsps1/service.rs b/lightning-liquidity/src/lsps1/service.rs index 6520adcf69b..f4022d01505 100644 --- a/lightning-liquidity/src/lsps1/service.rs +++ b/lightning-liquidity/src/lsps1/service.rs @@ -7,7 +7,7 @@ // You may not use this file except in accordance with one or both of these // licenses. -//! Contains the main LSPS1 server object, [`LSPS1ServiceHandler`]. +//! Contains the main bLIP-51 / LSPS1 server object, [`LSPS1ServiceHandler`]. use super::event::LSPS1ServiceEvent; use super::msgs::{ @@ -36,7 +36,7 @@ use bitcoin::secp256k1::PublicKey; use chrono::Utc; use core::ops::Deref; -/// Server-side configuration options for LSPS1 channel requests. +/// Server-side configuration options for bLIP-51 / LSPS1 channel requests. #[derive(Clone, Debug)] pub struct LSPS1ServiceConfig { /// A token to be send with each channel request. @@ -125,7 +125,7 @@ impl PeerState { } } -/// The main object allowing to send and receive LSPS1 messages. +/// The main object allowing to send and receive bLIP-51 / LSPS1 messages. pub struct LSPS1ServiceHandler where ES::Target: EntropySource, diff --git a/lightning-liquidity/src/lsps2/client.rs b/lightning-liquidity/src/lsps2/client.rs index 10707bc8c5a..0f9db62e79c 100644 --- a/lightning-liquidity/src/lsps2/client.rs +++ b/lightning-liquidity/src/lsps2/client.rs @@ -6,7 +6,7 @@ // , at your option. You may not use this file except in accordance with one or both of these // licenses. -//! Contains the main LSPS2 client object, [`LSPS2ClientHandler`]. +//! Contains the main bLIP-52 / LSPS2 client object, [`LSPS2ClientHandler`]. use crate::events::{Event, EventQueue}; use crate::lsps0::ser::{ProtocolMessageHandler, RequestId, ResponseError}; @@ -57,13 +57,13 @@ impl PeerState { } } -/// The main object allowing to send and receive LSPS2 messages. +/// The main object allowing to send and receive bLIP-52 / LSPS2 messages. /// /// Note that currently only the 'client-trusts-LSP' trust model is supported, i.e., we don't /// provide any additional API guidance to allow withholding the preimage until the channel is -/// opened. Please refer to the [`LSPS2 specification`] for more information. +/// opened. Please refer to the [`bLIP-52 / LSPS2 specification`] for more information. /// -/// [`LSPS2 specification`]: https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS2#trust-models +/// [`bLIP-52 / LSPS2 specification`]: https://github.com/lightning/blips/blob/master/blip-0052.md#trust-models pub struct LSPS2ClientHandler where ES::Target: EntropySource, diff --git a/lightning-liquidity/src/lsps2/event.rs b/lightning-liquidity/src/lsps2/event.rs index 1e28b259757..0334be24b3c 100644 --- a/lightning-liquidity/src/lsps2/event.rs +++ b/lightning-liquidity/src/lsps2/event.rs @@ -7,7 +7,7 @@ // You may not use this file except in accordance with one or both of these // licenses. -//! Contains LSPS2 event types +//! Contains bLIP-52 / LSPS2 event types use super::msgs::OpeningFeeParams; use crate::lsps0::ser::RequestId; @@ -25,7 +25,7 @@ pub enum LSPS2ClientEvent { /// /// [`LSPS2ClientHandler::select_opening_params`]: crate::lsps2::client::LSPS2ClientHandler::select_opening_params OpeningParametersReady { - /// The identifier of the issued LSPS2 `get_info` request, as returned by + /// The identifier of the issued bLIP-52 / LSPS2 `get_info` request, as returned by /// [`LSPS2ClientHandler::request_opening_params`] /// /// This can be used to track which request this event corresponds to. @@ -44,7 +44,7 @@ pub enum LSPS2ClientEvent { /// When the invoice is paid, the LSP will open a channel with the previously agreed upon /// parameters to you. InvoiceParametersReady { - /// The identifier of the issued LSPS2 `buy` request, as returned by + /// The identifier of the issued bLIP-52 / LSPS2 `buy` request, as returned by /// [`LSPS2ClientHandler::select_opening_params`]. /// /// This can be used to track which request this event corresponds to. @@ -62,7 +62,7 @@ pub enum LSPS2ClientEvent { }, } -/// An event which an LSPS2 server should take some action in response to. +/// An event which an bLIP-52 / LSPS2 server should take some action in response to. #[derive(Clone, Debug, PartialEq, Eq)] pub enum LSPS2ServiceEvent { /// A request from a client for information about JIT Channel parameters. diff --git a/lightning-liquidity/src/lsps2/mod.rs b/lightning-liquidity/src/lsps2/mod.rs index 0a29ac636d6..1d5fb76d3b4 100644 --- a/lightning-liquidity/src/lsps2/mod.rs +++ b/lightning-liquidity/src/lsps2/mod.rs @@ -7,7 +7,7 @@ // You may not use this file except in accordance with one or both of these // licenses. -//! Implementation of LSPS2: JIT Channel Negotiation specification. +//! Implementation of bLIP-52 / LSPS2: JIT Channel Negotiation specification. pub mod client; pub mod event; diff --git a/lightning-liquidity/src/lsps2/msgs.rs b/lightning-liquidity/src/lsps2/msgs.rs index f7c0df9db06..8d6378d24fe 100644 --- a/lightning-liquidity/src/lsps2/msgs.rs +++ b/lightning-liquidity/src/lsps2/msgs.rs @@ -1,4 +1,4 @@ -//! Message, request, and other primitive types used to implement LSPS2. +//! Message, request, and other primitive types used to implement bLIP-52 / LSPS2. use core::convert::TryFrom; @@ -161,7 +161,7 @@ pub struct BuyResponse { } #[derive(Clone, Debug, PartialEq, Eq)] -/// An enum that captures all the valid JSON-RPC requests in the LSPS2 protocol. +/// An enum that captures all the valid JSON-RPC requests in the bLIP-52 / LSPS2 protocol. pub enum LSPS2Request { /// A request to learn an LSP's channel fees and parameters. GetInfo(GetInfoRequest), @@ -170,7 +170,7 @@ pub enum LSPS2Request { } #[derive(Clone, Debug, PartialEq, Eq)] -/// An enum that captures all the valid JSON-RPC responses in the LSPS2 protocol. +/// An enum that captures all the valid JSON-RPC responses in the bLIP-52 / LSPS2 protocol. pub enum LSPS2Response { /// A successful response to a [`LSPS2Request::GetInfo`] request. GetInfo(GetInfoResponse), @@ -183,7 +183,7 @@ pub enum LSPS2Response { } #[derive(Clone, Debug, PartialEq, Eq)] -/// An enum that captures all valid JSON-RPC messages in the LSPS2 protocol. +/// An enum that captures all valid JSON-RPC messages in the bLIP-52 / LSPS2 protocol. pub enum LSPS2Message { /// An LSPS2 JSON-RPC request. Request(RequestId, LSPS2Request), diff --git a/lightning-liquidity/src/lsps2/service.rs b/lightning-liquidity/src/lsps2/service.rs index d4682a9b346..95a94bc422e 100644 --- a/lightning-liquidity/src/lsps2/service.rs +++ b/lightning-liquidity/src/lsps2/service.rs @@ -7,7 +7,7 @@ // You may not use this file except in accordance with one or both of these // licenses. -//! Contains the main LSPS2 server-side object, [`LSPS2ServiceHandler`]. +//! Contains the main bLIP-52 / LSPS2 server-side object, [`LSPS2ServiceHandler`]. use crate::events::{Event, EventQueue}; use crate::lsps0::ser::{ @@ -549,7 +549,7 @@ macro_rules! get_or_insert_peer_state_entry { }} } -/// The main object allowing to send and receive LSPS2 messages. +/// The main object allowing to send and receive bLIP-52 / LSPS2 messages. pub struct LSPS2ServiceHandler where CM::Target: AChannelManager, diff --git a/lightning-liquidity/src/lsps2/utils.rs b/lightning-liquidity/src/lsps2/utils.rs index 8a085b76c22..91db3449c60 100644 --- a/lightning-liquidity/src/lsps2/utils.rs +++ b/lightning-liquidity/src/lsps2/utils.rs @@ -1,4 +1,4 @@ -//! Utilities for implementing the LSPS2 standard. +//! Utilities for implementing the bLIP-52 / LSPS2 standard. use crate::lsps2::msgs::OpeningFeeParams; use crate::utils; @@ -57,7 +57,7 @@ pub fn is_expired_opening_fee_params(fee_params: &OpeningFeeParams) -> bool { /// /// Returns [`Option::None`] when the computation overflows. /// -/// See the [`specification`](https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS2#computing-the-opening_fee) for more details. +/// See the [`specification`](https://github.com/lightning/blips/blob/master/blip-0052.md#computing-the-opening_fee) for more details. pub fn compute_opening_fee( payment_size_msat: u64, opening_fee_min_fee_msat: u64, opening_fee_proportional: u64, ) -> Option { From 962da67d8ef3d991c4cb4255e5aa63dace24182d Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Fri, 31 Jan 2025 10:32:59 +0100 Subject: [PATCH 2/9] Fix `lsps1_service` builds As we're not testing with `cfg(lsps1_service)`, the builds broke during previous refactoring. This isn't bad as we're looking to completely overhaul / rewrite LSPS1 service soon, but until then we fix this pre-existing breakage to make sure following changes make sense. --- ci/ci-tests.sh | 2 ++ lightning-liquidity/src/lsps1/service.rs | 27 +++++++++++++++++++++--- lightning-liquidity/src/manager.rs | 2 +- 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/ci/ci-tests.sh b/ci/ci-tests.sh index f4987569fda..198e1c4b13b 100755 --- a/ci/ci-tests.sh +++ b/ci/ci-tests.sh @@ -132,3 +132,5 @@ RUSTFLAGS="--cfg=taproot" cargo test --verbose --color always -p lightning RUSTFLAGS="--cfg=splicing" cargo test --verbose --color always -p lightning [ "$CI_MINIMIZE_DISK_USAGE" != "" ] && cargo clean RUSTFLAGS="--cfg=async_payments" cargo test --verbose --color always -p lightning +[ "$CI_MINIMIZE_DISK_USAGE" != "" ] && cargo clean +RUSTFLAGS="--cfg=lsps1_service" cargo test --verbose --color always -p lightning-liquidity diff --git a/lightning-liquidity/src/lsps1/service.rs b/lightning-liquidity/src/lsps1/service.rs index f4022d01505..9cd2e0a1f2a 100644 --- a/lightning-liquidity/src/lsps1/service.rs +++ b/lightning-liquidity/src/lsps1/service.rs @@ -15,12 +15,11 @@ use super::msgs::{ LSPS1Message, LSPS1Options, LSPS1Request, LSPS1Response, OrderId, OrderParameters, OrderState, PaymentInfo, LSPS1_CREATE_ORDER_REQUEST_ORDER_MISMATCH_ERROR_CODE, }; -use super::utils::is_valid; use crate::message_queue::MessageQueue; use crate::events::{Event, EventQueue}; use crate::lsps0::ser::{ProtocolMessageHandler, RequestId, ResponseError}; -use crate::prelude::{new_hash_map, HashMap, String, ToString}; +use crate::prelude::{new_hash_map, HashMap, String}; use crate::sync::{Arc, Mutex, RwLock}; use crate::utils; @@ -306,7 +305,7 @@ where &self, request_id: RequestId, counterparty_node_id: &PublicKey, params: GetOrderRequest, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.read().unwrap(); - match outer_state_lock.get(&counterparty_node_id) { + match outer_state_lock.get(counterparty_node_id) { Some(inner_state_lock) => { let mut peer_state_lock = inner_state_lock.lock().unwrap(); @@ -457,3 +456,25 @@ where } } } + +fn check_range(min: u64, max: u64, value: u64) -> bool { + (value >= min) && (value <= max) +} + +fn is_valid(order: &OrderParameters, options: &LSPS1Options) -> bool { + let bool = check_range( + options.min_initial_client_balance_sat, + options.max_initial_client_balance_sat, + order.client_balance_sat, + ) && check_range( + options.min_initial_lsp_balance_sat, + options.max_initial_lsp_balance_sat, + order.lsp_balance_sat, + ) && check_range( + 1, + options.max_channel_expiry_blocks.into(), + order.channel_expiry_blocks.into(), + ); + + bool +} diff --git a/lightning-liquidity/src/manager.rs b/lightning-liquidity/src/manager.rs index a4c13033370..c8bf1e05a72 100644 --- a/lightning-liquidity/src/manager.rs +++ b/lightning-liquidity/src/manager.rs @@ -173,7 +173,7 @@ where { #[cfg(lsps1_service)] let lsps1_service_handler = service_config.as_ref().and_then(|config| { if let Some(number) = - as ProtocolMessageHandler>::PROTOCOL_NUMBER + as ProtocolMessageHandler>::PROTOCOL_NUMBER { supported_protocols.push(number); } From 5e0c5f0821bb36ab031cbc2cbb998bdb09e6fdd8 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Fri, 31 Jan 2025 10:22:24 +0100 Subject: [PATCH 3/9] Rename `Event` to `LiquidityEvent` In order to avoid naming collisions with LDK's `Event` type, we rename `lightning-liquidity`'s `Event` to `LiquidityEvent`. To minimize furhter churn on the upcoming renaming changes, we also `impl From X for LiquidityEvent` for the protocol-specific event variants, which also allows us to reduce some boilerplate while enqueuing. --- lightning-liquidity/src/events.rs | 57 ++++++++++++++---- lightning-liquidity/src/lsps0/client.rs | 12 ++-- lightning-liquidity/src/lsps1/client.rs | 58 ++++++++----------- lightning-liquidity/src/lsps1/service.rs | 30 +++++----- lightning-liquidity/src/lsps2/client.rs | 30 +++++----- lightning-liquidity/src/lsps2/service.rs | 14 ++--- lightning-liquidity/src/manager.rs | 12 ++-- .../tests/lsps2_integration_tests.rs | 10 ++-- 8 files changed, 119 insertions(+), 104 deletions(-) diff --git a/lightning-liquidity/src/events.rs b/lightning-liquidity/src/events.rs index 3db772deec8..a2c18417f9c 100644 --- a/lightning-liquidity/src/events.rs +++ b/lightning-liquidity/src/events.rs @@ -28,7 +28,7 @@ use core::task::{Poll, Waker}; pub const MAX_EVENT_QUEUE_SIZE: usize = 1000; pub(crate) struct EventQueue { - queue: Arc>>, + queue: Arc>>, waker: Arc>>, #[cfg(feature = "std")] condvar: crate::sync::Condvar, @@ -47,11 +47,11 @@ impl EventQueue { Self { queue, waker } } - pub fn enqueue(&self, event: Event) { + pub fn enqueue>(&self, event: E) { { let mut queue = self.queue.lock().unwrap(); if queue.len() < MAX_EVENT_QUEUE_SIZE { - queue.push_back(event); + queue.push_back(event.into()); } else { return; } @@ -64,19 +64,21 @@ impl EventQueue { self.condvar.notify_one(); } - pub fn next_event(&self) -> Option { + pub fn next_event(&self) -> Option { self.queue.lock().unwrap().pop_front() } - pub async fn next_event_async(&self) -> Event { + pub async fn next_event_async(&self) -> LiquidityEvent { EventFuture { event_queue: Arc::clone(&self.queue), waker: Arc::clone(&self.waker) }.await } #[cfg(feature = "std")] - pub fn wait_next_event(&self) -> Event { + pub fn wait_next_event(&self) -> LiquidityEvent { let mut queue = self .condvar - .wait_while(self.queue.lock().unwrap(), |queue: &mut VecDeque| queue.is_empty()) + .wait_while(self.queue.lock().unwrap(), |queue: &mut VecDeque| { + queue.is_empty() + }) .unwrap(); let event = queue.pop_front().expect("non-empty queue"); @@ -95,14 +97,14 @@ impl EventQueue { event } - pub fn get_and_clear_pending_events(&self) -> Vec { + pub fn get_and_clear_pending_events(&self) -> Vec { self.queue.lock().unwrap().split_off(0).into() } } /// An event which you should probably take some action in response to. #[derive(Debug, Clone, PartialEq, Eq)] -pub enum Event { +pub enum LiquidityEvent { /// An LSPS0 client event. LSPS0Client(lsps0::event::LSPS0ClientEvent), /// An LSPS1 (Channel Request) client event. @@ -116,13 +118,44 @@ pub enum Event { LSPS2Service(lsps2::event::LSPS2ServiceEvent), } +impl From for LiquidityEvent { + fn from(event: lsps0::event::LSPS0ClientEvent) -> Self { + Self::LSPS0Client(event) + } +} + +impl From for LiquidityEvent { + fn from(event: lsps1::event::LSPS1ClientEvent) -> Self { + Self::LSPS1Client(event) + } +} + +#[cfg(lsps1_service)] +impl From for LiquidityEvent { + fn from(event: lsps1::event::LSPS1ServiceEvent) -> Self { + Self::LSPS1Service(event) + } +} + +impl From for LiquidityEvent { + fn from(event: lsps2::event::LSPS2ClientEvent) -> Self { + Self::LSPS2Client(event) + } +} + +impl From for LiquidityEvent { + fn from(event: lsps2::event::LSPS2ServiceEvent) -> Self { + Self::LSPS2Service(event) + } +} + struct EventFuture { - event_queue: Arc>>, + event_queue: Arc>>, waker: Arc>>, } impl Future for EventFuture { - type Output = Event; + type Output = LiquidityEvent; fn poll( self: core::pin::Pin<&mut Self>, cx: &mut core::task::Context<'_>, @@ -154,7 +187,7 @@ mod tests { let secp_ctx = Secp256k1::new(); let counterparty_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()); - let expected_event = Event::LSPS0Client(LSPS0ClientEvent::ListProtocolsResponse { + let expected_event = LiquidityEvent::LSPS0Client(LSPS0ClientEvent::ListProtocolsResponse { counterparty_node_id, protocols: Vec::new(), }); diff --git a/lightning-liquidity/src/lsps0/client.rs b/lightning-liquidity/src/lsps0/client.rs index 651429f2825..84a11b5af6a 100644 --- a/lightning-liquidity/src/lsps0/client.rs +++ b/lightning-liquidity/src/lsps0/client.rs @@ -4,7 +4,7 @@ //! specifcation](https://github.com/lightning/blips/blob/master/blip-0050.md) for more //! information. -use crate::events::{Event, EventQueue}; +use crate::events::EventQueue; use crate::lsps0::event::LSPS0ClientEvent; use crate::lsps0::msgs::{ LSPS0Message, LSPS0Request, LSPS0Response, ListProtocolsRequest, ListProtocolsResponse, @@ -62,12 +62,10 @@ where ) -> Result<(), LightningError> { match response { LSPS0Response::ListProtocols(ListProtocolsResponse { protocols }) => { - self.pending_events.enqueue(Event::LSPS0Client( - LSPS0ClientEvent::ListProtocolsResponse { - counterparty_node_id: *counterparty_node_id, - protocols, - }, - )); + self.pending_events.enqueue(LSPS0ClientEvent::ListProtocolsResponse { + counterparty_node_id: *counterparty_node_id, + protocols, + }); Ok(()) }, LSPS0Response::ListProtocolsError(ResponseError { code, message, data, .. }) => { diff --git a/lightning-liquidity/src/lsps1/client.rs b/lightning-liquidity/src/lsps1/client.rs index 90704e08532..2658cb9fcad 100644 --- a/lightning-liquidity/src/lsps1/client.rs +++ b/lightning-liquidity/src/lsps1/client.rs @@ -16,7 +16,7 @@ use super::msgs::{ }; use crate::message_queue::MessageQueue; -use crate::events::{Event, EventQueue}; +use crate::events::EventQueue; use crate::lsps0::ser::{ProtocolMessageHandler, RequestId, ResponseError}; use crate::prelude::{new_hash_map, HashMap, HashSet}; use crate::sync::{Arc, Mutex, RwLock}; @@ -119,13 +119,11 @@ where }); } - self.pending_events.enqueue(Event::LSPS1Client( - LSPS1ClientEvent::SupportedOptionsReady { - counterparty_node_id: *counterparty_node_id, - supported_options: result.options, - request_id, - }, - )); + self.pending_events.enqueue(LSPS1ClientEvent::SupportedOptionsReady { + counterparty_node_id: *counterparty_node_id, + supported_options: result.options, + request_id, + }); Ok(()) }, None => Err(LightningError { @@ -156,13 +154,11 @@ where }); } - self.pending_events.enqueue(Event::LSPS1Client( - LSPS1ClientEvent::SupportedOptionsRequestFailed { - request_id: request_id.clone(), - counterparty_node_id: *counterparty_node_id, - error: error.clone(), - }, - )); + self.pending_events.enqueue(LSPS1ClientEvent::SupportedOptionsRequestFailed { + request_id: request_id.clone(), + counterparty_node_id: *counterparty_node_id, + error: error.clone(), + }); Err(LightningError { err: format!( @@ -233,14 +229,14 @@ where }); } - self.pending_events.enqueue(Event::LSPS1Client(LSPS1ClientEvent::OrderCreated { + self.pending_events.enqueue(LSPS1ClientEvent::OrderCreated { request_id, counterparty_node_id: *counterparty_node_id, order_id: response.order_id, order: response.order, payment: response.payment, channel: response.channel, - })); + }); }, None => { return Err(LightningError { @@ -274,13 +270,11 @@ where }); } - self.pending_events.enqueue(Event::LSPS1Client( - LSPS1ClientEvent::OrderRequestFailed { - request_id: request_id.clone(), - counterparty_node_id: *counterparty_node_id, - error: error.clone(), - }, - )); + self.pending_events.enqueue(LSPS1ClientEvent::OrderRequestFailed { + request_id: request_id.clone(), + counterparty_node_id: *counterparty_node_id, + error: error.clone(), + }); Err(LightningError { err: format!( @@ -352,14 +346,14 @@ where }); } - self.pending_events.enqueue(Event::LSPS1Client(LSPS1ClientEvent::OrderStatus { + self.pending_events.enqueue(LSPS1ClientEvent::OrderStatus { request_id, counterparty_node_id: *counterparty_node_id, order_id: response.order_id, order: response.order, payment: response.payment, channel: response.channel, - })); + }); }, None => { return Err(LightningError { @@ -393,13 +387,11 @@ where }); } - self.pending_events.enqueue(Event::LSPS1Client( - LSPS1ClientEvent::OrderRequestFailed { - request_id: request_id.clone(), - counterparty_node_id: *counterparty_node_id, - error: error.clone(), - }, - )); + self.pending_events.enqueue(LSPS1ClientEvent::OrderRequestFailed { + request_id: request_id.clone(), + counterparty_node_id: *counterparty_node_id, + error: error.clone(), + }); Err(LightningError { err: format!( diff --git a/lightning-liquidity/src/lsps1/service.rs b/lightning-liquidity/src/lsps1/service.rs index 9cd2e0a1f2a..fc973fa062b 100644 --- a/lightning-liquidity/src/lsps1/service.rs +++ b/lightning-liquidity/src/lsps1/service.rs @@ -17,7 +17,7 @@ use super::msgs::{ }; use crate::message_queue::MessageQueue; -use crate::events::{Event, EventQueue}; +use crate::events::EventQueue; use crate::lsps0::ser::{ProtocolMessageHandler, RequestId, ResponseError}; use crate::prelude::{new_hash_map, HashMap, String}; use crate::sync::{Arc, Mutex, RwLock}; @@ -219,13 +219,11 @@ where .insert(request_id.clone(), LSPS1Request::CreateOrder(params.clone())); } - self.pending_events.enqueue(Event::LSPS1Service( - LSPS1ServiceEvent::RequestForPaymentDetails { - request_id, - counterparty_node_id: *counterparty_node_id, - order: params.order, - }, - )); + self.pending_events.enqueue(LSPS1ServiceEvent::RequestForPaymentDetails { + request_id, + counterparty_node_id: *counterparty_node_id, + order: params.order, + }); Ok(()) } @@ -322,11 +320,11 @@ where if let Err(e) = outbound_channel.awaiting_payment() { peer_state_lock.outbound_channels_by_order_id.remove(¶ms.order_id); - self.pending_events.enqueue(Event::LSPS1Service(LSPS1ServiceEvent::Refund { + self.pending_events.enqueue(LSPS1ServiceEvent::Refund { request_id, counterparty_node_id: *counterparty_node_id, order_id: params.order_id, - })); + }); return Err(e); } @@ -334,13 +332,11 @@ where .pending_requests .insert(request_id.clone(), LSPS1Request::GetOrder(params.clone())); - self.pending_events.enqueue(Event::LSPS1Service( - LSPS1ServiceEvent::CheckPaymentConfirmation { - request_id, - counterparty_node_id: *counterparty_node_id, - order_id: params.order_id, - }, - )); + self.pending_events.enqueue(LSPS1ServiceEvent::CheckPaymentConfirmation { + request_id, + counterparty_node_id: *counterparty_node_id, + order_id: params.order_id, + }); }, None => { return Err(LightningError { diff --git a/lightning-liquidity/src/lsps2/client.rs b/lightning-liquidity/src/lsps2/client.rs index 0f9db62e79c..31be95f03ff 100644 --- a/lightning-liquidity/src/lsps2/client.rs +++ b/lightning-liquidity/src/lsps2/client.rs @@ -8,7 +8,7 @@ //! Contains the main bLIP-52 / LSPS2 client object, [`LSPS2ClientHandler`]. -use crate::events::{Event, EventQueue}; +use crate::events::EventQueue; use crate::lsps0::ser::{ProtocolMessageHandler, RequestId, ResponseError}; use crate::lsps2::event::LSPS2ClientEvent; use crate::message_queue::MessageQueue; @@ -198,13 +198,11 @@ where }); } - self.pending_events.enqueue(Event::LSPS2Client( - LSPS2ClientEvent::OpeningParametersReady { - request_id, - counterparty_node_id: *counterparty_node_id, - opening_fee_params_menu: result.opening_fee_params_menu, - }, - )); + self.pending_events.enqueue(LSPS2ClientEvent::OpeningParametersReady { + request_id, + counterparty_node_id: *counterparty_node_id, + opening_fee_params_menu: result.opening_fee_params_menu, + }); }, None => { return Err(LightningError { @@ -264,15 +262,13 @@ where })?; if let Ok(intercept_scid) = result.jit_channel_scid.to_scid() { - self.pending_events.enqueue(Event::LSPS2Client( - LSPS2ClientEvent::InvoiceParametersReady { - request_id, - counterparty_node_id: *counterparty_node_id, - intercept_scid, - cltv_expiry_delta: result.lsp_cltv_expiry_delta, - payment_size_msat: jit_channel.payment_size_msat, - }, - )); + self.pending_events.enqueue(LSPS2ClientEvent::InvoiceParametersReady { + request_id, + counterparty_node_id: *counterparty_node_id, + intercept_scid, + cltv_expiry_delta: result.lsp_cltv_expiry_delta, + payment_size_msat: jit_channel.payment_size_msat, + }); } else { return Err(LightningError { err: format!( diff --git a/lightning-liquidity/src/lsps2/service.rs b/lightning-liquidity/src/lsps2/service.rs index 95a94bc422e..191f119bd51 100644 --- a/lightning-liquidity/src/lsps2/service.rs +++ b/lightning-liquidity/src/lsps2/service.rs @@ -9,7 +9,7 @@ //! Contains the main bLIP-52 / LSPS2 server-side object, [`LSPS2ServiceHandler`]. -use crate::events::{Event, EventQueue}; +use crate::events::EventQueue; use crate::lsps0::ser::{ LSPSMessage, ProtocolMessageHandler, RequestId, ResponseError, JSONRPC_INTERNAL_ERROR_ERROR_CODE, JSONRPC_INTERNAL_ERROR_ERROR_MESSAGE, @@ -806,13 +806,13 @@ where }; match jit_channel.htlc_intercepted(htlc) { Ok(Some(HTLCInterceptedAction::OpenChannel(open_channel_params))) => { - let event = Event::LSPS2Service(LSPS2ServiceEvent::OpenChannel { + let event = LSPS2ServiceEvent::OpenChannel { their_network_key: counterparty_node_id.clone(), amt_to_forward_msat: open_channel_params.amt_to_forward_msat, opening_fee_msat: open_channel_params.opening_fee_msat, user_channel_id: jit_channel.user_channel_id, intercept_scid, - }); + }; self.pending_events.enqueue(event); }, Ok(Some(HTLCInterceptedAction::ForwardHTLC(channel_id))) => { @@ -1091,11 +1091,11 @@ where request, ) { (Ok(()), msg) => { - let event = Event::LSPS2Service(LSPS2ServiceEvent::GetInfo { + let event = LSPS2ServiceEvent::GetInfo { request_id, counterparty_node_id: *counterparty_node_id, token: params.token, - }); + }; self.pending_events.enqueue(event); (Ok(()), msg) @@ -1210,12 +1210,12 @@ where request, ) { (Ok(()), msg) => { - let event = Event::LSPS2Service(LSPS2ServiceEvent::BuyRequest { + let event = LSPS2ServiceEvent::BuyRequest { request_id, counterparty_node_id: *counterparty_node_id, opening_fee_params: params.opening_fee_params, payment_size_msat: params.payment_size_msat, - }); + }; self.pending_events.enqueue(event); (Ok(()), msg) diff --git a/lightning-liquidity/src/manager.rs b/lightning-liquidity/src/manager.rs index c8bf1e05a72..31d7c2d354c 100644 --- a/lightning-liquidity/src/manager.rs +++ b/lightning-liquidity/src/manager.rs @@ -1,4 +1,4 @@ -use crate::events::{Event, EventQueue}; +use crate::events::{EventQueue, LiquidityEvent}; use crate::lsps0::client::LSPS0ClientHandler; use crate::lsps0::msgs::LSPS0Message; use crate::lsps0::ser::{ @@ -73,7 +73,7 @@ pub struct LiquidityClientConfig { /// [`LiquidityManager`] to wake the [`PeerManager`] when there are pending messages to be sent. /// /// Users need to continually poll [`LiquidityManager::get_and_clear_pending_events`] in order to surface -/// [`Event`]'s that likely need to be handled. +/// [`LiquidityEvent`]'s that likely need to be handled. /// /// If the LSPS2 service is configured, users must forward the following parameters from LDK events: /// - [`Event::HTLCIntercepted`] to [`LSPS2ServiceHandler::htlc_intercepted`] @@ -329,7 +329,7 @@ where { /// /// [`MAX_EVENT_QUEUE_SIZE`]: crate::events::MAX_EVENT_QUEUE_SIZE #[cfg(feature = "std")] - pub fn wait_next_event(&self) -> Event { + pub fn wait_next_event(&self) -> LiquidityEvent { self.pending_events.wait_next_event() } @@ -342,7 +342,7 @@ where { /// [`MAX_EVENT_QUEUE_SIZE`] has been reached. /// /// [`MAX_EVENT_QUEUE_SIZE`]: crate::events::MAX_EVENT_QUEUE_SIZE - pub fn next_event(&self) -> Option { + pub fn next_event(&self) -> Option { self.pending_events.next_event() } @@ -355,7 +355,7 @@ where { /// [`MAX_EVENT_QUEUE_SIZE`] has been reached. /// /// [`MAX_EVENT_QUEUE_SIZE`]: crate::events::MAX_EVENT_QUEUE_SIZE - pub async fn next_event_async(&self) -> Event { + pub async fn next_event_async(&self) -> LiquidityEvent { self.pending_events.next_event_async().await } @@ -368,7 +368,7 @@ where { /// [`MAX_EVENT_QUEUE_SIZE`] has been reached. /// /// [`MAX_EVENT_QUEUE_SIZE`]: crate::events::MAX_EVENT_QUEUE_SIZE - pub fn get_and_clear_pending_events(&self) -> Vec { + pub fn get_and_clear_pending_events(&self) -> Vec { self.pending_events.get_and_clear_pending_events() } diff --git a/lightning-liquidity/tests/lsps2_integration_tests.rs b/lightning-liquidity/tests/lsps2_integration_tests.rs index 92e172606ab..f31a4de7cb1 100644 --- a/lightning-liquidity/tests/lsps2_integration_tests.rs +++ b/lightning-liquidity/tests/lsps2_integration_tests.rs @@ -4,7 +4,7 @@ mod common; use common::{create_service_and_client_nodes, get_lsps_message, Node}; -use lightning_liquidity::events::Event; +use lightning_liquidity::events::LiquidityEvent; use lightning_liquidity::lsps2::client::LSPS2ClientConfig; use lightning_liquidity::lsps2::event::{LSPS2ClientEvent, LSPS2ServiceEvent}; use lightning_liquidity::lsps2::msgs::RawOpeningFeeParams; @@ -113,7 +113,7 @@ fn invoice_generation_flow() { let get_info_event = service_node.liquidity_manager.next_event().unwrap(); match get_info_event { - Event::LSPS2Service(LSPS2ServiceEvent::GetInfo { + LiquidityEvent::LSPS2Service(LSPS2ServiceEvent::GetInfo { request_id, counterparty_node_id, token, @@ -151,7 +151,7 @@ fn invoice_generation_flow() { let opening_params_event = client_node.liquidity_manager.next_event().unwrap(); let opening_fee_params = match opening_params_event { - Event::LSPS2Client(LSPS2ClientEvent::OpeningParametersReady { + LiquidityEvent::LSPS2Client(LSPS2ClientEvent::OpeningParametersReady { request_id, counterparty_node_id, opening_fee_params_menu, @@ -175,7 +175,7 @@ fn invoice_generation_flow() { let buy_event = service_node.liquidity_manager.next_event().unwrap(); match buy_event { - Event::LSPS2Service(LSPS2ServiceEvent::BuyRequest { + LiquidityEvent::LSPS2Service(LSPS2ServiceEvent::BuyRequest { request_id, counterparty_node_id, opening_fee_params: ofp, @@ -210,7 +210,7 @@ fn invoice_generation_flow() { let invoice_params_event = client_node.liquidity_manager.next_event().unwrap(); match invoice_params_event { - Event::LSPS2Client(LSPS2ClientEvent::InvoiceParametersReady { + LiquidityEvent::LSPS2Client(LSPS2ClientEvent::InvoiceParametersReady { request_id, counterparty_node_id, intercept_scid: iscid, From 095194ffcbc14505fb64cdcbbe39e61eec4c056f Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Wed, 29 Jan 2025 22:04:17 +0000 Subject: [PATCH 4/9] Mark static method string as `'static` since it is --- lightning-liquidity/src/lsps0/msgs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lightning-liquidity/src/lsps0/msgs.rs b/lightning-liquidity/src/lsps0/msgs.rs index c3cb4fb3725..760bf8870b3 100644 --- a/lightning-liquidity/src/lsps0/msgs.rs +++ b/lightning-liquidity/src/lsps0/msgs.rs @@ -41,7 +41,7 @@ pub enum LSPS0Request { impl LSPS0Request { /// Returns the method name associated with the given request variant. - pub fn method(&self) -> &str { + pub fn method(&self) -> &'static str { match self { LSPS0Request::ListProtocols(_) => LSPS0_LISTPROTOCOLS_METHOD_NAME, } From f9c477f80a8fbc8b1ddcaec7b6fb057ccfc10bb1 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Sun, 2 Feb 2025 09:21:18 +0100 Subject: [PATCH 5/9] Prefix BLIP-50/LSPS0 message types to avoid naming collisions --- lightning-liquidity/src/lsps0/client.rs | 9 +++++---- lightning-liquidity/src/lsps0/msgs.rs | 18 ++++++++++-------- lightning-liquidity/src/lsps0/ser.rs | 4 ++-- lightning-liquidity/src/lsps0/service.rs | 10 +++++----- 4 files changed, 22 insertions(+), 19 deletions(-) diff --git a/lightning-liquidity/src/lsps0/client.rs b/lightning-liquidity/src/lsps0/client.rs index 84a11b5af6a..56e7d3a5ad4 100644 --- a/lightning-liquidity/src/lsps0/client.rs +++ b/lightning-liquidity/src/lsps0/client.rs @@ -7,7 +7,8 @@ use crate::events::EventQueue; use crate::lsps0::event::LSPS0ClientEvent; use crate::lsps0::msgs::{ - LSPS0Message, LSPS0Request, LSPS0Response, ListProtocolsRequest, ListProtocolsResponse, + LSPS0ListProtocolsRequest, LSPS0ListProtocolsResponse, LSPS0Message, LSPS0Request, + LSPS0Response, }; use crate::lsps0::ser::{ProtocolMessageHandler, ResponseError}; use crate::message_queue::MessageQueue; @@ -51,7 +52,7 @@ where pub fn list_protocols(&self, counterparty_node_id: &PublicKey) { let msg = LSPS0Message::Request( utils::generate_request_id(&self.entropy_source), - LSPS0Request::ListProtocols(ListProtocolsRequest {}), + LSPS0Request::ListProtocols(LSPS0ListProtocolsRequest {}), ); self.pending_messages.enqueue(counterparty_node_id, msg.into()); @@ -61,7 +62,7 @@ where &self, response: LSPS0Response, counterparty_node_id: &PublicKey, ) -> Result<(), LightningError> { match response { - LSPS0Response::ListProtocols(ListProtocolsResponse { protocols }) => { + LSPS0Response::ListProtocols(LSPS0ListProtocolsResponse { protocols }) => { self.pending_events.enqueue(LSPS0ClientEvent::ListProtocolsResponse { counterparty_node_id: *counterparty_node_id, protocols, @@ -146,7 +147,7 @@ mod tests { *message, LSPSMessage::LSPS0(LSPS0Message::Request( RequestId("00000000000000000000000000000000".to_string()), - LSPS0Request::ListProtocols(ListProtocolsRequest {}) + LSPS0Request::ListProtocols(LSPS0ListProtocolsRequest {}) )) ); } diff --git a/lightning-liquidity/src/lsps0/msgs.rs b/lightning-liquidity/src/lsps0/msgs.rs index 760bf8870b3..5c522af9123 100644 --- a/lightning-liquidity/src/lsps0/msgs.rs +++ b/lightning-liquidity/src/lsps0/msgs.rs @@ -15,7 +15,7 @@ pub(crate) const LSPS0_LISTPROTOCOLS_METHOD_NAME: &str = "lsps0.list_protocols"; /// specification](https://github.com/lightning/blips/blob/master/blip-0050.md#lsps-specification-support-query) /// for more information. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize, Default)] -pub struct ListProtocolsRequest {} +pub struct LSPS0ListProtocolsRequest {} /// A response to a `list_protocols` request. /// @@ -23,7 +23,7 @@ pub struct ListProtocolsRequest {} /// specification](https://github.com/lightning/blips/blob/master/blip-0050.md#lsps-specification-support-query) /// for more information. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct ListProtocolsResponse { +pub struct LSPS0ListProtocolsResponse { /// A list of supported protocols. pub protocols: Vec, } @@ -36,7 +36,7 @@ pub struct ListProtocolsResponse { #[derive(Clone, Debug, PartialEq, Eq)] pub enum LSPS0Request { /// A request calling `list_protocols`. - ListProtocols(ListProtocolsRequest), + ListProtocols(LSPS0ListProtocolsRequest), } impl LSPS0Request { @@ -56,7 +56,7 @@ impl LSPS0Request { #[derive(Clone, Debug, PartialEq, Eq)] pub enum LSPS0Response { /// A response to a `list_protocols` request. - ListProtocols(ListProtocolsResponse), + ListProtocols(LSPS0ListProtocolsResponse), /// An error response to a `list_protocols` request. ListProtocolsError(ResponseError), } @@ -118,7 +118,7 @@ mod tests { msg, LSPSMessage::LSPS0(LSPS0Message::Request( RequestId("request:id:xyz123".to_string()), - LSPS0Request::ListProtocols(ListProtocolsRequest {}) + LSPS0Request::ListProtocols(LSPS0ListProtocolsRequest {}) )) ); } @@ -127,7 +127,7 @@ mod tests { fn serializes_request() { let request = LSPSMessage::LSPS0(LSPS0Message::Request( RequestId("request:id:xyz123".to_string()), - LSPS0Request::ListProtocols(ListProtocolsRequest {}), + LSPS0Request::ListProtocols(LSPS0ListProtocolsRequest {}), )); let json = serde_json::to_string(&request).unwrap(); assert_eq!( @@ -156,7 +156,9 @@ mod tests { response, LSPSMessage::LSPS0(LSPS0Message::Response( RequestId("request:id:xyz123".to_string()), - LSPS0Response::ListProtocols(ListProtocolsResponse { protocols: vec![1, 2, 3] }) + LSPS0Response::ListProtocols(LSPS0ListProtocolsResponse { + protocols: vec![1, 2, 3] + }) )) ); } @@ -212,7 +214,7 @@ mod tests { fn serializes_response() { let response = LSPSMessage::LSPS0(LSPS0Message::Response( RequestId("request:id:xyz123".to_string()), - LSPS0Response::ListProtocols(ListProtocolsResponse { protocols: vec![1, 2, 3] }), + LSPS0Response::ListProtocols(LSPS0ListProtocolsResponse { protocols: vec![1, 2, 3] }), )); let json = serde_json::to_string(&response).unwrap(); assert_eq!( diff --git a/lightning-liquidity/src/lsps0/ser.rs b/lightning-liquidity/src/lsps0/ser.rs index bb57734ae60..52522623108 100644 --- a/lightning-liquidity/src/lsps0/ser.rs +++ b/lightning-liquidity/src/lsps0/ser.rs @@ -5,7 +5,7 @@ //! information. use crate::lsps0::msgs::{ - LSPS0Message, LSPS0Request, LSPS0Response, ListProtocolsRequest, + LSPS0ListProtocolsRequest, LSPS0Message, LSPS0Request, LSPS0Response, LSPS0_LISTPROTOCOLS_METHOD_NAME, }; @@ -428,7 +428,7 @@ impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> { Some(method) => match method { LSPSMethod::LSPS0ListProtocols => Ok(LSPSMessage::LSPS0(LSPS0Message::Request( id, - LSPS0Request::ListProtocols(ListProtocolsRequest {}), + LSPS0Request::ListProtocols(LSPS0ListProtocolsRequest {}), ))), LSPSMethod::LSPS1GetInfo => { let request = serde_json::from_value(params.unwrap_or(json!({}))) diff --git a/lightning-liquidity/src/lsps0/service.rs b/lightning-liquidity/src/lsps0/service.rs index efd1669f5ac..8a0d8676cc8 100644 --- a/lightning-liquidity/src/lsps0/service.rs +++ b/lightning-liquidity/src/lsps0/service.rs @@ -13,7 +13,7 @@ //! specifcation](https://github.com/lightning/blips/blob/master/blip-0050.md) for more //! information. -use crate::lsps0::msgs::{LSPS0Message, LSPS0Request, LSPS0Response, ListProtocolsResponse}; +use crate::lsps0::msgs::{LSPS0ListProtocolsResponse, LSPS0Message, LSPS0Request, LSPS0Response}; use crate::lsps0::ser::{ProtocolMessageHandler, RequestId}; use crate::message_queue::MessageQueue; use crate::prelude::Vec; @@ -43,7 +43,7 @@ impl LSPS0ServiceHandler { LSPS0Request::ListProtocols(_) => { let msg = LSPS0Message::Response( request_id, - LSPS0Response::ListProtocols(ListProtocolsResponse { + LSPS0Response::ListProtocols(LSPS0ListProtocolsResponse { protocols: self.protocols.clone(), }), ); @@ -79,7 +79,7 @@ impl ProtocolMessageHandler for LSPS0ServiceHandler { #[cfg(test)] mod tests { - use crate::lsps0::msgs::ListProtocolsRequest; + use crate::lsps0::msgs::LSPS0ListProtocolsRequest; use crate::lsps0::ser::LSPSMessage; use crate::tests::utils; use alloc::string::ToString; @@ -96,7 +96,7 @@ mod tests { let list_protocols_request = LSPS0Message::Request( RequestId("xyz123".to_string()), - LSPS0Request::ListProtocols(ListProtocolsRequest {}), + LSPS0Request::ListProtocols(LSPS0ListProtocolsRequest {}), ); let counterparty_node_id = utils::parse_pubkey( "027100442c3b79f606f80f322d98d499eefcb060599efc5d4ecb00209c2cb54190", @@ -115,7 +115,7 @@ mod tests { *message, LSPSMessage::LSPS0(LSPS0Message::Response( RequestId("xyz123".to_string()), - LSPS0Response::ListProtocols(ListProtocolsResponse { protocols: vec![] }) + LSPS0Response::ListProtocols(LSPS0ListProtocolsResponse { protocols: vec![] }) )) ); } From 6b720fd88b43abc6c8c6f157423b1c694164331a Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Sun, 2 Feb 2025 09:36:15 +0100 Subject: [PATCH 6/9] Prefix BLIP-51/LSPS1 message types to avoid naming collisions --- lightning-liquidity/src/lsps1/client.rs | 27 +++--- lightning-liquidity/src/lsps1/event.rs | 26 +++--- lightning-liquidity/src/lsps1/msgs.rs | 108 ++++++++++++----------- lightning-liquidity/src/lsps1/service.rs | 51 ++++++----- 4 files changed, 111 insertions(+), 101 deletions(-) diff --git a/lightning-liquidity/src/lsps1/client.rs b/lightning-liquidity/src/lsps1/client.rs index 2658cb9fcad..e354ffa9d1d 100644 --- a/lightning-liquidity/src/lsps1/client.rs +++ b/lightning-liquidity/src/lsps1/client.rs @@ -11,8 +11,9 @@ use super::event::LSPS1ClientEvent; use super::msgs::{ - CreateOrderRequest, CreateOrderResponse, GetInfoRequest, GetInfoResponse, GetOrderRequest, - LSPS1Message, LSPS1Request, LSPS1Response, OrderId, OrderParameters, + LSPS1CreateOrderRequest, LSPS1CreateOrderResponse, LSPS1GetInfoRequest, LSPS1GetInfoResponse, + LSPS1GetOrderRequest, LSPS1Message, LSPS1OrderId, LSPS1OrderParams, LSPS1Request, + LSPS1Response, }; use crate::message_queue::MessageQueue; @@ -94,14 +95,15 @@ where peer_state_lock.pending_get_info_requests.insert(request_id.clone()); } - let request = LSPS1Request::GetInfo(GetInfoRequest {}); + let request = LSPS1Request::GetInfo(LSPS1GetInfoRequest {}); let msg = LSPS1Message::Request(request_id.clone(), request).into(); self.pending_messages.enqueue(&counterparty_node_id, msg); request_id } fn handle_get_info_response( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, result: GetInfoResponse, + &self, request_id: RequestId, counterparty_node_id: &PublicKey, + result: LSPS1GetInfoResponse, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.write().unwrap(); @@ -184,7 +186,7 @@ where /// /// The client agrees to paying channel fees according to the provided parameters. pub fn create_order( - &self, counterparty_node_id: &PublicKey, order: OrderParameters, + &self, counterparty_node_id: &PublicKey, order: LSPS1OrderParams, refund_onchain_address: Option
, ) -> RequestId { let (request_id, request_msg) = { @@ -195,8 +197,10 @@ where let mut peer_state_lock = inner_state_lock.lock().unwrap(); let request_id = crate::utils::generate_request_id(&self.entropy_source); - let request = - LSPS1Request::CreateOrder(CreateOrderRequest { order, refund_onchain_address }); + let request = LSPS1Request::CreateOrder(LSPS1CreateOrderRequest { + order, + refund_onchain_address, + }); let msg = LSPS1Message::Request(request_id.clone(), request).into(); peer_state_lock.pending_create_order_requests.insert(request_id.clone()); @@ -212,7 +216,7 @@ where fn handle_create_order_response( &self, request_id: RequestId, counterparty_node_id: &PublicKey, - response: CreateOrderResponse, + response: LSPS1CreateOrderResponse, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.read().unwrap(); match outer_state_lock.get(counterparty_node_id) { @@ -302,7 +306,7 @@ where /// /// [`LSPS1ClientEvent::OrderStatus`]: crate::lsps1::event::LSPS1ClientEvent::OrderStatus pub fn check_order_status( - &self, counterparty_node_id: &PublicKey, order_id: OrderId, + &self, counterparty_node_id: &PublicKey, order_id: LSPS1OrderId, ) -> RequestId { let (request_id, request_msg) = { let mut outer_state_lock = self.per_peer_state.write().unwrap(); @@ -314,7 +318,8 @@ where let request_id = crate::utils::generate_request_id(&self.entropy_source); peer_state_lock.pending_get_order_requests.insert(request_id.clone()); - let request = LSPS1Request::GetOrder(GetOrderRequest { order_id: order_id.clone() }); + let request = + LSPS1Request::GetOrder(LSPS1GetOrderRequest { order_id: order_id.clone() }); let msg = LSPS1Message::Request(request_id.clone(), request).into(); (request_id, Some(msg)) @@ -329,7 +334,7 @@ where fn handle_get_order_response( &self, request_id: RequestId, counterparty_node_id: &PublicKey, - response: CreateOrderResponse, + response: LSPS1CreateOrderResponse, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.read().unwrap(); match outer_state_lock.get(counterparty_node_id) { diff --git a/lightning-liquidity/src/lsps1/event.rs b/lightning-liquidity/src/lsps1/event.rs index 3bdeca477fe..91e3160d2f0 100644 --- a/lightning-liquidity/src/lsps1/event.rs +++ b/lightning-liquidity/src/lsps1/event.rs @@ -9,8 +9,8 @@ //! Contains bLIP-51 / LSPS1 event types -use super::msgs::OrderId; -use super::msgs::{ChannelInfo, LSPS1Options, OrderParameters, PaymentInfo}; +use super::msgs::LSPS1OrderId; +use super::msgs::{LSPS1ChannelInfo, LSPS1Options, LSPS1OrderParams, LSPS1PaymentInfo}; use crate::lsps0::ser::{RequestId, ResponseError}; @@ -78,13 +78,13 @@ pub enum LSPS1ClientEvent { /// The node id of the LSP. counterparty_node_id: PublicKey, /// The id of the channel order. - order_id: OrderId, + order_id: LSPS1OrderId, /// The order created by client and approved by LSP. - order: OrderParameters, + order: LSPS1OrderParams, /// The details regarding payment of the order - payment: PaymentInfo, + payment: LSPS1PaymentInfo, /// The details regarding state of the channel ordered. - channel: Option, + channel: Option, }, /// Information from the LSP about the status of a previously created order. /// @@ -102,13 +102,13 @@ pub enum LSPS1ClientEvent { /// The node id of the LSP. counterparty_node_id: PublicKey, /// The id of the channel order. - order_id: OrderId, + order_id: LSPS1OrderId, /// The order created by client and approved by LSP. - order: OrderParameters, + order: LSPS1OrderParams, /// The details regarding payment of the order - payment: PaymentInfo, + payment: LSPS1PaymentInfo, /// The details regarding state of the channel ordered. - channel: Option, + channel: Option, }, /// A request previously issued via [`LSPS1ClientHandler::create_order`] or [`LSPS1ClientHandler::check_order_status`]. /// failed as the LSP returned an error response. @@ -151,7 +151,7 @@ pub enum LSPS1ServiceEvent { /// The node id of the client making the information request. counterparty_node_id: PublicKey, /// The order requested by the client. - order: OrderParameters, + order: LSPS1OrderParams, }, /// A request from client to check the status of the payment. /// @@ -169,7 +169,7 @@ pub enum LSPS1ServiceEvent { /// The node id of the client making the information request. counterparty_node_id: PublicKey, /// The order id of order with pending payment. - order_id: OrderId, + order_id: LSPS1OrderId, }, /// If error is encountered, refund the amount if paid by the client. Refund { @@ -178,6 +178,6 @@ pub enum LSPS1ServiceEvent { /// The node id of the client making the information request. counterparty_node_id: PublicKey, /// The order id of the refunded order. - order_id: OrderId, + order_id: LSPS1OrderId, }, } diff --git a/lightning-liquidity/src/lsps1/msgs.rs b/lightning-liquidity/src/lsps1/msgs.rs index 94e030400a5..db46a21ba8a 100644 --- a/lightning-liquidity/src/lsps1/msgs.rs +++ b/lightning-liquidity/src/lsps1/msgs.rs @@ -27,7 +27,7 @@ pub(crate) const LSPS1_CREATE_ORDER_REQUEST_ORDER_MISMATCH_ERROR_CODE: i32 = 100 /// The identifier of an order. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize, Hash)] -pub struct OrderId(pub String); +pub struct LSPS1OrderId(pub String); /// A request made to an LSP to retrieve the supported options. /// @@ -36,7 +36,7 @@ pub struct OrderId(pub String); /// more information. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize, Default)] #[serde(default)] -pub struct GetInfoRequest {} +pub struct LSPS1GetInfoRequest {} /// An object representing the supported protocol options. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] @@ -69,9 +69,9 @@ pub struct LSPS1Options { pub max_channel_balance_sat: u64, } -/// A response to a [`GetInfoRequest`]. +/// A response to a [`LSPS1GetInfoRequest`]. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct GetInfoResponse { +pub struct LSPS1GetInfoResponse { /// All options supported by the LSP. #[serde(flatten)] pub options: LSPS1Options, @@ -83,10 +83,10 @@ pub struct GetInfoResponse { /// specification](https://github.com/lightning/blips/blob/master/blip-0051.md#2-lsps1create_order) /// for more information. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct CreateOrderRequest { +pub struct LSPS1CreateOrderRequest { /// The order made. #[serde(flatten)] - pub order: OrderParameters, + pub order: LSPS1OrderParams, /// The address where the LSP will send the funds if the order fails. #[serde(default)] #[serde(skip_serializing_if = "Option::is_none")] @@ -96,7 +96,7 @@ pub struct CreateOrderRequest { /// An object representing an bLIP-51 / LSPS1 channel order. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct OrderParameters { +pub struct LSPS1OrderParams { /// Indicates how many satoshi the LSP will provide on their side. #[serde(with = "string_amount")] pub lsp_balance_sat: u64, @@ -118,28 +118,28 @@ pub struct OrderParameters { pub announce_channel: bool, } -/// A response to a [`CreateOrderRequest`]. +/// A response to a [`LSPS1CreateOrderRequest`]. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct CreateOrderResponse { +pub struct LSPS1CreateOrderResponse { /// The id of the channel order. - pub order_id: OrderId, + pub order_id: LSPS1OrderId, /// The parameters of channel order. #[serde(flatten)] - pub order: OrderParameters, + pub order: LSPS1OrderParams, /// The datetime when the order was created pub created_at: chrono::DateTime, /// The current state of the order. - pub order_state: OrderState, + pub order_state: LSPS1OrderState, /// Contains details about how to pay for the order. - pub payment: PaymentInfo, + pub payment: LSPS1PaymentInfo, /// Contains information about the channel state. - pub channel: Option, + pub channel: Option, } -/// An object representing the state of an order. +/// An object representing the status of an order. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum OrderState { +pub enum LSPS1OrderState { /// The order has been created. Created, /// The LSP has opened the channel and published the funding transaction. @@ -150,18 +150,18 @@ pub enum OrderState { /// Details regarding how to pay for an order. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct PaymentInfo { +pub struct LSPS1PaymentInfo { /// A Lightning payment using BOLT 11. - pub bolt11: Option, + pub bolt11: Option, /// An onchain payment. - pub onchain: Option, + pub onchain: Option, } /// A Lightning payment using BOLT 11. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct Bolt11PaymentInfo { +pub struct LSPS1Bolt11PaymentInfo { /// Indicates the current state of the payment. - pub state: PaymentState, + pub state: LSPS1PaymentState, /// The datetime when the payment option expires. pub expires_at: chrono::DateTime, /// The total fee the LSP will charge to open this channel in satoshi. @@ -176,9 +176,9 @@ pub struct Bolt11PaymentInfo { /// An onchain payment. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct OnchainPaymentInfo { +pub struct LSPS1OnchainPaymentInfo { /// Indicates the current state of the payment. - pub state: PaymentState, + pub state: LSPS1PaymentState, /// The datetime when the payment option expires. pub expires_at: chrono::DateTime, /// The total fee the LSP will charge to open this channel in satoshi. @@ -211,7 +211,7 @@ pub struct OnchainPaymentInfo { /// been deprecated and `REFUNDED` should be used instead. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum PaymentState { +pub enum LSPS1PaymentState { /// A payment is expected. ExpectPayment, /// A sufficient payment has been received. @@ -223,7 +223,7 @@ pub enum PaymentState { /// Details regarding a detected on-chain payment. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct OnchainPayment { +pub struct LSPS1OnchainPayment { /// The outpoint of the payment. pub outpoint: String, /// The amount of satoshi paid. @@ -235,7 +235,7 @@ pub struct OnchainPayment { /// Details regarding the state of an ordered channel. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct ChannelInfo { +pub struct LSPS1ChannelInfo { /// The datetime when the funding transaction has been published. pub funded_at: chrono::DateTime, /// The outpoint of the funding transaction. @@ -250,36 +250,36 @@ pub struct ChannelInfo { /// specification](https://github.com/lightning/blips/blob/master/blip-0051.md#21-lsps1get_order) /// for more information. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct GetOrderRequest { +pub struct LSPS1GetOrderRequest { /// The id of the order. - pub order_id: OrderId, + pub order_id: LSPS1OrderId, } /// An enum that captures all the valid JSON-RPC requests in the bLIP-51 / LSPS1 protocol. #[derive(Clone, Debug, PartialEq, Eq)] pub enum LSPS1Request { /// A request to learn about the options supported by the LSP. - GetInfo(GetInfoRequest), + GetInfo(LSPS1GetInfoRequest), /// A request to create a channel order. - CreateOrder(CreateOrderRequest), + CreateOrder(LSPS1CreateOrderRequest), /// A request to query a previously created channel order. - GetOrder(GetOrderRequest), + GetOrder(LSPS1GetOrderRequest), } /// An enum that captures all the valid JSON-RPC responses in the bLIP-51 / LSPS1 protocol. #[derive(Clone, Debug, PartialEq, Eq)] pub enum LSPS1Response { - /// A successful response to a [`GetInfoRequest`]. - GetInfo(GetInfoResponse), - /// An error response to a [`GetInfoRequest`]. + /// A successful response to a [`LSPS1GetInfoRequest`]. + GetInfo(LSPS1GetInfoResponse), + /// An error response to a [`LSPS1GetInfoRequest`]. GetInfoError(ResponseError), - /// A successful response to a [`CreateOrderRequest`]. - CreateOrder(CreateOrderResponse), - /// An error response to a [`CreateOrderRequest`]. + /// A successful response to a [`LSPS1CreateOrderRequest`]. + CreateOrder(LSPS1CreateOrderResponse), + /// An error response to a [`LSPS1CreateOrderRequest`]. CreateOrderError(ResponseError), - /// A successful response to a [`GetOrderRequest`]. - GetOrder(CreateOrderResponse), - /// An error response to a [`GetOrderRequest`]. + /// A successful response to a [`LSPS1GetOrderRequest`]. + GetOrder(LSPS1CreateOrderResponse), + /// An error response to a [`LSPS1GetOrderRequest`]. GetOrderError(ResponseError), } @@ -351,7 +351,7 @@ mod tests { fn parse_spec_test_vectors() { // Here, we simply assert that we're able to parse all examples given in LSPS1. let json_str = r#"{}"#; - let _get_info_request: GetInfoRequest = serde_json::from_str(json_str).unwrap(); + let _get_info_request: LSPS1GetInfoRequest = serde_json::from_str(json_str).unwrap(); let json_str = r#"{ "min_required_channel_confirmations": 0, @@ -365,7 +365,7 @@ mod tests { "min_channel_balance_sat": "50000", "max_channel_balance_sat": "100000000" }"#; - let _get_info_response: GetInfoResponse = serde_json::from_str(json_str).unwrap(); + let _get_info_response: LSPS1GetInfoResponse = serde_json::from_str(json_str).unwrap(); let json_str = r#"{ "lsp_balance_sat": "5000000", @@ -377,7 +377,8 @@ mod tests { "refund_onchain_address": "bc1qvmsy0f3yyes6z9jvddk8xqwznndmdwapvrc0xrmhd3vqj5rhdrrq6hz49h", "announce_channel": true }"#; - let _create_order_request: CreateOrderRequest = serde_json::from_str(json_str).unwrap(); + let _create_order_request: LSPS1CreateOrderRequest = + serde_json::from_str(json_str).unwrap(); let json_str = r#"{ "state" : "EXPECT_PAYMENT", @@ -386,7 +387,7 @@ mod tests { "order_total_sat": "200888", "invoice": "lnbc252u1p3aht9ysp580g4633gd2x9lc5al0wd8wx0mpn9748jeyz46kqjrpxn52uhfpjqpp5qgf67tcqmuqehzgjm8mzya90h73deafvr4m5705l5u5l4r05l8cqdpud3h8ymm4w3jhytnpwpczqmt0de6xsmre2pkxzm3qydmkzdjrdev9s7zhgfaqxqyjw5qcqpjrzjqt6xptnd85lpqnu2lefq4cx070v5cdwzh2xlvmdgnu7gqp4zvkus5zapryqqx9qqqyqqqqqqqqqqqcsq9q9qyysgqen77vu8xqjelum24hgjpgfdgfgx4q0nehhalcmuggt32japhjuksq9jv6eksjfnppm4hrzsgyxt8y8xacxut9qv3fpyetz8t7tsymygq8yzn05" }"#; - let _bolt11_payment: Bolt11PaymentInfo = serde_json::from_str(json_str).unwrap(); + let _bolt11_payment: LSPS1Bolt11PaymentInfo = serde_json::from_str(json_str).unwrap(); let json_str = r#"{ "state": "EXPECT_PAYMENT", @@ -397,7 +398,7 @@ mod tests { "min_onchain_payment_confirmations": 1, "min_fee_for_0conf": 253 }"#; - let _onchain_payment: OnchainPaymentInfo = serde_json::from_str(json_str).unwrap(); + let _onchain_payment: LSPS1OnchainPaymentInfo = serde_json::from_str(json_str).unwrap(); let json_str = r#"{ "bolt11": { @@ -417,7 +418,7 @@ mod tests { "min_fee_for_0conf": 253 } }"#; - let _payment: PaymentInfo = serde_json::from_str(json_str).unwrap(); + let _payment: LSPS1PaymentInfo = serde_json::from_str(json_str).unwrap(); let json_str = r#"{ "order_id": "bb4b5d0a-8334-49d8-9463-90a6d413af7c", @@ -451,26 +452,27 @@ mod tests { }, "channel": null }"#; - let _create_order_response: CreateOrderResponse = serde_json::from_str(json_str).unwrap(); + let _create_order_response: LSPS1CreateOrderResponse = + serde_json::from_str(json_str).unwrap(); let json_str = r#"{ "order_id": "bb4b5d0a-8334-49d8-9463-90a6d413af7c" }"#; - let _get_order_request: GetOrderRequest = serde_json::from_str(json_str).unwrap(); + let _get_order_request: LSPS1GetOrderRequest = serde_json::from_str(json_str).unwrap(); let json_str = r#"{ "funded_at": "2012-04-23T18:25:43.511Z", "funding_outpoint": "0301e0480b374b32851a9462db29dc19fe830a7f7d7a88b81612b9d42099c0ae:0", "expires_at": "2012-04-23T18:25:43.511Z" }"#; - let _channel: ChannelInfo = serde_json::from_str(json_str).unwrap(); + let _channel: LSPS1ChannelInfo = serde_json::from_str(json_str).unwrap(); let json_str = r#""CANCELLED""#; - let payment_state: PaymentState = serde_json::from_str(json_str).unwrap(); - assert_eq!(payment_state, PaymentState::Refunded); + let payment_state: LSPS1PaymentState = serde_json::from_str(json_str).unwrap(); + assert_eq!(payment_state, LSPS1PaymentState::Refunded); let json_str = r#""REFUNDED""#; - let payment_state: PaymentState = serde_json::from_str(json_str).unwrap(); - assert_eq!(payment_state, PaymentState::Refunded); + let payment_state: LSPS1PaymentState = serde_json::from_str(json_str).unwrap(); + assert_eq!(payment_state, LSPS1PaymentState::Refunded); } } diff --git a/lightning-liquidity/src/lsps1/service.rs b/lightning-liquidity/src/lsps1/service.rs index fc973fa062b..b51721eb506 100644 --- a/lightning-liquidity/src/lsps1/service.rs +++ b/lightning-liquidity/src/lsps1/service.rs @@ -11,9 +11,10 @@ use super::event::LSPS1ServiceEvent; use super::msgs::{ - ChannelInfo, CreateOrderRequest, CreateOrderResponse, GetInfoResponse, GetOrderRequest, - LSPS1Message, LSPS1Options, LSPS1Request, LSPS1Response, OrderId, OrderParameters, OrderState, - PaymentInfo, LSPS1_CREATE_ORDER_REQUEST_ORDER_MISMATCH_ERROR_CODE, + LSPS1ChannelInfo, LSPS1CreateOrderRequest, LSPS1CreateOrderResponse, LSPS1GetInfoResponse, + LSPS1GetOrderRequest, LSPS1Message, LSPS1Options, LSPS1OrderId, LSPS1OrderParams, + LSPS1OrderState, LSPS1PaymentInfo, LSPS1Request, LSPS1Response, + LSPS1_CREATE_ORDER_REQUEST_ORDER_MISMATCH_ERROR_CODE, }; use crate::message_queue::MessageQueue; @@ -54,8 +55,8 @@ impl From for LightningError { #[derive(PartialEq, Debug)] enum OutboundRequestState { - OrderCreated { order_id: OrderId }, - WaitingPayment { order_id: OrderId }, + OrderCreated { order_id: LSPS1OrderId }, + WaitingPayment { order_id: LSPS1OrderId }, Ready, } @@ -71,9 +72,9 @@ impl OutboundRequestState { } struct OutboundLSPS1Config { - order: OrderParameters, + order: LSPS1OrderParams, created_at: chrono::DateTime, - payment: PaymentInfo, + payment: LSPS1PaymentInfo, } struct OutboundCRChannel { @@ -83,8 +84,8 @@ struct OutboundCRChannel { impl OutboundCRChannel { fn new( - order: OrderParameters, created_at: chrono::DateTime, order_id: OrderId, - payment: PaymentInfo, + order: LSPS1OrderParams, created_at: chrono::DateTime, order_id: LSPS1OrderId, + payment: LSPS1PaymentInfo, ) -> Self { Self { state: OutboundRequestState::OrderCreated { order_id }, @@ -105,13 +106,13 @@ impl OutboundCRChannel { #[derive(Default)] struct PeerState { - outbound_channels_by_order_id: HashMap, + outbound_channels_by_order_id: HashMap, request_to_cid: HashMap, pending_requests: HashMap, } impl PeerState { - fn insert_outbound_channel(&mut self, order_id: OrderId, channel: OutboundCRChannel) { + fn insert_outbound_channel(&mut self, order_id: LSPS1OrderId, channel: OutboundCRChannel) { self.outbound_channels_by_order_id.insert(order_id, channel); } @@ -119,7 +120,7 @@ impl PeerState { self.request_to_cid.insert(request_id, channel_id); } - fn remove_outbound_channel(&mut self, order_id: OrderId) { + fn remove_outbound_channel(&mut self, order_id: LSPS1OrderId) { self.outbound_channels_by_order_id.remove(&order_id); } } @@ -166,7 +167,7 @@ where fn handle_get_info_request( &self, request_id: RequestId, counterparty_node_id: &PublicKey, ) -> Result<(), LightningError> { - let response = LSPS1Response::GetInfo(GetInfoResponse { + let response = LSPS1Response::GetInfo(LSPS1GetInfoResponse { options: self .config .supported_options @@ -184,7 +185,8 @@ where } fn handle_create_order_request( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, params: CreateOrderRequest, + &self, request_id: RequestId, counterparty_node_id: &PublicKey, + params: LSPS1CreateOrderRequest, ) -> Result<(), LightningError> { if !is_valid(¶ms.order, &self.config.supported_options.as_ref().unwrap()) { let response = LSPS1Response::CreateOrderError(ResponseError { @@ -234,7 +236,7 @@ where /// /// [`LSPS1ServiceEvent::RequestForPaymentDetails`]: crate::lsps1::event::LSPS1ServiceEvent::RequestForPaymentDetails pub fn send_payment_details( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, payment: PaymentInfo, + &self, request_id: RequestId, counterparty_node_id: &PublicKey, payment: LSPS1PaymentInfo, created_at: chrono::DateTime, ) -> Result<(), APIError> { let (result, response) = { @@ -256,10 +258,10 @@ where peer_state_lock.insert_outbound_channel(order_id.clone(), channel); - let response = LSPS1Response::CreateOrder(CreateOrderResponse { + let response = LSPS1Response::CreateOrder(LSPS1CreateOrderResponse { order: params.order, order_id, - order_state: OrderState::Created, + order_state: LSPS1OrderState::Created, created_at, payment, channel: None, @@ -300,7 +302,8 @@ where } fn handle_get_order_request( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, params: GetOrderRequest, + &self, request_id: RequestId, counterparty_node_id: &PublicKey, + params: LSPS1GetOrderRequest, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.read().unwrap(); match outer_state_lock.get(counterparty_node_id) { @@ -358,8 +361,8 @@ where /// /// [`LSPS1ServiceEvent::CheckPaymentConfirmation`]: crate::lsps1::event::LSPS1ServiceEvent::CheckPaymentConfirmation pub fn update_order_status( - &self, request_id: RequestId, counterparty_node_id: PublicKey, order_id: OrderId, - order_state: OrderState, channel: Option, + &self, request_id: RequestId, counterparty_node_id: PublicKey, order_id: LSPS1OrderId, + order_state: LSPS1OrderState, channel: Option, ) -> Result<(), APIError> { let (result, response) = { let outer_state_lock = self.per_peer_state.read().unwrap(); @@ -373,7 +376,7 @@ where { let config = &outbound_channel.config; - let response = LSPS1Response::GetOrder(CreateOrderResponse { + let response = LSPS1Response::GetOrder(LSPS1CreateOrderResponse { order_id, order: config.order.clone(), order_state, @@ -411,9 +414,9 @@ where result } - fn generate_order_id(&self) -> OrderId { + fn generate_order_id(&self) -> LSPS1OrderId { let bytes = self.entropy_source.get_secure_random_bytes(); - OrderId(utils::hex_str(&bytes[0..16])) + LSPS1OrderId(utils::hex_str(&bytes[0..16])) } } @@ -457,7 +460,7 @@ fn check_range(min: u64, max: u64, value: u64) -> bool { (value >= min) && (value <= max) } -fn is_valid(order: &OrderParameters, options: &LSPS1Options) -> bool { +fn is_valid(order: &LSPS1OrderParams, options: &LSPS1Options) -> bool { let bool = check_range( options.min_initial_client_balance_sat, options.max_initial_client_balance_sat, From cfc636c174d4f7325d9a5505c43ac6890cdfbd59 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Sun, 2 Feb 2025 09:46:08 +0100 Subject: [PATCH 7/9] Prefix BLIP-52/LSPS2 message types to avoid naming collisions --- lightning-liquidity/src/lsps2/client.rs | 15 ++-- lightning-liquidity/src/lsps2/event.rs | 6 +- lightning-liquidity/src/lsps2/msgs.rs | 70 ++++++++++--------- lightning-liquidity/src/lsps2/service.rs | 25 +++---- lightning-liquidity/src/lsps2/utils.rs | 6 +- .../tests/lsps2_integration_tests.rs | 4 +- 6 files changed, 65 insertions(+), 61 deletions(-) diff --git a/lightning-liquidity/src/lsps2/client.rs b/lightning-liquidity/src/lsps2/client.rs index 31be95f03ff..f0157b139bf 100644 --- a/lightning-liquidity/src/lsps2/client.rs +++ b/lightning-liquidity/src/lsps2/client.rs @@ -26,8 +26,8 @@ use core::default::Default; use core::ops::Deref; use crate::lsps2::msgs::{ - BuyRequest, BuyResponse, GetInfoRequest, GetInfoResponse, LSPS2Message, LSPS2Request, - LSPS2Response, OpeningFeeParams, + LSPS2BuyRequest, LSPS2BuyResponse, LSPS2GetInfoRequest, LSPS2GetInfoResponse, LSPS2Message, + LSPS2OpeningFeeParams, LSPS2Request, LSPS2Response, }; /// Client-side configuration options for JIT channels. @@ -122,7 +122,7 @@ where peer_state_lock.pending_get_info_requests.insert(request_id.clone()); } - let request = LSPS2Request::GetInfo(GetInfoRequest { token }); + let request = LSPS2Request::GetInfo(LSPS2GetInfoRequest { token }); let msg = LSPS2Message::Request(request_id.clone(), request).into(); self.pending_messages.enqueue(&counterparty_node_id, msg); @@ -149,7 +149,7 @@ where /// [`InvoiceParametersReady`]: crate::lsps2::event::LSPS2ClientEvent::InvoiceParametersReady pub fn select_opening_params( &self, counterparty_node_id: PublicKey, payment_size_msat: Option, - opening_fee_params: OpeningFeeParams, + opening_fee_params: LSPS2OpeningFeeParams, ) -> Result { let request_id = crate::utils::generate_request_id(&self.entropy_source); @@ -173,7 +173,7 @@ where } } - let request = LSPS2Request::Buy(BuyRequest { opening_fee_params, payment_size_msat }); + let request = LSPS2Request::Buy(LSPS2BuyRequest { opening_fee_params, payment_size_msat }); let msg = LSPS2Message::Request(request_id.clone(), request).into(); self.pending_messages.enqueue(&counterparty_node_id, msg); @@ -181,7 +181,8 @@ where } fn handle_get_info_response( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, result: GetInfoResponse, + &self, request_id: RequestId, counterparty_node_id: &PublicKey, + result: LSPS2GetInfoResponse, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.read().unwrap(); match outer_state_lock.get(counterparty_node_id) { @@ -245,7 +246,7 @@ where } fn handle_buy_response( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, result: BuyResponse, + &self, request_id: RequestId, counterparty_node_id: &PublicKey, result: LSPS2BuyResponse, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.read().unwrap(); match outer_state_lock.get(counterparty_node_id) { diff --git a/lightning-liquidity/src/lsps2/event.rs b/lightning-liquidity/src/lsps2/event.rs index 0334be24b3c..41dcb9c7433 100644 --- a/lightning-liquidity/src/lsps2/event.rs +++ b/lightning-liquidity/src/lsps2/event.rs @@ -9,7 +9,7 @@ //! Contains bLIP-52 / LSPS2 event types -use super::msgs::OpeningFeeParams; +use super::msgs::LSPS2OpeningFeeParams; use crate::lsps0::ser::RequestId; use crate::prelude::{String, Vec}; @@ -36,7 +36,7 @@ pub enum LSPS2ClientEvent { counterparty_node_id: PublicKey, /// The menu of fee parameters the LSP is offering at this time. /// You must select one of these if you wish to proceed. - opening_fee_params_menu: Vec, + opening_fee_params_menu: Vec, }, /// Provides the necessary information to generate a payable invoice that then may be given to /// the payer. @@ -103,7 +103,7 @@ pub enum LSPS2ServiceEvent { /// The client node id that is making this request. counterparty_node_id: PublicKey, /// The channel parameters they have selected. - opening_fee_params: OpeningFeeParams, + opening_fee_params: LSPS2OpeningFeeParams, /// The size of the initial payment they would like to receive. payment_size_msat: Option, }, diff --git a/lightning-liquidity/src/lsps2/msgs.rs b/lightning-liquidity/src/lsps2/msgs.rs index 8d6378d24fe..ab8114c38cc 100644 --- a/lightning-liquidity/src/lsps2/msgs.rs +++ b/lightning-liquidity/src/lsps2/msgs.rs @@ -27,7 +27,7 @@ pub(crate) const LSPS2_BUY_REQUEST_PAYMENT_SIZE_TOO_LARGE_ERROR_CODE: i32 = 203; #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] /// A request made to an LSP to learn their current channel fees and parameters. -pub struct GetInfoRequest { +pub struct LSPS2GetInfoRequest { /// An optional token to provide to the LSP. pub token: Option, } @@ -35,8 +35,8 @@ pub struct GetInfoRequest { /// Fees and parameters for a JIT Channel without the promise. /// /// The promise will be calculated automatically for the LSP and this type converted -/// into an [`OpeningFeeParams`] for transit over the wire. -pub struct RawOpeningFeeParams { +/// into an [`LSPS2OpeningFeeParams`] for transit over the wire. +pub struct LSPS2RawOpeningFeeParams { /// The minimum fee required for the channel open. pub min_fee_msat: u64, /// A fee proportional to the size of the initial payment. @@ -53,8 +53,10 @@ pub struct RawOpeningFeeParams { pub max_payment_size_msat: u64, } -impl RawOpeningFeeParams { - pub(crate) fn into_opening_fee_params(self, promise_secret: &[u8; 32]) -> OpeningFeeParams { +impl LSPS2RawOpeningFeeParams { + pub(crate) fn into_opening_fee_params( + self, promise_secret: &[u8; 32], + ) -> LSPS2OpeningFeeParams { let mut hmac = HmacEngine::::new(promise_secret); hmac.input(&self.min_fee_msat.to_be_bytes()); hmac.input(&self.proportional.to_be_bytes()); @@ -65,7 +67,7 @@ impl RawOpeningFeeParams { hmac.input(&self.max_payment_size_msat.to_be_bytes()); let promise_bytes = Hmac::from_engine(hmac).to_byte_array(); let promise = utils::hex_str(&promise_bytes[..]); - OpeningFeeParams { + LSPS2OpeningFeeParams { min_fee_msat: self.min_fee_msat, proportional: self.proportional, valid_until: self.valid_until.clone(), @@ -82,9 +84,9 @@ impl RawOpeningFeeParams { /// Fees and parameters for a JIT Channel including the promise. /// /// The promise is an HMAC calculated using a secret known to the LSP and the rest of the fields as input. -/// It exists so the LSP can verify the authenticity of a client provided OpeningFeeParams by recalculating +/// It exists so the LSP can verify the authenticity of a client provided LSPS2OpeningFeeParams by recalculating /// the promise using the secret. Once verified they can be confident it was not modified by the client. -pub struct OpeningFeeParams { +pub struct LSPS2OpeningFeeParams { /// The minimum fee required for the channel open. #[serde(with = "string_amount")] pub min_fee_msat: u64, @@ -106,18 +108,18 @@ pub struct OpeningFeeParams { pub promise: String, } -/// A response to a [`GetInfoRequest`] +/// A response to a [`LSPS2GetInfoRequest`] #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct GetInfoResponse { +pub struct LSPS2GetInfoResponse { /// A set of opening fee parameters. - pub opening_fee_params_menu: Vec, + pub opening_fee_params_menu: Vec, } /// A request to buy a JIT channel. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct BuyRequest { +pub struct LSPS2BuyRequest { /// The fee parameters you would like to use. - pub opening_fee_params: OpeningFeeParams, + pub opening_fee_params: LSPS2OpeningFeeParams, /// The size of the initial payment you expect to receive. #[serde(default)] #[serde(skip_serializing_if = "Option::is_none")] @@ -127,9 +129,9 @@ pub struct BuyRequest { /// A newtype that holds a `short_channel_id` in human readable format of BBBxTTTx000. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct InterceptScid(String); +pub struct LSPS2InterceptScid(String); -impl From for InterceptScid { +impl From for LSPS2InterceptScid { fn from(scid: u64) -> Self { let block = scid_utils::block_from_scid(scid); let tx_index = scid_utils::tx_index_from_scid(scid); @@ -139,20 +141,20 @@ impl From for InterceptScid { } } -impl InterceptScid { - /// Try to convert a [`InterceptScid`] into a u64 used by LDK. +impl LSPS2InterceptScid { + /// Try to convert a [`LSPS2InterceptScid`] into a u64 used by LDK. pub fn to_scid(&self) -> Result { utils::scid_from_human_readable_string(&self.0) } } -/// A response to a [`BuyRequest`]. +/// A response to a [`LSPS2BuyRequest`]. /// /// Includes information needed to construct an invoice. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct BuyResponse { +pub struct LSPS2BuyResponse { /// The intercept short channel id used by LSP to identify need to open channel. - pub jit_channel_scid: InterceptScid, + pub jit_channel_scid: LSPS2InterceptScid, /// The locktime expiry delta the lsp requires. pub lsp_cltv_expiry_delta: u32, /// A flag that indicates who is trusting who. @@ -164,20 +166,20 @@ pub struct BuyResponse { /// An enum that captures all the valid JSON-RPC requests in the bLIP-52 / LSPS2 protocol. pub enum LSPS2Request { /// A request to learn an LSP's channel fees and parameters. - GetInfo(GetInfoRequest), + GetInfo(LSPS2GetInfoRequest), /// A request to buy a JIT channel from an LSP. - Buy(BuyRequest), + Buy(LSPS2BuyRequest), } #[derive(Clone, Debug, PartialEq, Eq)] /// An enum that captures all the valid JSON-RPC responses in the bLIP-52 / LSPS2 protocol. pub enum LSPS2Response { /// A successful response to a [`LSPS2Request::GetInfo`] request. - GetInfo(GetInfoResponse), + GetInfo(LSPS2GetInfoResponse), /// An error response to a [`LSPS2Request::GetInfo`] request. GetInfoError(ResponseError), /// A successful response to a [`LSPS2Request::Buy`] request. - Buy(BuyResponse), + Buy(LSPS2BuyResponse), /// An error response to a [`LSPS2Request::Buy`] request. BuyError(ResponseError), } @@ -226,7 +228,7 @@ mod tests { let min_payment_size_msat = 1; let max_payment_size_msat = 100_000_000; - let raw = RawOpeningFeeParams { + let raw = LSPS2RawOpeningFeeParams { min_fee_msat, proportional, valid_until: valid_until.clone().into(), @@ -261,7 +263,7 @@ mod tests { let min_payment_size_msat = 1; let max_payment_size_msat = 100_000_000; - let raw = RawOpeningFeeParams { + let raw = LSPS2RawOpeningFeeParams { min_fee_msat, proportional, valid_until: valid_until.into(), @@ -288,7 +290,7 @@ mod tests { let min_payment_size_msat = 1; let max_payment_size_msat = 100_000_000; - let raw = RawOpeningFeeParams { + let raw = LSPS2RawOpeningFeeParams { min_fee_msat, proportional, valid_until: valid_until.into(), @@ -317,7 +319,7 @@ mod tests { let min_payment_size_msat = 1; let max_payment_size_msat = 100_000_000; - let raw = RawOpeningFeeParams { + let raw = LSPS2RawOpeningFeeParams { min_fee_msat, proportional, valid_until: valid_until.into(), @@ -343,7 +345,7 @@ mod tests { let min_payment_size_msat = 1; let max_payment_size_msat = 100_000_000; - let raw = RawOpeningFeeParams { + let raw = LSPS2RawOpeningFeeParams { min_fee_msat, proportional, valid_until: valid_until.into(), @@ -362,13 +364,13 @@ mod tests { let payment_size_msat = Some(1234); let buy_request_fixed = - BuyRequest { opening_fee_params: opening_fee_params.clone(), payment_size_msat }; + LSPS2BuyRequest { opening_fee_params: opening_fee_params.clone(), payment_size_msat }; let json_str = r#"{"opening_fee_params":{"max_client_to_self_delay":128,"max_payment_size_msat":"100000000","min_fee_msat":"100","min_lifetime":144,"min_payment_size_msat":"1","promise":"1134a5c51e3ba2e8f4259610d5e12c1bf4c50ddcd3f8af563e0a00d1fff41dea","proportional":21,"valid_until":"2023-05-20T08:30:45Z"},"payment_size_msat":"1234"}"#; assert_eq!(json_str, serde_json::json!(buy_request_fixed).to_string()); assert_eq!(buy_request_fixed, serde_json::from_str(json_str).unwrap()); let payment_size_msat = None; - let buy_request_variable = BuyRequest { opening_fee_params, payment_size_msat }; + let buy_request_variable = LSPS2BuyRequest { opening_fee_params, payment_size_msat }; // Check we skip serialization if payment_size_msat is None. let json_str = r#"{"opening_fee_params":{"max_client_to_self_delay":128,"max_payment_size_msat":"100000000","min_fee_msat":"100","min_lifetime":144,"min_payment_size_msat":"1","promise":"1134a5c51e3ba2e8f4259610d5e12c1bf4c50ddcd3f8af563e0a00d1fff41dea","proportional":21,"valid_until":"2023-05-20T08:30:45Z"}}"#; @@ -407,7 +409,7 @@ mod tests { } ] }"#; - let _get_info_response: GetInfoResponse = serde_json::from_str(json_str).unwrap(); + let _get_info_response: LSPS2GetInfoResponse = serde_json::from_str(json_str).unwrap(); let json_str = r#"{ "opening_fee_params": { @@ -422,13 +424,13 @@ mod tests { }, "payment_size_msat": "42000" }"#; - let _buy_request: BuyRequest = serde_json::from_str(json_str).unwrap(); + let _buy_request: LSPS2BuyRequest = serde_json::from_str(json_str).unwrap(); let json_str = r#"{ "jit_channel_scid": "29451x4815x1", "lsp_cltv_expiry_delta" : 144, "client_trusts_lsp": false }"#; - let _buy_response: BuyResponse = serde_json::from_str(json_str).unwrap(); + let _buy_response: LSPS2BuyResponse = serde_json::from_str(json_str).unwrap(); } } diff --git a/lightning-liquidity/src/lsps2/service.rs b/lightning-liquidity/src/lsps2/service.rs index 191f119bd51..3b53fe42f1a 100644 --- a/lightning-liquidity/src/lsps2/service.rs +++ b/lightning-liquidity/src/lsps2/service.rs @@ -40,8 +40,8 @@ use core::ops::Deref; use core::sync::atomic::{AtomicUsize, Ordering}; use crate::lsps2::msgs::{ - BuyRequest, BuyResponse, GetInfoRequest, GetInfoResponse, LSPS2Message, LSPS2Request, - LSPS2Response, OpeningFeeParams, RawOpeningFeeParams, + LSPS2BuyRequest, LSPS2BuyResponse, LSPS2GetInfoRequest, LSPS2GetInfoResponse, LSPS2Message, + LSPS2OpeningFeeParams, LSPS2RawOpeningFeeParams, LSPS2Request, LSPS2Response, LSPS2_BUY_REQUEST_INVALID_OPENING_FEE_PARAMS_ERROR_CODE, LSPS2_BUY_REQUEST_PAYMENT_SIZE_TOO_LARGE_ERROR_CODE, LSPS2_BUY_REQUEST_PAYMENT_SIZE_TOO_SMALL_ERROR_CODE, @@ -142,7 +142,7 @@ impl OutboundJITChannelState { } fn htlc_intercepted( - &mut self, opening_fee_params: &OpeningFeeParams, payment_size_msat: &Option, + &mut self, opening_fee_params: &LSPS2OpeningFeeParams, payment_size_msat: &Option, htlc: InterceptedHTLC, ) -> Result<(Self, Option), ChannelStateError> { match self { @@ -395,13 +395,14 @@ impl OutboundJITChannelState { struct OutboundJITChannel { state: OutboundJITChannelState, user_channel_id: u128, - opening_fee_params: OpeningFeeParams, + opening_fee_params: LSPS2OpeningFeeParams, payment_size_msat: Option, } impl OutboundJITChannel { fn new( - payment_size_msat: Option, opening_fee_params: OpeningFeeParams, user_channel_id: u128, + payment_size_msat: Option, opening_fee_params: LSPS2OpeningFeeParams, + user_channel_id: u128, ) -> Self { Self { user_channel_id, @@ -647,7 +648,7 @@ where /// [`LSPS2ServiceEvent::GetInfo`]: crate::lsps2::event::LSPS2ServiceEvent::GetInfo pub fn opening_fee_params_generated( &self, counterparty_node_id: &PublicKey, request_id: RequestId, - opening_fee_params_menu: Vec, + opening_fee_params_menu: Vec, ) -> Result<(), APIError> { let (result, response) = { let outer_state_lock = self.per_peer_state.read().unwrap(); @@ -658,7 +659,7 @@ where match self.remove_pending_request(&mut peer_state_lock, &request_id) { Some(LSPS2Request::GetInfo(_)) => { - let response = LSPS2Response::GetInfo(GetInfoResponse { + let response = LSPS2Response::GetInfo(LSPS2GetInfoResponse { opening_fee_params_menu: opening_fee_params_menu .into_iter() .map(|param| { @@ -736,7 +737,7 @@ where peer_state_lock .insert_outbound_channel(intercept_scid, outbound_jit_channel); - let response = LSPS2Response::Buy(BuyResponse { + let response = LSPS2Response::Buy(LSPS2BuyResponse { jit_channel_scid: intercept_scid.into(), lsp_cltv_expiry_delta: cltv_expiry_delta, client_trusts_lsp, @@ -1076,7 +1077,7 @@ where } fn handle_get_info_request( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, params: GetInfoRequest, + &self, request_id: RequestId, counterparty_node_id: &PublicKey, params: LSPS2GetInfoRequest, ) -> Result<(), LightningError> { let (result, response) = { let mut outer_state_lock = self.per_peer_state.write().unwrap(); @@ -1112,7 +1113,7 @@ where } fn handle_buy_request( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, params: BuyRequest, + &self, request_id: RequestId, counterparty_node_id: &PublicKey, params: LSPS2BuyRequest, ) -> Result<(), LightningError> { if let Some(payment_size_msat) = params.payment_size_msat { if payment_size_msat < params.opening_fee_params.min_payment_size_msat { @@ -1513,7 +1514,7 @@ mod tests { #[test] fn test_jit_channel_state_mpp() { let payment_size_msat = Some(500_000_000); - let opening_fee_params = OpeningFeeParams { + let opening_fee_params = LSPS2OpeningFeeParams { min_fee_msat: 10_000_000, proportional: 10_000, valid_until: Utc.timestamp_opt(3000, 0).unwrap(), @@ -1705,7 +1706,7 @@ mod tests { #[test] fn test_jit_channel_state_no_mpp() { let payment_size_msat = None; - let opening_fee_params = OpeningFeeParams { + let opening_fee_params = LSPS2OpeningFeeParams { min_fee_msat: 10_000_000, proportional: 10_000, valid_until: Utc.timestamp_opt(3000, 0).unwrap(), diff --git a/lightning-liquidity/src/lsps2/utils.rs b/lightning-liquidity/src/lsps2/utils.rs index 91db3449c60..c3eb82ae0d7 100644 --- a/lightning-liquidity/src/lsps2/utils.rs +++ b/lightning-liquidity/src/lsps2/utils.rs @@ -1,6 +1,6 @@ //! Utilities for implementing the bLIP-52 / LSPS2 standard. -use crate::lsps2::msgs::OpeningFeeParams; +use crate::lsps2::msgs::LSPS2OpeningFeeParams; use crate::utils; use bitcoin::hashes::hmac::{Hmac, HmacEngine}; @@ -12,7 +12,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; /// Determines if the given parameters are valid given the secret used to generate the promise. pub fn is_valid_opening_fee_params( - fee_params: &OpeningFeeParams, promise_secret: &[u8; 32], + fee_params: &LSPS2OpeningFeeParams, promise_secret: &[u8; 32], ) -> bool { if is_expired_opening_fee_params(fee_params) { return false; @@ -32,7 +32,7 @@ pub fn is_valid_opening_fee_params( /// Determines if the given parameters are expired, or still valid. #[cfg_attr(not(feature = "std"), allow(unused_variables))] -pub fn is_expired_opening_fee_params(fee_params: &OpeningFeeParams) -> bool { +pub fn is_expired_opening_fee_params(fee_params: &LSPS2OpeningFeeParams) -> bool { #[cfg(feature = "std")] { let seconds_since_epoch = SystemTime::now() diff --git a/lightning-liquidity/tests/lsps2_integration_tests.rs b/lightning-liquidity/tests/lsps2_integration_tests.rs index f31a4de7cb1..ed9b1bf94ef 100644 --- a/lightning-liquidity/tests/lsps2_integration_tests.rs +++ b/lightning-liquidity/tests/lsps2_integration_tests.rs @@ -7,7 +7,7 @@ use common::{create_service_and_client_nodes, get_lsps_message, Node}; use lightning_liquidity::events::LiquidityEvent; use lightning_liquidity::lsps2::client::LSPS2ClientConfig; use lightning_liquidity::lsps2::event::{LSPS2ClientEvent, LSPS2ServiceEvent}; -use lightning_liquidity::lsps2::msgs::RawOpeningFeeParams; +use lightning_liquidity::lsps2::msgs::LSPS2RawOpeningFeeParams; use lightning_liquidity::lsps2::service::LSPS2ServiceConfig; use lightning_liquidity::lsps2::utils::is_valid_opening_fee_params; use lightning_liquidity::{LiquidityClientConfig, LiquidityServiceConfig}; @@ -125,7 +125,7 @@ fn invoice_generation_flow() { _ => panic!("Unexpected event"), } - let raw_opening_params = RawOpeningFeeParams { + let raw_opening_params = LSPS2RawOpeningFeeParams { min_fee_msat: 100, proportional: 21, valid_until: DateTime::parse_from_rfc3339("2035-05-20T08:30:45Z").unwrap().into(), From 8526b9fca36560822bc4219aba0b02aefe196f20 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Sun, 2 Feb 2025 09:47:41 +0100 Subject: [PATCH 8/9] Prefix general LSPS message types to avoid naming collisions --- lightning-liquidity/src/lsps0/client.rs | 26 ++++++++-------- lightning-liquidity/src/lsps0/msgs.rs | 26 ++++++++-------- lightning-liquidity/src/lsps0/ser.rs | 24 +++++++-------- lightning-liquidity/src/lsps0/service.rs | 10 +++--- lightning-liquidity/src/lsps1/client.rs | 33 +++++++++++--------- lightning-liquidity/src/lsps1/event.rs | 22 ++++++------- lightning-liquidity/src/lsps1/msgs.rs | 12 ++++---- lightning-liquidity/src/lsps1/service.rs | 24 +++++++-------- lightning-liquidity/src/lsps2/client.rs | 25 ++++++++------- lightning-liquidity/src/lsps2/event.rs | 10 +++--- lightning-liquidity/src/lsps2/msgs.rs | 10 +++--- lightning-liquidity/src/lsps2/service.rs | 39 ++++++++++++------------ lightning-liquidity/src/manager.rs | 12 ++++---- lightning-liquidity/src/utils.rs | 6 ++-- 14 files changed, 143 insertions(+), 136 deletions(-) diff --git a/lightning-liquidity/src/lsps0/client.rs b/lightning-liquidity/src/lsps0/client.rs index 56e7d3a5ad4..7b049e65566 100644 --- a/lightning-liquidity/src/lsps0/client.rs +++ b/lightning-liquidity/src/lsps0/client.rs @@ -10,7 +10,7 @@ use crate::lsps0::msgs::{ LSPS0ListProtocolsRequest, LSPS0ListProtocolsResponse, LSPS0Message, LSPS0Request, LSPS0Response, }; -use crate::lsps0::ser::{ProtocolMessageHandler, ResponseError}; +use crate::lsps0::ser::{LSPSProtocolMessageHandler, LSPSResponseError}; use crate::message_queue::MessageQueue; use crate::sync::Arc; use crate::utils; @@ -69,20 +69,20 @@ where }); Ok(()) }, - LSPS0Response::ListProtocolsError(ResponseError { code, message, data, .. }) => { - Err(LightningError { - err: format!( - "ListProtocols error received. code = {}, message = {}, data = {:?}", - code, message, data - ), - action: ErrorAction::IgnoreAndLog(Level::Info), - }) - }, + LSPS0Response::ListProtocolsError(LSPSResponseError { + code, message, data, .. + }) => Err(LightningError { + err: format!( + "ListProtocols error received. code = {}, message = {}, data = {:?}", + code, message, data + ), + action: ErrorAction::IgnoreAndLog(Level::Info), + }), } } } -impl ProtocolMessageHandler for LSPS0ClientHandler +impl LSPSProtocolMessageHandler for LSPS0ClientHandler where ES::Target: EntropySource, { @@ -113,7 +113,7 @@ mod tests { use alloc::string::ToString; use alloc::sync::Arc; - use crate::lsps0::ser::{LSPSMessage, RequestId}; + use crate::lsps0::ser::{LSPSMessage, LSPSRequestId}; use crate::tests::utils::{self, TestEntropy}; use super::*; @@ -146,7 +146,7 @@ mod tests { assert_eq!( *message, LSPSMessage::LSPS0(LSPS0Message::Request( - RequestId("00000000000000000000000000000000".to_string()), + LSPSRequestId("00000000000000000000000000000000".to_string()), LSPS0Request::ListProtocols(LSPS0ListProtocolsRequest {}) )) ); diff --git a/lightning-liquidity/src/lsps0/msgs.rs b/lightning-liquidity/src/lsps0/msgs.rs index 5c522af9123..91ec28ca119 100644 --- a/lightning-liquidity/src/lsps0/msgs.rs +++ b/lightning-liquidity/src/lsps0/msgs.rs @@ -1,6 +1,6 @@ //! Message, request, and other primitive types used to implement LSPS0. -use crate::lsps0::ser::{LSPSMessage, RequestId, ResponseError}; +use crate::lsps0::ser::{LSPSMessage, LSPSRequestId, LSPSResponseError}; use crate::prelude::Vec; use serde::{Deserialize, Serialize}; @@ -58,7 +58,7 @@ pub enum LSPS0Response { /// A response to a `list_protocols` request. ListProtocols(LSPS0ListProtocolsResponse), /// An error response to a `list_protocols` request. - ListProtocolsError(ResponseError), + ListProtocolsError(LSPSResponseError), } /// An bLIP-50 / LSPS0 protocol message. @@ -69,9 +69,9 @@ pub enum LSPS0Response { #[derive(Clone, Debug, PartialEq, Eq)] pub enum LSPS0Message { /// A request variant. - Request(RequestId, LSPS0Request), + Request(LSPSRequestId, LSPS0Request), /// A response variant. - Response(RequestId, LSPS0Response), + Response(LSPSRequestId, LSPS0Response), } impl TryFrom for LSPS0Message { @@ -117,7 +117,7 @@ mod tests { assert_eq!( msg, LSPSMessage::LSPS0(LSPS0Message::Request( - RequestId("request:id:xyz123".to_string()), + LSPSRequestId("request:id:xyz123".to_string()), LSPS0Request::ListProtocols(LSPS0ListProtocolsRequest {}) )) ); @@ -126,7 +126,7 @@ mod tests { #[test] fn serializes_request() { let request = LSPSMessage::LSPS0(LSPS0Message::Request( - RequestId("request:id:xyz123".to_string()), + LSPSRequestId("request:id:xyz123".to_string()), LSPS0Request::ListProtocols(LSPS0ListProtocolsRequest {}), )); let json = serde_json::to_string(&request).unwrap(); @@ -147,7 +147,7 @@ mod tests { }"#; let mut request_id_to_method_map = new_hash_map(); request_id_to_method_map - .insert(RequestId("request:id:xyz123".to_string()), LSPSMethod::LSPS0ListProtocols); + .insert(LSPSRequestId("request:id:xyz123".to_string()), LSPSMethod::LSPS0ListProtocols); let response = LSPSMessage::from_str_with_id_map(json, &mut request_id_to_method_map).unwrap(); @@ -155,7 +155,7 @@ mod tests { assert_eq!( response, LSPSMessage::LSPS0(LSPS0Message::Response( - RequestId("request:id:xyz123".to_string()), + LSPSRequestId("request:id:xyz123".to_string()), LSPS0Response::ListProtocols(LSPS0ListProtocolsResponse { protocols: vec![1, 2, 3] }) @@ -175,7 +175,7 @@ mod tests { }"#; let mut request_id_to_method_map = new_hash_map(); request_id_to_method_map - .insert(RequestId("request:id:xyz123".to_string()), LSPSMethod::LSPS0ListProtocols); + .insert(LSPSRequestId("request:id:xyz123".to_string()), LSPSMethod::LSPS0ListProtocols); let response = LSPSMessage::from_str_with_id_map(json, &mut request_id_to_method_map).unwrap(); @@ -183,8 +183,8 @@ mod tests { assert_eq!( response, LSPSMessage::LSPS0(LSPS0Message::Response( - RequestId("request:id:xyz123".to_string()), - LSPS0Response::ListProtocolsError(ResponseError { + LSPSRequestId("request:id:xyz123".to_string()), + LSPS0Response::ListProtocolsError(LSPSResponseError { code: -32617, message: "Unknown Error".to_string(), data: None @@ -204,7 +204,7 @@ mod tests { }"#; let mut request_id_to_method_map = new_hash_map(); request_id_to_method_map - .insert(RequestId("request:id:xyz123".to_string()), LSPSMethod::LSPS0ListProtocols); + .insert(LSPSRequestId("request:id:xyz123".to_string()), LSPSMethod::LSPS0ListProtocols); let response = LSPSMessage::from_str_with_id_map(json, &mut request_id_to_method_map); assert!(response.is_err()); @@ -213,7 +213,7 @@ mod tests { #[test] fn serializes_response() { let response = LSPSMessage::LSPS0(LSPS0Message::Response( - RequestId("request:id:xyz123".to_string()), + LSPSRequestId("request:id:xyz123".to_string()), LSPS0Response::ListProtocols(LSPS0ListProtocolsResponse { protocols: vec![1, 2, 3] }), )); let json = serde_json::to_string(&response).unwrap(); diff --git a/lightning-liquidity/src/lsps0/ser.rs b/lightning-liquidity/src/lsps0/ser.rs index 52522623108..e97a015802e 100644 --- a/lightning-liquidity/src/lsps0/ser.rs +++ b/lightning-liquidity/src/lsps0/ser.rs @@ -138,7 +138,7 @@ pub const LSPS_MESSAGE_TYPE_ID: u16 = 37913; /// /// The messages the protocol uses need to be able to be mapped /// from and into [`LSPSMessage`]. -pub(crate) trait ProtocolMessageHandler { +pub(crate) trait LSPSProtocolMessageHandler { type ProtocolMessage: TryFrom + Into; const PROTOCOL_NUMBER: Option; @@ -184,14 +184,14 @@ impl wire::Type for RawLSPSMessage { /// more information. #[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)] #[serde(transparent)] -pub struct RequestId(pub String); +pub struct LSPSRequestId(pub String); /// An error returned in response to an JSON-RPC request. /// /// Please refer to the [JSON-RPC 2.0 specification](https://www.jsonrpc.org/specification#error_object) for /// more information. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] -pub struct ResponseError { +pub struct LSPSResponseError { /// A number that indicates the error type that occurred. pub code: i32, /// A string providing a short description of the error. @@ -204,7 +204,7 @@ pub struct ResponseError { #[derive(Clone, Debug, PartialEq, Eq)] pub enum LSPSMessage { /// An invalid variant. - Invalid(ResponseError), + Invalid(LSPSResponseError), /// An LSPS0 message. LSPS0(LSPS0Message), /// An LSPS1 message. @@ -219,7 +219,7 @@ impl LSPSMessage { /// The given `request_id_to_method` associates request ids with method names, as response objects /// don't carry the latter. pub(crate) fn from_str_with_id_map( - json_str: &str, request_id_to_method_map: &mut HashMap, + json_str: &str, request_id_to_method_map: &mut HashMap, ) -> Result { let deserializer = &mut serde_json::Deserializer::from_str(json_str); let visitor = LSPSMessageVisitor { request_id_to_method_map }; @@ -227,16 +227,16 @@ impl LSPSMessage { } /// Returns the request id and the method. - pub(crate) fn get_request_id_and_method(&self) -> Option<(RequestId, LSPSMethod)> { + pub(crate) fn get_request_id_and_method(&self) -> Option<(LSPSRequestId, LSPSMethod)> { match self { LSPSMessage::LSPS0(LSPS0Message::Request(request_id, request)) => { - Some((RequestId(request_id.0.clone()), request.into())) + Some((LSPSRequestId(request_id.0.clone()), request.into())) }, LSPSMessage::LSPS1(LSPS1Message::Request(request_id, request)) => { - Some((RequestId(request_id.0.clone()), request.into())) + Some((LSPSRequestId(request_id.0.clone()), request.into())) }, LSPSMessage::LSPS2(LSPS2Message::Request(request_id, request)) => { - Some((RequestId(request_id.0.clone()), request.into())) + Some((LSPSRequestId(request_id.0.clone()), request.into())) }, _ => None, } @@ -361,7 +361,7 @@ impl Serialize for LSPSMessage { } struct LSPSMessageVisitor<'a> { - request_id_to_method_map: &'a mut HashMap, + request_id_to_method_map: &'a mut HashMap, } impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> { @@ -375,11 +375,11 @@ impl<'de, 'a> Visitor<'de> for LSPSMessageVisitor<'a> { where A: MapAccess<'de>, { - let mut id: Option = None; + let mut id: Option = None; let mut method: Option = None; let mut params = None; let mut result = None; - let mut error: Option = None; + let mut error: Option = None; while let Some(key) = map.next_key()? { match key { diff --git a/lightning-liquidity/src/lsps0/service.rs b/lightning-liquidity/src/lsps0/service.rs index 8a0d8676cc8..189a2cd0917 100644 --- a/lightning-liquidity/src/lsps0/service.rs +++ b/lightning-liquidity/src/lsps0/service.rs @@ -14,7 +14,7 @@ //! information. use crate::lsps0::msgs::{LSPS0ListProtocolsResponse, LSPS0Message, LSPS0Request, LSPS0Response}; -use crate::lsps0::ser::{ProtocolMessageHandler, RequestId}; +use crate::lsps0::ser::{LSPSProtocolMessageHandler, LSPSRequestId}; use crate::message_queue::MessageQueue; use crate::prelude::Vec; use crate::sync::Arc; @@ -37,7 +37,7 @@ impl LSPS0ServiceHandler { } fn handle_request( - &self, request_id: RequestId, request: LSPS0Request, counterparty_node_id: &PublicKey, + &self, request_id: LSPSRequestId, request: LSPS0Request, counterparty_node_id: &PublicKey, ) -> Result<(), lightning::ln::msgs::LightningError> { match request { LSPS0Request::ListProtocols(_) => { @@ -54,7 +54,7 @@ impl LSPS0ServiceHandler { } } -impl ProtocolMessageHandler for LSPS0ServiceHandler { +impl LSPSProtocolMessageHandler for LSPS0ServiceHandler { type ProtocolMessage = LSPS0Message; const PROTOCOL_NUMBER: Option = None; @@ -95,7 +95,7 @@ mod tests { let lsps0_handler = Arc::new(LSPS0ServiceHandler::new(protocols, pending_messages.clone())); let list_protocols_request = LSPS0Message::Request( - RequestId("xyz123".to_string()), + LSPSRequestId("xyz123".to_string()), LSPS0Request::ListProtocols(LSPS0ListProtocolsRequest {}), ); let counterparty_node_id = utils::parse_pubkey( @@ -114,7 +114,7 @@ mod tests { assert_eq!( *message, LSPSMessage::LSPS0(LSPS0Message::Response( - RequestId("xyz123".to_string()), + LSPSRequestId("xyz123".to_string()), LSPS0Response::ListProtocols(LSPS0ListProtocolsResponse { protocols: vec![] }) )) ); diff --git a/lightning-liquidity/src/lsps1/client.rs b/lightning-liquidity/src/lsps1/client.rs index e354ffa9d1d..88b3abc5ce3 100644 --- a/lightning-liquidity/src/lsps1/client.rs +++ b/lightning-liquidity/src/lsps1/client.rs @@ -18,7 +18,7 @@ use super::msgs::{ use crate::message_queue::MessageQueue; use crate::events::EventQueue; -use crate::lsps0::ser::{ProtocolMessageHandler, RequestId, ResponseError}; +use crate::lsps0::ser::{LSPSProtocolMessageHandler, LSPSRequestId, LSPSResponseError}; use crate::prelude::{new_hash_map, HashMap, HashSet}; use crate::sync::{Arc, Mutex, RwLock}; @@ -40,9 +40,9 @@ pub struct LSPS1ClientConfig { #[derive(Default)] struct PeerState { - pending_get_info_requests: HashSet, - pending_create_order_requests: HashSet, - pending_get_order_requests: HashSet, + pending_get_info_requests: HashSet, + pending_create_order_requests: HashSet, + pending_get_order_requests: HashSet, } /// The main object allowing to send and receive bLIP-51 / LSPS1 messages. @@ -81,10 +81,10 @@ where /// /// `counterparty_node_id` is the `node_id` of the LSP you would like to use. /// - /// Returns the used [`RequestId`], which will be returned via [`SupportedOptionsReady`]. + /// Returns the used [`LSPSRequestId`], which will be returned via [`SupportedOptionsReady`]. /// /// [`SupportedOptionsReady`]: crate::lsps1::event::LSPS1ClientEvent::SupportedOptionsReady - pub fn request_supported_options(&self, counterparty_node_id: PublicKey) -> RequestId { + pub fn request_supported_options(&self, counterparty_node_id: PublicKey) -> LSPSRequestId { let request_id = crate::utils::generate_request_id(&self.entropy_source); { let mut outer_state_lock = self.per_peer_state.write().unwrap(); @@ -102,7 +102,7 @@ where } fn handle_get_info_response( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, + &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, result: LSPS1GetInfoResponse, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.write().unwrap(); @@ -139,7 +139,8 @@ where } fn handle_get_info_error( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, error: ResponseError, + &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, + error: LSPSResponseError, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.read().unwrap(); match outer_state_lock.get(counterparty_node_id) { @@ -188,7 +189,7 @@ where pub fn create_order( &self, counterparty_node_id: &PublicKey, order: LSPS1OrderParams, refund_onchain_address: Option
, - ) -> RequestId { + ) -> LSPSRequestId { let (request_id, request_msg) = { let mut outer_state_lock = self.per_peer_state.write().unwrap(); let inner_state_lock = outer_state_lock @@ -215,7 +216,7 @@ where } fn handle_create_order_response( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, + &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, response: LSPS1CreateOrderResponse, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.read().unwrap(); @@ -257,7 +258,8 @@ where } fn handle_create_order_error( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, error: ResponseError, + &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, + error: LSPSResponseError, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.read().unwrap(); match outer_state_lock.get(counterparty_node_id) { @@ -307,7 +309,7 @@ where /// [`LSPS1ClientEvent::OrderStatus`]: crate::lsps1::event::LSPS1ClientEvent::OrderStatus pub fn check_order_status( &self, counterparty_node_id: &PublicKey, order_id: LSPS1OrderId, - ) -> RequestId { + ) -> LSPSRequestId { let (request_id, request_msg) = { let mut outer_state_lock = self.per_peer_state.write().unwrap(); let inner_state_lock = outer_state_lock @@ -333,7 +335,7 @@ where } fn handle_get_order_response( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, + &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, response: LSPS1CreateOrderResponse, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.read().unwrap(); @@ -375,7 +377,8 @@ where } fn handle_get_order_error( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, error: ResponseError, + &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, + error: LSPSResponseError, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.read().unwrap(); match outer_state_lock.get(counterparty_node_id) { @@ -419,7 +422,7 @@ where } } -impl ProtocolMessageHandler for LSPS1ClientHandler +impl LSPSProtocolMessageHandler for LSPS1ClientHandler where ES::Target: EntropySource, { diff --git a/lightning-liquidity/src/lsps1/event.rs b/lightning-liquidity/src/lsps1/event.rs index 91e3160d2f0..508a5a42a90 100644 --- a/lightning-liquidity/src/lsps1/event.rs +++ b/lightning-liquidity/src/lsps1/event.rs @@ -12,7 +12,7 @@ use super::msgs::LSPS1OrderId; use super::msgs::{LSPS1ChannelInfo, LSPS1Options, LSPS1OrderParams, LSPS1PaymentInfo}; -use crate::lsps0::ser::{RequestId, ResponseError}; +use crate::lsps0::ser::{LSPSRequestId, LSPSResponseError}; use bitcoin::secp256k1::PublicKey; @@ -34,7 +34,7 @@ pub enum LSPS1ClientEvent { /// This can be used to track which request this event corresponds to. /// /// [`LSPS1ClientHandler::request_supported_options`]: crate::lsps1::client::LSPS1ClientHandler::request_supported_options - request_id: RequestId, + request_id: LSPSRequestId, /// The node id of the LSP that provided this response. counterparty_node_id: PublicKey, /// All options supported by the LSP. @@ -51,11 +51,11 @@ pub enum LSPS1ClientEvent { /// This can be used to track which request this event corresponds to. /// /// [`LSPS1ClientHandler::request_supported_options`]: crate::lsps1::client::LSPS1ClientHandler::request_supported_options - request_id: RequestId, + request_id: LSPSRequestId, /// The node id of the LSP that provided this response. counterparty_node_id: PublicKey, /// The error that was returned. - error: ResponseError, + error: LSPSResponseError, }, /// Confirmation from the LSP about the order created by the client. /// @@ -74,7 +74,7 @@ pub enum LSPS1ClientEvent { /// This can be used to track which request this event corresponds to. /// /// [`LSPS1ClientHandler::create_order`]: crate::lsps1::client::LSPS1ClientHandler::create_order - request_id: RequestId, + request_id: LSPSRequestId, /// The node id of the LSP. counterparty_node_id: PublicKey, /// The id of the channel order. @@ -98,7 +98,7 @@ pub enum LSPS1ClientEvent { /// This can be used to track which request this event corresponds to. /// /// [`LSPS1ClientHandler::check_order_status`]: crate::lsps1::client::LSPS1ClientHandler::check_order_status - request_id: RequestId, + request_id: LSPSRequestId, /// The node id of the LSP. counterparty_node_id: PublicKey, /// The id of the channel order. @@ -123,11 +123,11 @@ pub enum LSPS1ClientEvent { /// /// [`LSPS1ClientHandler::create_order`]: crate::lsps1::client::LSPS1ClientHandler::create_order /// [`LSPS1ClientHandler::check_order_status`]: crate::lsps1::client::LSPS1ClientHandler::check_order_status - request_id: RequestId, + request_id: LSPSRequestId, /// The node id of the LSP. counterparty_node_id: PublicKey, /// The error that was returned. - error: ResponseError, + error: LSPSResponseError, }, } @@ -147,7 +147,7 @@ pub enum LSPS1ServiceEvent { /// An identifier that must be passed to [`LSPS1ServiceHandler::send_payment_details`]. /// /// [`LSPS1ServiceHandler::send_payment_details`]: crate::lsps1::service::LSPS1ServiceHandler::send_payment_details - request_id: RequestId, + request_id: LSPSRequestId, /// The node id of the client making the information request. counterparty_node_id: PublicKey, /// The order requested by the client. @@ -165,7 +165,7 @@ pub enum LSPS1ServiceEvent { /// An identifier that must be passed to [`LSPS1ServiceHandler::update_order_status`]. /// /// [`LSPS1ServiceHandler::update_order_status`]: crate::lsps1::service::LSPS1ServiceHandler::update_order_status - request_id: RequestId, + request_id: LSPSRequestId, /// The node id of the client making the information request. counterparty_node_id: PublicKey, /// The order id of order with pending payment. @@ -174,7 +174,7 @@ pub enum LSPS1ServiceEvent { /// If error is encountered, refund the amount if paid by the client. Refund { /// An identifier. - request_id: RequestId, + request_id: LSPSRequestId, /// The node id of the client making the information request. counterparty_node_id: PublicKey, /// The order id of the refunded order. diff --git a/lightning-liquidity/src/lsps1/msgs.rs b/lightning-liquidity/src/lsps1/msgs.rs index db46a21ba8a..86c63e71048 100644 --- a/lightning-liquidity/src/lsps1/msgs.rs +++ b/lightning-liquidity/src/lsps1/msgs.rs @@ -2,7 +2,7 @@ use crate::lsps0::ser::{ string_amount, u32_fee_rate, unchecked_address, unchecked_address_option, LSPSMessage, - RequestId, ResponseError, + LSPSRequestId, LSPSResponseError, }; use crate::prelude::String; @@ -272,24 +272,24 @@ pub enum LSPS1Response { /// A successful response to a [`LSPS1GetInfoRequest`]. GetInfo(LSPS1GetInfoResponse), /// An error response to a [`LSPS1GetInfoRequest`]. - GetInfoError(ResponseError), + GetInfoError(LSPSResponseError), /// A successful response to a [`LSPS1CreateOrderRequest`]. CreateOrder(LSPS1CreateOrderResponse), /// An error response to a [`LSPS1CreateOrderRequest`]. - CreateOrderError(ResponseError), + CreateOrderError(LSPSResponseError), /// A successful response to a [`LSPS1GetOrderRequest`]. GetOrder(LSPS1CreateOrderResponse), /// An error response to a [`LSPS1GetOrderRequest`]. - GetOrderError(ResponseError), + GetOrderError(LSPSResponseError), } /// An enum that captures all valid JSON-RPC messages in the bLIP-51 / LSPS1 protocol. #[derive(Clone, Debug, PartialEq, Eq)] pub enum LSPS1Message { /// An LSPS1 JSON-RPC request. - Request(RequestId, LSPS1Request), + Request(LSPSRequestId, LSPS1Request), /// An LSPS1 JSON-RPC response. - Response(RequestId, LSPS1Response), + Response(LSPSRequestId, LSPS1Response), } impl TryFrom for LSPS1Message { diff --git a/lightning-liquidity/src/lsps1/service.rs b/lightning-liquidity/src/lsps1/service.rs index b51721eb506..836bebed500 100644 --- a/lightning-liquidity/src/lsps1/service.rs +++ b/lightning-liquidity/src/lsps1/service.rs @@ -19,7 +19,7 @@ use super::msgs::{ use crate::message_queue::MessageQueue; use crate::events::EventQueue; -use crate::lsps0::ser::{ProtocolMessageHandler, RequestId, ResponseError}; +use crate::lsps0::ser::{LSPSProtocolMessageHandler, LSPSRequestId, LSPSResponseError}; use crate::prelude::{new_hash_map, HashMap, String}; use crate::sync::{Arc, Mutex, RwLock}; use crate::utils; @@ -107,8 +107,8 @@ impl OutboundCRChannel { #[derive(Default)] struct PeerState { outbound_channels_by_order_id: HashMap, - request_to_cid: HashMap, - pending_requests: HashMap, + request_to_cid: HashMap, + pending_requests: HashMap, } impl PeerState { @@ -116,7 +116,7 @@ impl PeerState { self.outbound_channels_by_order_id.insert(order_id, channel); } - fn insert_request(&mut self, request_id: RequestId, channel_id: u128) { + fn insert_request(&mut self, request_id: LSPSRequestId, channel_id: u128) { self.request_to_cid.insert(request_id, channel_id); } @@ -165,7 +165,7 @@ where } fn handle_get_info_request( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, + &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, ) -> Result<(), LightningError> { let response = LSPS1Response::GetInfo(LSPS1GetInfoResponse { options: self @@ -185,11 +185,11 @@ where } fn handle_create_order_request( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, + &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, params: LSPS1CreateOrderRequest, ) -> Result<(), LightningError> { if !is_valid(¶ms.order, &self.config.supported_options.as_ref().unwrap()) { - let response = LSPS1Response::CreateOrderError(ResponseError { + let response = LSPS1Response::CreateOrderError(LSPSResponseError { code: LSPS1_CREATE_ORDER_REQUEST_ORDER_MISMATCH_ERROR_CODE, message: format!("Order does not match options supported by LSP server"), data: Some(format!( @@ -236,8 +236,8 @@ where /// /// [`LSPS1ServiceEvent::RequestForPaymentDetails`]: crate::lsps1::event::LSPS1ServiceEvent::RequestForPaymentDetails pub fn send_payment_details( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, payment: LSPS1PaymentInfo, - created_at: chrono::DateTime, + &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, + payment: LSPS1PaymentInfo, created_at: chrono::DateTime, ) -> Result<(), APIError> { let (result, response) = { let outer_state_lock = self.per_peer_state.read().unwrap(); @@ -302,7 +302,7 @@ where } fn handle_get_order_request( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, + &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, params: LSPS1GetOrderRequest, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.read().unwrap(); @@ -361,7 +361,7 @@ where /// /// [`LSPS1ServiceEvent::CheckPaymentConfirmation`]: crate::lsps1::event::LSPS1ServiceEvent::CheckPaymentConfirmation pub fn update_order_status( - &self, request_id: RequestId, counterparty_node_id: PublicKey, order_id: LSPS1OrderId, + &self, request_id: LSPSRequestId, counterparty_node_id: PublicKey, order_id: LSPS1OrderId, order_state: LSPS1OrderState, channel: Option, ) -> Result<(), APIError> { let (result, response) = { @@ -420,7 +420,7 @@ where } } -impl ProtocolMessageHandler +impl LSPSProtocolMessageHandler for LSPS1ServiceHandler where ES::Target: EntropySource, diff --git a/lightning-liquidity/src/lsps2/client.rs b/lightning-liquidity/src/lsps2/client.rs index f0157b139bf..f822e119a58 100644 --- a/lightning-liquidity/src/lsps2/client.rs +++ b/lightning-liquidity/src/lsps2/client.rs @@ -9,7 +9,7 @@ //! Contains the main bLIP-52 / LSPS2 client object, [`LSPS2ClientHandler`]. use crate::events::EventQueue; -use crate::lsps0::ser::{ProtocolMessageHandler, RequestId, ResponseError}; +use crate::lsps0::ser::{LSPSProtocolMessageHandler, LSPSRequestId, LSPSResponseError}; use crate::lsps2::event::LSPS2ClientEvent; use crate::message_queue::MessageQueue; use crate::prelude::{new_hash_map, new_hash_set, HashMap, HashSet, String, ToString}; @@ -45,8 +45,8 @@ impl InboundJITChannel { } struct PeerState { - pending_get_info_requests: HashSet, - pending_buy_requests: HashMap, + pending_get_info_requests: HashSet, + pending_buy_requests: HashMap, } impl PeerState { @@ -105,12 +105,12 @@ 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. /// - /// Returns the used [`RequestId`], which will be returned via [`OpeningParametersReady`]. + /// Returns the used [`LSPSRequestId`], which will be returned via [`OpeningParametersReady`]. /// /// [`OpeningParametersReady`]: crate::lsps2::event::LSPS2ClientEvent::OpeningParametersReady pub fn request_opening_params( &self, counterparty_node_id: PublicKey, token: Option, - ) -> RequestId { + ) -> LSPSRequestId { let request_id = crate::utils::generate_request_id(&self.entropy_source); { @@ -150,7 +150,7 @@ where pub fn select_opening_params( &self, counterparty_node_id: PublicKey, payment_size_msat: Option, opening_fee_params: LSPS2OpeningFeeParams, - ) -> Result { + ) -> Result { let request_id = crate::utils::generate_request_id(&self.entropy_source); { @@ -181,7 +181,7 @@ where } fn handle_get_info_response( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, + &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, result: LSPS2GetInfoResponse, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.read().unwrap(); @@ -220,7 +220,8 @@ where } fn handle_get_info_error( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, _error: ResponseError, + &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, + _error: LSPSResponseError, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.read().unwrap(); match outer_state_lock.get(counterparty_node_id) { @@ -246,7 +247,8 @@ where } fn handle_buy_response( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, result: LSPS2BuyResponse, + &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, + result: LSPS2BuyResponse, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.read().unwrap(); match outer_state_lock.get(counterparty_node_id) { @@ -294,7 +296,8 @@ where } fn handle_buy_error( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, _error: ResponseError, + &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, + _error: LSPSResponseError, ) -> Result<(), LightningError> { let outer_state_lock = self.per_peer_state.read().unwrap(); match outer_state_lock.get(counterparty_node_id) { @@ -315,7 +318,7 @@ where } } -impl ProtocolMessageHandler for LSPS2ClientHandler +impl LSPSProtocolMessageHandler for LSPS2ClientHandler where ES::Target: EntropySource, { diff --git a/lightning-liquidity/src/lsps2/event.rs b/lightning-liquidity/src/lsps2/event.rs index 41dcb9c7433..6ae09a417b7 100644 --- a/lightning-liquidity/src/lsps2/event.rs +++ b/lightning-liquidity/src/lsps2/event.rs @@ -10,7 +10,7 @@ //! Contains bLIP-52 / LSPS2 event types use super::msgs::LSPS2OpeningFeeParams; -use crate::lsps0::ser::RequestId; +use crate::lsps0::ser::LSPSRequestId; use crate::prelude::{String, Vec}; use bitcoin::secp256k1::PublicKey; @@ -31,7 +31,7 @@ pub enum LSPS2ClientEvent { /// This can be used to track which request this event corresponds to. /// /// [`LSPS2ClientHandler::request_opening_params`]: crate::lsps2::client::LSPS2ClientHandler::request_opening_params - request_id: RequestId, + request_id: LSPSRequestId, /// The node id of the LSP that provided this response. counterparty_node_id: PublicKey, /// The menu of fee parameters the LSP is offering at this time. @@ -50,7 +50,7 @@ pub enum LSPS2ClientEvent { /// This can be used to track which request this event corresponds to. /// /// [`LSPS2ClientHandler::select_opening_params`]: crate::lsps2::client::LSPS2ClientHandler::select_opening_params - request_id: RequestId, + request_id: LSPSRequestId, /// The node id of the LSP. counterparty_node_id: PublicKey, /// The intercept short channel id to use in the route hint. @@ -79,7 +79,7 @@ pub enum LSPS2ServiceEvent { /// An identifier that must be passed to [`LSPS2ServiceHandler::opening_fee_params_generated`]. /// /// [`LSPS2ServiceHandler::opening_fee_params_generated`]: crate::lsps2::service::LSPS2ServiceHandler::opening_fee_params_generated - request_id: RequestId, + request_id: LSPSRequestId, /// The node id of the client making the information request. counterparty_node_id: PublicKey, /// An optional token that can be used as an API key, coupon code, etc. @@ -99,7 +99,7 @@ pub enum LSPS2ServiceEvent { /// An identifier that must be passed into [`LSPS2ServiceHandler::invoice_parameters_generated`]. /// /// [`LSPS2ServiceHandler::invoice_parameters_generated`]: crate::lsps2::service::LSPS2ServiceHandler::invoice_parameters_generated - request_id: RequestId, + request_id: LSPSRequestId, /// The client node id that is making this request. counterparty_node_id: PublicKey, /// The channel parameters they have selected. diff --git a/lightning-liquidity/src/lsps2/msgs.rs b/lightning-liquidity/src/lsps2/msgs.rs index ab8114c38cc..3df9e0212ed 100644 --- a/lightning-liquidity/src/lsps2/msgs.rs +++ b/lightning-liquidity/src/lsps2/msgs.rs @@ -11,7 +11,7 @@ use serde::{Deserialize, Serialize}; use lightning::util::scid_utils; use crate::lsps0::ser::{ - string_amount, string_amount_option, LSPSMessage, RequestId, ResponseError, + string_amount, string_amount_option, LSPSMessage, LSPSRequestId, LSPSResponseError, }; use crate::prelude::{String, Vec}; use crate::utils; @@ -177,20 +177,20 @@ pub enum LSPS2Response { /// A successful response to a [`LSPS2Request::GetInfo`] request. GetInfo(LSPS2GetInfoResponse), /// An error response to a [`LSPS2Request::GetInfo`] request. - GetInfoError(ResponseError), + GetInfoError(LSPSResponseError), /// A successful response to a [`LSPS2Request::Buy`] request. Buy(LSPS2BuyResponse), /// An error response to a [`LSPS2Request::Buy`] request. - BuyError(ResponseError), + BuyError(LSPSResponseError), } #[derive(Clone, Debug, PartialEq, Eq)] /// An enum that captures all valid JSON-RPC messages in the bLIP-52 / LSPS2 protocol. pub enum LSPS2Message { /// An LSPS2 JSON-RPC request. - Request(RequestId, LSPS2Request), + Request(LSPSRequestId, LSPS2Request), /// An LSPS2 JSON-RPC response. - Response(RequestId, LSPS2Response), + Response(LSPSRequestId, LSPS2Response), } impl TryFrom for LSPS2Message { diff --git a/lightning-liquidity/src/lsps2/service.rs b/lightning-liquidity/src/lsps2/service.rs index 3b53fe42f1a..60b6c499ed6 100644 --- a/lightning-liquidity/src/lsps2/service.rs +++ b/lightning-liquidity/src/lsps2/service.rs @@ -11,7 +11,7 @@ use crate::events::EventQueue; use crate::lsps0::ser::{ - LSPSMessage, ProtocolMessageHandler, RequestId, ResponseError, + LSPSMessage, LSPSProtocolMessageHandler, LSPSRequestId, LSPSResponseError, JSONRPC_INTERNAL_ERROR_ERROR_CODE, JSONRPC_INTERNAL_ERROR_ERROR_MESSAGE, LSPS0_CLIENT_REJECTED_ERROR_CODE, }; @@ -457,7 +457,7 @@ struct PeerState { outbound_channels_by_intercept_scid: HashMap, intercept_scid_by_user_channel_id: HashMap, intercept_scid_by_channel_id: HashMap, - pending_requests: HashMap, + pending_requests: HashMap, } impl PeerState { @@ -523,7 +523,7 @@ macro_rules! get_or_insert_peer_state_entry { match $outer_state_lock.entry(*$counterparty_node_id) { Entry::Vacant(e) => { if is_limited_by_max_total_peers { - let error_response = ResponseError { + let error_response = LSPSResponseError { code: JSONRPC_INTERNAL_ERROR_ERROR_CODE, message: JSONRPC_INTERNAL_ERROR_ERROR_MESSAGE.to_string(), data: None, }; @@ -592,7 +592,7 @@ where /// /// [`LSPS2ServiceEvent::GetInfo`]: crate::lsps2::event::LSPS2ServiceEvent::GetInfo pub fn invalid_token_provided( - &self, counterparty_node_id: &PublicKey, request_id: RequestId, + &self, counterparty_node_id: &PublicKey, request_id: LSPSRequestId, ) -> Result<(), APIError> { let (result, response) = { let outer_state_lock = self.per_peer_state.read().unwrap(); @@ -603,7 +603,7 @@ where match self.remove_pending_request(&mut peer_state_lock, &request_id) { Some(LSPS2Request::GetInfo(_)) => { - let response = LSPS2Response::GetInfoError(ResponseError { + let response = LSPS2Response::GetInfoError(LSPSResponseError { code: LSPS2_GET_INFO_REQUEST_UNRECOGNIZED_OR_STALE_TOKEN_ERROR_CODE, message: "an unrecognized or stale token was provided".to_string(), data: None, @@ -647,7 +647,7 @@ where /// /// [`LSPS2ServiceEvent::GetInfo`]: crate::lsps2::event::LSPS2ServiceEvent::GetInfo pub fn opening_fee_params_generated( - &self, counterparty_node_id: &PublicKey, request_id: RequestId, + &self, counterparty_node_id: &PublicKey, request_id: LSPSRequestId, opening_fee_params_menu: Vec, ) -> Result<(), APIError> { let (result, response) = { @@ -706,7 +706,7 @@ where /// /// [`LSPS2ServiceEvent::BuyRequest`]: crate::lsps2::event::LSPS2ServiceEvent::BuyRequest pub fn invoice_parameters_generated( - &self, counterparty_node_id: &PublicKey, request_id: RequestId, intercept_scid: u64, + &self, counterparty_node_id: &PublicKey, request_id: LSPSRequestId, intercept_scid: u64, cltv_expiry_delta: u32, client_trusts_lsp: bool, user_channel_id: u128, ) -> Result<(), APIError> { let (result, response) = { @@ -1077,7 +1077,8 @@ where } fn handle_get_info_request( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, params: LSPS2GetInfoRequest, + &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, + params: LSPS2GetInfoRequest, ) -> Result<(), LightningError> { let (result, response) = { let mut outer_state_lock = self.per_peer_state.write().unwrap(); @@ -1113,11 +1114,11 @@ where } fn handle_buy_request( - &self, request_id: RequestId, counterparty_node_id: &PublicKey, params: LSPS2BuyRequest, + &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, params: LSPS2BuyRequest, ) -> Result<(), LightningError> { if let Some(payment_size_msat) = params.payment_size_msat { if payment_size_msat < params.opening_fee_params.min_payment_size_msat { - let response = LSPS2Response::BuyError(ResponseError { + let response = LSPS2Response::BuyError(LSPSResponseError { code: LSPS2_BUY_REQUEST_PAYMENT_SIZE_TOO_SMALL_ERROR_CODE, message: "payment size is below our minimum supported payment size".to_string(), data: None, @@ -1132,7 +1133,7 @@ where } if payment_size_msat > params.opening_fee_params.max_payment_size_msat { - let response = LSPS2Response::BuyError(ResponseError { + let response = LSPS2Response::BuyError(LSPSResponseError { code: LSPS2_BUY_REQUEST_PAYMENT_SIZE_TOO_LARGE_ERROR_CODE, message: "payment size is above our maximum supported payment size".to_string(), data: None, @@ -1152,7 +1153,7 @@ where ) { Some(opening_fee) => { if opening_fee >= payment_size_msat { - let response = LSPS2Response::BuyError(ResponseError { + let response = LSPS2Response::BuyError(LSPSResponseError { code: LSPS2_BUY_REQUEST_PAYMENT_SIZE_TOO_SMALL_ERROR_CODE, message: "payment size is too small to cover the opening fee" .to_string(), @@ -1167,7 +1168,7 @@ where } }, None => { - let response = LSPS2Response::BuyError(ResponseError { + let response = LSPS2Response::BuyError(LSPSResponseError { code: LSPS2_BUY_REQUEST_PAYMENT_SIZE_TOO_LARGE_ERROR_CODE, message: "overflow error when calculating opening_fee".to_string(), data: None, @@ -1184,7 +1185,7 @@ where // TODO: if payment_size_msat is specified, make sure our node has sufficient incoming liquidity from public network to receive it. if !is_valid_opening_fee_params(¶ms.opening_fee_params, &self.config.promise_secret) { - let response = LSPS2Response::BuyError(ResponseError { + let response = LSPS2Response::BuyError(LSPSResponseError { code: LSPS2_BUY_REQUEST_INVALID_OPENING_FEE_PARAMS_ERROR_CODE, message: "valid_until is already past OR the promise did not match the provided parameters".to_string(), data: None, @@ -1233,11 +1234,11 @@ where } fn insert_pending_request<'a>( - &self, peer_state_lock: &mut MutexGuard<'a, PeerState>, request_id: RequestId, + &self, peer_state_lock: &mut MutexGuard<'a, PeerState>, request_id: LSPSRequestId, counterparty_node_id: PublicKey, request: LSPS2Request, ) -> (Result<(), LightningError>, Option) { if self.total_pending_requests.load(Ordering::Relaxed) >= MAX_TOTAL_PENDING_REQUESTS { - let response = LSPS2Response::BuyError(ResponseError { + let response = LSPS2Response::BuyError(LSPSResponseError { code: LSPS0_CLIENT_REJECTED_ERROR_CODE, message: "Reached maximum number of pending requests. Please try again later." .to_string(), @@ -1259,7 +1260,7 @@ where self.total_pending_requests.fetch_add(1, Ordering::Relaxed); (Ok(()), None) } else { - let response = LSPS2Response::BuyError(ResponseError { + let response = LSPS2Response::BuyError(LSPSResponseError { code: LSPS0_CLIENT_REJECTED_ERROR_CODE, message: "Reached maximum number of pending requests. Please try again later." .to_string(), @@ -1279,7 +1280,7 @@ where } fn remove_pending_request<'a>( - &self, peer_state_lock: &mut MutexGuard<'a, PeerState>, request_id: &RequestId, + &self, peer_state_lock: &mut MutexGuard<'a, PeerState>, request_id: &LSPSRequestId, ) -> Option { match peer_state_lock.pending_requests.remove(request_id) { Some(req) => { @@ -1346,7 +1347,7 @@ where } } -impl ProtocolMessageHandler for LSPS2ServiceHandler +impl LSPSProtocolMessageHandler for LSPS2ServiceHandler where CM::Target: AChannelManager, { diff --git a/lightning-liquidity/src/manager.rs b/lightning-liquidity/src/manager.rs index 31d7c2d354c..afaac25cdd2 100644 --- a/lightning-liquidity/src/manager.rs +++ b/lightning-liquidity/src/manager.rs @@ -2,8 +2,8 @@ use crate::events::{EventQueue, LiquidityEvent}; use crate::lsps0::client::LSPS0ClientHandler; use crate::lsps0::msgs::LSPS0Message; use crate::lsps0::ser::{ - LSPSMessage, LSPSMethod, ProtocolMessageHandler, RawLSPSMessage, RequestId, ResponseError, - JSONRPC_INVALID_MESSAGE_ERROR_CODE, JSONRPC_INVALID_MESSAGE_ERROR_MESSAGE, + LSPSMessage, LSPSMethod, LSPSProtocolMessageHandler, LSPSRequestId, LSPSResponseError, + RawLSPSMessage, JSONRPC_INVALID_MESSAGE_ERROR_CODE, JSONRPC_INVALID_MESSAGE_ERROR_MESSAGE, LSPS_MESSAGE_TYPE_ID, }; use crate::lsps0::service::LSPS0ServiceHandler; @@ -95,7 +95,7 @@ where { pending_messages: Arc, pending_events: Arc, - request_id_to_method_map: Mutex>, + request_id_to_method_map: Mutex>, // We ignore peers if they send us bogus data. ignored_peers: RwLock>, lsps0_client_handler: LSPS0ClientHandler, @@ -146,7 +146,7 @@ where { let lsps2_service_handler = service_config.as_ref().and_then(|config| { config.lsps2_service_config.as_ref().map(|config| { if let Some(number) = - as ProtocolMessageHandler>::PROTOCOL_NUMBER + as LSPSProtocolMessageHandler>::PROTOCOL_NUMBER { supported_protocols.push(number); } @@ -173,7 +173,7 @@ where { #[cfg(lsps1_service)] let lsps1_service_handler = service_config.as_ref().and_then(|config| { if let Some(number) = - as ProtocolMessageHandler>::PROTOCOL_NUMBER + as LSPSProtocolMessageHandler>::PROTOCOL_NUMBER { supported_protocols.push(number); } @@ -485,7 +485,7 @@ where LSPSMessage::from_str_with_id_map(&msg.payload, &mut request_id_to_method_map) } .map_err(|_| { - let error = ResponseError { + let error = LSPSResponseError { code: JSONRPC_INVALID_MESSAGE_ERROR_CODE, message: JSONRPC_INVALID_MESSAGE_ERROR_MESSAGE.to_string(), data: None, diff --git a/lightning-liquidity/src/utils.rs b/lightning-liquidity/src/utils.rs index e355c72eb65..8f961e72632 100644 --- a/lightning-liquidity/src/utils.rs +++ b/lightning-liquidity/src/utils.rs @@ -1,7 +1,7 @@ use core::{fmt::Write, ops::Deref}; use lightning::sign::EntropySource; -use crate::lsps0::ser::RequestId; +use crate::lsps0::ser::LSPSRequestId; use crate::prelude::String; pub fn scid_from_human_readable_string(human_readable_scid: &str) -> Result { @@ -14,12 +14,12 @@ pub fn scid_from_human_readable_string(human_readable_scid: &str) -> Result(entropy_source: &ES) -> RequestId +pub(crate) fn generate_request_id(entropy_source: &ES) -> LSPSRequestId where ES::Target: EntropySource, { let bytes = entropy_source.get_secure_random_bytes(); - RequestId(hex_str(&bytes[0..16])) + LSPSRequestId(hex_str(&bytes[0..16])) } #[inline] From 690fcb15450f729900fdd803ab1c8e2fc5c4b86d Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Thu, 9 Jan 2025 11:09:46 +0100 Subject: [PATCH 9/9] Introduce `LSPSDateTime` wrapper This wrapper is more ergonomic to use in the local context and will be used as a serialization wrapper in following commits. --- lightning-liquidity/src/lsps0/ser.rs | 43 ++++++++++++++++++- lightning-liquidity/src/lsps1/msgs.rs | 16 +++---- lightning-liquidity/src/lsps1/service.rs | 12 +++--- lightning-liquidity/src/lsps2/msgs.rs | 30 +++++++------ lightning-liquidity/src/lsps2/service.rs | 12 +++--- lightning-liquidity/src/lsps2/utils.rs | 14 +----- .../tests/lsps2_integration_tests.rs | 6 +-- 7 files changed, 83 insertions(+), 50 deletions(-) diff --git a/lightning-liquidity/src/lsps0/ser.rs b/lightning-liquidity/src/lsps0/ser.rs index e97a015802e..a0cb6bfb143 100644 --- a/lightning-liquidity/src/lsps0/ser.rs +++ b/lightning-liquidity/src/lsps0/ser.rs @@ -24,9 +24,12 @@ use lightning::util::ser::WithoutLength; use bitcoin::secp256k1::PublicKey; -use core::fmt; +use core::fmt::{self, Display}; use core::str::FromStr; +#[cfg(feature = "std")] +use std::time::{SystemTime, UNIX_EPOCH}; + use serde::de::{self, MapAccess, Visitor}; use serde::ser::SerializeStruct; use serde::{Deserialize, Deserializer, Serialize}; @@ -186,6 +189,44 @@ impl wire::Type for RawLSPSMessage { #[serde(transparent)] pub struct LSPSRequestId(pub String); +/// An object representing datetimes as described in bLIP-50 / LSPS0. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)] +#[serde(transparent)] +pub struct LSPSDateTime(chrono::DateTime); + +impl LSPSDateTime { + /// Returns the LSPSDateTime as RFC3339 formatted string. + pub fn to_rfc3339(&self) -> String { + self.0.to_rfc3339() + } + + /// Returns if the given time is in the past. + #[cfg(feature = "std")] + pub fn is_past(&self) -> bool { + let now_seconds_since_epoch = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock to be ahead of the unix epoch") + .as_secs(); + let datetime_seconds_since_epoch = + self.0.timestamp().try_into().expect("expiration to be ahead of unix epoch"); + now_seconds_since_epoch > datetime_seconds_since_epoch + } +} + +impl FromStr for LSPSDateTime { + type Err = (); + fn from_str(s: &str) -> Result { + let datetime = chrono::DateTime::parse_from_rfc3339(s).map_err(|_| ())?; + Ok(Self(datetime.into())) + } +} + +impl Display for LSPSDateTime { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.to_rfc3339()) + } +} + /// An error returned in response to an JSON-RPC request. /// /// Please refer to the [JSON-RPC 2.0 specification](https://www.jsonrpc.org/specification#error_object) for diff --git a/lightning-liquidity/src/lsps1/msgs.rs b/lightning-liquidity/src/lsps1/msgs.rs index 86c63e71048..c3bcc46cf05 100644 --- a/lightning-liquidity/src/lsps1/msgs.rs +++ b/lightning-liquidity/src/lsps1/msgs.rs @@ -1,8 +1,8 @@ //! Message, request, and other primitive types used to implement bLIP-51 / LSPS1. use crate::lsps0::ser::{ - string_amount, u32_fee_rate, unchecked_address, unchecked_address_option, LSPSMessage, - LSPSRequestId, LSPSResponseError, + string_amount, u32_fee_rate, unchecked_address, unchecked_address_option, LSPSDateTime, + LSPSMessage, LSPSRequestId, LSPSResponseError, }; use crate::prelude::String; @@ -13,8 +13,6 @@ use lightning_invoice::Bolt11Invoice; use serde::{Deserialize, Serialize}; -use chrono::Utc; - use core::convert::TryFrom; pub(crate) const LSPS1_GET_INFO_METHOD_NAME: &str = "lsps1.get_info"; @@ -127,7 +125,7 @@ pub struct LSPS1CreateOrderResponse { #[serde(flatten)] pub order: LSPS1OrderParams, /// The datetime when the order was created - pub created_at: chrono::DateTime, + pub created_at: LSPSDateTime, /// The current state of the order. pub order_state: LSPS1OrderState, /// Contains details about how to pay for the order. @@ -163,7 +161,7 @@ pub struct LSPS1Bolt11PaymentInfo { /// Indicates the current state of the payment. pub state: LSPS1PaymentState, /// The datetime when the payment option expires. - pub expires_at: chrono::DateTime, + pub expires_at: LSPSDateTime, /// The total fee the LSP will charge to open this channel in satoshi. #[serde(with = "string_amount")] pub fee_total_sat: u64, @@ -180,7 +178,7 @@ pub struct LSPS1OnchainPaymentInfo { /// Indicates the current state of the payment. pub state: LSPS1PaymentState, /// The datetime when the payment option expires. - pub expires_at: chrono::DateTime, + pub expires_at: LSPSDateTime, /// The total fee the LSP will charge to open this channel in satoshi. #[serde(with = "string_amount")] pub fee_total_sat: u64, @@ -237,11 +235,11 @@ pub struct LSPS1OnchainPayment { #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct LSPS1ChannelInfo { /// The datetime when the funding transaction has been published. - pub funded_at: chrono::DateTime, + pub funded_at: LSPSDateTime, /// The outpoint of the funding transaction. pub funding_outpoint: OutPoint, /// The earliest datetime when the channel may be closed by the LSP. - pub expires_at: chrono::DateTime, + pub expires_at: LSPSDateTime, } /// A request made to an LSP to retrieve information about an previously made order. diff --git a/lightning-liquidity/src/lsps1/service.rs b/lightning-liquidity/src/lsps1/service.rs index 836bebed500..998e4823215 100644 --- a/lightning-liquidity/src/lsps1/service.rs +++ b/lightning-liquidity/src/lsps1/service.rs @@ -19,7 +19,9 @@ use super::msgs::{ use crate::message_queue::MessageQueue; use crate::events::EventQueue; -use crate::lsps0::ser::{LSPSProtocolMessageHandler, LSPSRequestId, LSPSResponseError}; +use crate::lsps0::ser::{ + LSPSDateTime, LSPSProtocolMessageHandler, LSPSRequestId, LSPSResponseError, +}; use crate::prelude::{new_hash_map, HashMap, String}; use crate::sync::{Arc, Mutex, RwLock}; use crate::utils; @@ -73,7 +75,7 @@ impl OutboundRequestState { struct OutboundLSPS1Config { order: LSPS1OrderParams, - created_at: chrono::DateTime, + created_at: LSPSDateTime, payment: LSPS1PaymentInfo, } @@ -84,7 +86,7 @@ struct OutboundCRChannel { impl OutboundCRChannel { fn new( - order: LSPS1OrderParams, created_at: chrono::DateTime, order_id: LSPS1OrderId, + order: LSPS1OrderParams, created_at: LSPSDateTime, order_id: LSPS1OrderId, payment: LSPS1PaymentInfo, ) -> Self { Self { @@ -237,7 +239,7 @@ where /// [`LSPS1ServiceEvent::RequestForPaymentDetails`]: crate::lsps1::event::LSPS1ServiceEvent::RequestForPaymentDetails pub fn send_payment_details( &self, request_id: LSPSRequestId, counterparty_node_id: &PublicKey, - payment: LSPS1PaymentInfo, created_at: chrono::DateTime, + payment: LSPS1PaymentInfo, created_at: LSPSDateTime, ) -> Result<(), APIError> { let (result, response) = { let outer_state_lock = self.per_peer_state.read().unwrap(); @@ -380,7 +382,7 @@ where order_id, order: config.order.clone(), order_state, - created_at: config.created_at, + created_at: config.created_at.clone(), payment: config.payment.clone(), channel, }); diff --git a/lightning-liquidity/src/lsps2/msgs.rs b/lightning-liquidity/src/lsps2/msgs.rs index 3df9e0212ed..9812f4d7338 100644 --- a/lightning-liquidity/src/lsps2/msgs.rs +++ b/lightning-liquidity/src/lsps2/msgs.rs @@ -5,13 +5,13 @@ use core::convert::TryFrom; use bitcoin::hashes::hmac::{Hmac, HmacEngine}; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::{Hash, HashEngine}; -use chrono::Utc; use serde::{Deserialize, Serialize}; use lightning::util::scid_utils; use crate::lsps0::ser::{ - string_amount, string_amount_option, LSPSMessage, LSPSRequestId, LSPSResponseError, + string_amount, string_amount_option, LSPSDateTime, LSPSMessage, LSPSRequestId, + LSPSResponseError, }; use crate::prelude::{String, Vec}; use crate::utils; @@ -42,7 +42,7 @@ pub struct LSPS2RawOpeningFeeParams { /// A fee proportional to the size of the initial payment. pub proportional: u32, /// An [`ISO8601`](https://www.iso.org/iso-8601-date-and-time-format.html) formatted date for which these params are valid. - pub valid_until: chrono::DateTime, + pub valid_until: LSPSDateTime, /// The number of blocks after confirmation that the LSP promises it will keep the channel alive without closing. pub min_lifetime: u32, /// The maximum number of blocks that the client is allowed to set its `to_self_delay` parameter. @@ -93,7 +93,7 @@ pub struct LSPS2OpeningFeeParams { /// A fee proportional to the size of the initial payment. pub proportional: u32, /// An [`ISO8601`](https://www.iso.org/iso-8601-date-and-time-format.html) formatted date for which these params are valid. - pub valid_until: chrono::DateTime, + pub valid_until: LSPSDateTime, /// The number of blocks after confirmation that the LSP promises it will keep the channel alive without closing. pub min_lifetime: u32, /// The maximum number of blocks that the client is allowed to set its `to_self_delay` parameter. @@ -214,15 +214,17 @@ impl From for LSPSMessage { #[cfg(test)] mod tests { use super::*; + use crate::alloc::string::ToString; use crate::lsps2::utils::is_valid_opening_fee_params; + use core::str::FromStr; + #[test] fn into_opening_fee_params_produces_valid_promise() { let min_fee_msat = 100; let proportional = 21; - let valid_until: chrono::DateTime = - chrono::DateTime::parse_from_rfc3339("2035-05-20T08:30:45Z").unwrap().into(); + let valid_until = LSPSDateTime::from_str("2035-05-20T08:30:45Z").unwrap(); let min_lifetime = 144; let max_client_to_self_delay = 128; let min_payment_size_msat = 1; @@ -257,7 +259,7 @@ mod tests { fn changing_single_field_produced_invalid_params() { let min_fee_msat = 100; let proportional = 21; - let valid_until = chrono::DateTime::parse_from_rfc3339("2035-05-20T08:30:45Z").unwrap(); + let valid_until = LSPSDateTime::from_str("2035-05-20T08:30:45Z").unwrap(); let min_lifetime = 144; let max_client_to_self_delay = 128; let min_payment_size_msat = 1; @@ -266,7 +268,7 @@ mod tests { let raw = LSPS2RawOpeningFeeParams { min_fee_msat, proportional, - valid_until: valid_until.into(), + valid_until, min_lifetime, max_client_to_self_delay, min_payment_size_msat, @@ -284,7 +286,7 @@ mod tests { fn wrong_secret_produced_invalid_params() { let min_fee_msat = 100; let proportional = 21; - let valid_until = chrono::DateTime::parse_from_rfc3339("2035-05-20T08:30:45Z").unwrap(); + let valid_until = LSPSDateTime::from_str("2035-05-20T08:30:45Z").unwrap(); let min_lifetime = 144; let max_client_to_self_delay = 128; let min_payment_size_msat = 1; @@ -293,7 +295,7 @@ mod tests { let raw = LSPS2RawOpeningFeeParams { min_fee_msat, proportional, - valid_until: valid_until.into(), + valid_until, min_lifetime, max_client_to_self_delay, min_payment_size_msat, @@ -313,7 +315,7 @@ mod tests { fn expired_params_produces_invalid_params() { let min_fee_msat = 100; let proportional = 21; - let valid_until = chrono::DateTime::parse_from_rfc3339("2023-05-20T08:30:45Z").unwrap(); + let valid_until = LSPSDateTime::from_str("2023-05-20T08:30:45Z").unwrap(); let min_lifetime = 144; let max_client_to_self_delay = 128; let min_payment_size_msat = 1; @@ -322,7 +324,7 @@ mod tests { let raw = LSPS2RawOpeningFeeParams { min_fee_msat, proportional, - valid_until: valid_until.into(), + valid_until, min_lifetime, max_client_to_self_delay, min_payment_size_msat, @@ -339,7 +341,7 @@ mod tests { fn buy_request_serialization() { let min_fee_msat = 100; let proportional = 21; - let valid_until = chrono::DateTime::parse_from_rfc3339("2023-05-20T08:30:45Z").unwrap(); + let valid_until = LSPSDateTime::from_str("2023-05-20T08:30:45Z").unwrap(); let min_lifetime = 144; let max_client_to_self_delay = 128; let min_payment_size_msat = 1; @@ -348,7 +350,7 @@ mod tests { let raw = LSPS2RawOpeningFeeParams { min_fee_msat, proportional, - valid_until: valid_until.into(), + valid_until, min_lifetime, max_client_to_self_delay, min_payment_size_msat, diff --git a/lightning-liquidity/src/lsps2/service.rs b/lightning-liquidity/src/lsps2/service.rs index 60b6c499ed6..896cd9ae39e 100644 --- a/lightning-liquidity/src/lsps2/service.rs +++ b/lightning-liquidity/src/lsps2/service.rs @@ -1419,12 +1419,14 @@ fn calculate_amount_to_forward_per_htlc( #[cfg(test)] mod tests { - use super::*; - use chrono::TimeZone; - use chrono::Utc; + + use crate::lsps0::ser::LSPSDateTime; + use proptest::prelude::*; + use core::str::FromStr; + const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000; fn arb_forward_amounts() -> impl Strategy { @@ -1518,7 +1520,7 @@ mod tests { let opening_fee_params = LSPS2OpeningFeeParams { min_fee_msat: 10_000_000, proportional: 10_000, - valid_until: Utc.timestamp_opt(3000, 0).unwrap(), + valid_until: LSPSDateTime::from_str("2035-05-20T08:30:45Z").unwrap(), min_lifetime: 4032, max_client_to_self_delay: 2016, min_payment_size_msat: 10_000_000, @@ -1710,7 +1712,7 @@ mod tests { let opening_fee_params = LSPS2OpeningFeeParams { min_fee_msat: 10_000_000, proportional: 10_000, - valid_until: Utc.timestamp_opt(3000, 0).unwrap(), + valid_until: LSPSDateTime::from_str("2035-05-20T08:30:45Z").unwrap(), min_lifetime: 4032, max_client_to_self_delay: 2016, min_payment_size_msat: 10_000_000, diff --git a/lightning-liquidity/src/lsps2/utils.rs b/lightning-liquidity/src/lsps2/utils.rs index c3eb82ae0d7..76ceeb8f60b 100644 --- a/lightning-liquidity/src/lsps2/utils.rs +++ b/lightning-liquidity/src/lsps2/utils.rs @@ -7,9 +7,6 @@ use bitcoin::hashes::hmac::{Hmac, HmacEngine}; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::{Hash, HashEngine}; -#[cfg(feature = "std")] -use std::time::{SystemTime, UNIX_EPOCH}; - /// Determines if the given parameters are valid given the secret used to generate the promise. pub fn is_valid_opening_fee_params( fee_params: &LSPS2OpeningFeeParams, promise_secret: &[u8; 32], @@ -35,16 +32,7 @@ pub fn is_valid_opening_fee_params( pub fn is_expired_opening_fee_params(fee_params: &LSPS2OpeningFeeParams) -> bool { #[cfg(feature = "std")] { - let seconds_since_epoch = SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("system clock to be ahead of the unix epoch") - .as_secs(); - let valid_until_seconds_since_epoch = fee_params - .valid_until - .timestamp() - .try_into() - .expect("expiration to be ahead of unix epoch"); - seconds_since_epoch > valid_until_seconds_since_epoch + fee_params.valid_until.is_past() } #[cfg(not(feature = "std"))] { diff --git a/lightning-liquidity/tests/lsps2_integration_tests.rs b/lightning-liquidity/tests/lsps2_integration_tests.rs index ed9b1bf94ef..5a3f88dacac 100644 --- a/lightning-liquidity/tests/lsps2_integration_tests.rs +++ b/lightning-liquidity/tests/lsps2_integration_tests.rs @@ -5,6 +5,7 @@ mod common; use common::{create_service_and_client_nodes, get_lsps_message, Node}; use lightning_liquidity::events::LiquidityEvent; +use lightning_liquidity::lsps0::ser::LSPSDateTime; use lightning_liquidity::lsps2::client::LSPS2ClientConfig; use lightning_liquidity::lsps2::event::{LSPS2ClientEvent, LSPS2ServiceEvent}; use lightning_liquidity::lsps2::msgs::LSPS2RawOpeningFeeParams; @@ -24,8 +25,7 @@ use bitcoin::hashes::{sha256, Hash}; use bitcoin::secp256k1::{PublicKey, Secp256k1}; use bitcoin::Network; -use chrono::DateTime; - +use std::str::FromStr; use std::time::Duration; fn create_jit_invoice( @@ -128,7 +128,7 @@ fn invoice_generation_flow() { let raw_opening_params = LSPS2RawOpeningFeeParams { min_fee_msat: 100, proportional: 21, - valid_until: DateTime::parse_from_rfc3339("2035-05-20T08:30:45Z").unwrap().into(), + valid_until: LSPSDateTime::from_str("2035-05-20T08:30:45Z").unwrap(), min_lifetime: 144, max_client_to_self_delay: 128, min_payment_size_msat: 1,