lsps-types: add LSPS2 messages and opening fee params
What changed, and why it matters
This commit is a routine code reorganization for the Core Lightning project. It moves data structures and helper functions related to the LSPS2 (Just-In-Time channel) protocol from one internal plugin file into a shared library module. It also adds validation helpers and one missing error code. There is no indication this fixes or introduces a security vulnerability; it is a structural refactor with tests.
No security action required. Review as normal code-quality refactor. If auditing, verify that the moved validation logic preserves the original error-code mapping and that the service plugin still performs HMAC promise verification before relying on these shared types.
Security signals we found
Refactor only: moves existing types/functions without changing their core behavior
Adds input-validation helpers for LSPS2 opening fee parameters
Adds missing bLIP-52 error code 200 (unrecognized_or_stale_token)
Keeps HMAC promise verification in the service plugin rather than exposing it in shared types
Includes unit tests for arithmetic overflow and boundary conditions
Evidence from the diff
The commit moves LSPS2 message types, OpeningFeeParams, Promise, and compute_opening_fee from plugins/lsps-plugin/src/proto/lsps2.rs into a new lsps-types crate. It splits the previous mixed validation logic: general LSP-side checks (expiry, fee overflow, fee vs payment size, min/max limits) are now in OpeningFeeParams::validate/check_limits/check_payment_size/is_expired_at, while the HMAC promise verification remains in the service plugin. It adds the UNRECOGNIZED_OR_STALE_TOKEN (200) error code from bLIP-52 and includes unit tests covering success, expiry, overflow, fee-too-large, limit checks, unknown-field rejection, and a spec example roundtrip. No runtime behavior changes are described beyond the refactor.
Changed components
lsps-types/src/lib.rslsps-types/src/lsps2/fee.rslsps-types/src/lsps2/mod.rslsps-types/src/lsps2/params.rslsps-types/src/lsps2/promise.rsInspect captured patch +570 / −0
### lsps-types/src/lib.rs
@@ -11,3 +11,4 @@
#[macro_use]
pub mod jsonrpc;
pub mod lsps0;
+pub mod lsps2;
### lsps-types/src/lsps2/fee.rs
@@ -0,0 +1,20 @@
+/// Computes the opening fee in millisatoshis as described in LSPS2.
+/// Returns None if an arithmetic overflow occurs during calculation.
+///
+/// # Arguments
+/// * `payment_size_msat` - The size of the payment for which the channel is
+/// being opened.
+/// * `opening_fee_min_fee_msat` - The minimum fee to be paid by the client to
+/// the LSP
+/// * `opening_fee_proportional` - The proportional fee charged by the LSP
+pub fn compute_opening_fee(
+ payment_size_msat: u64,
+ opening_fee_min_fee_msat: u64,
+ opening_fee_proportional: u64,
+) -> Option<u64> {
+ payment_size_msat
+ .checked_mul(opening_fee_proportional)
+ .and_then(|f| f.checked_add(999999))
+ .and_then(|f| f.checked_div(1000000))
+ .map(|f| std::cmp::max(f, opening_fee_min_fee_msat))
+}
### lsps-types/src/lsps2/mod.rs
@@ -0,0 +1,102 @@
+//! LSPS2 (bLIP-52): JIT channel negotiation messages, opening fee
+//! parameters and the opening fee computation.
+
+use crate::jsonrpc::{JsonRpcRequest, RpcError};
+use crate::lsps0::{Msat, ShortChannelId};
+use serde::{Deserialize, Serialize};
+
+mod fee;
+mod params;
+mod promise;
+
+pub use fee::compute_opening_fee;
+pub use params::{OpeningFeeParams, ValidationError};
+pub use promise::{Promise, PromiseError};
+
+// Lsps2 specific error codes defined in BLIP-52.
+// Are in the range 00200 to 00299.
+pub mod error_codes {
+ pub const UNRECOGNIZED_OR_STALE_TOKEN: i64 = 200;
+ pub const INVALID_OPENING_FEE_PARAMS: i64 = 201;
+ pub const PAYMENT_SIZE_TOO_SMALL: i64 = 202;
+ pub const PAYMENT_SIZE_TOO_LARGE: i64 = 203;
+}
+
+/// The `lsps2.buy` errors defined in bLIP-52.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Error {
+ InvalidOpeningFeeParams,
+ PaymentSizeTooSmall,
+ PaymentSizeTooLarge,
+}
+
+impl core::fmt::Display for Error {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let err_str = match self {
+ Error::InvalidOpeningFeeParams => "Invalid opening fee params",
+ Error::PaymentSizeTooSmall => "Payment size too small",
+ Error::PaymentSizeTooLarge => "Payment size too large",
+ };
+ write!(f, "{}", &err_str)
+ }
+}
+
+impl From<Error> for RpcError {
+ fn from(error: Error) -> Self {
+ match error {
+ Error::InvalidOpeningFeeParams => RpcError::invalid_opening_fee_params(error),
+ Error::PaymentSizeTooSmall => RpcError::payment_size_too_small(error),
+ Error::PaymentSizeTooLarge => RpcError::payment_size_too_large(error),
+ }
+ }
+}
+
+impl core::error::Error for Error {}
+
+pub trait LSPS2RpcErrorExt {
+ rpc_error_methods! {
+ unrecognized_or_stale_token, unrecognized_or_stale_token_with_data => error_codes::UNRECOGNIZED_OR_STALE_TOKEN,
+ invalid_opening_fee_params, invalid_opening_fee_params_with_data => error_codes::INVALID_OPENING_FEE_PARAMS,
+ payment_size_too_small, payment_size_too_small_with_data => error_codes::PAYMENT_SIZE_TOO_SMALL,
+ payment_size_too_large, payment_size_too_large_with_data => error_codes::PAYMENT_SIZE_TOO_LARGE
+ }
+}
+
+impl LSPS2RpcErrorExt for RpcError {}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Lsps2GetInfoRequest {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub token: Option<String>,
+}
+
+impl JsonRpcRequest for Lsps2GetInfoRequest {
+ const METHOD: &'static str = "lsps2.get_info";
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Lsps2GetInfoResponse {
+ pub opening_fee_params_menu: Vec<OpeningFeeParams>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Lsps2BuyRequest {
+ pub opening_fee_params: OpeningFeeParams,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub payment_size_msat: Option<Msat>,
+}
+
+impl JsonRpcRequest for Lsps2BuyRequest {
+ const METHOD: &'static str = "lsps2.buy";
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Lsps2BuyResponse {
+ pub jit_channel_scid: ShortChannelId,
+ pub lsp_cltv_expiry_delta: u32,
+ // is an optional Boolean. If not specified, it defaults to false. If
+ // specified and true, the client MUST trust the LSP to actually create and
+ // confirm a valid channel funding transaction.
+ #[serde(default)]
+ pub client_trusts_lsp: bool,
+}
### lsps-types/src/lsps2/params.rs
@@ -0,0 +1,327 @@
+use super::{Error, Promise, compute_opening_fee};
+use crate::lsps0::{DateTime, Msat, Ppm};
+use serde::{Deserialize, Serialize};
+
+/// Represents a set of parameters for calculating the opening fee for a JIT
+/// channel.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(deny_unknown_fields)] // LSPS2 requires the client to fail if a field is unrecognized.
+pub struct OpeningFeeParams {
+ pub min_fee_msat: Msat,
+ pub proportional: Ppm,
+ pub valid_until: DateTime,
+ pub min_lifetime: u32,
+ pub max_client_to_self_delay: u32,
+ pub min_payment_size_msat: Msat,
+ pub max_payment_size_msat: Msat,
+ pub promise: Promise, // Max 512 bytes
+}
+
+/// Reasons why an [`OpeningFeeParams`] can't be used.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum ValidationError {
+ /// `min_payment_size_msat` is greater than `max_payment_size_msat`, so no
+ /// payment size is acceptable.
+ MinAboveMax { min: Msat, max: Msat },
+ /// `valid_until` is in the past.
+ Expired { valid_until: DateTime },
+ /// Computing the opening fee for `payment_size` overflowed.
+ FeeOverflow { payment_size: Msat },
+ /// The opening fee is not strictly less than `payment_size`.
+ FeeNotBelowPaymentSize {
+ opening_fee: Msat,
+ payment_size: Msat,
+ },
+}
+
+impl core::fmt::Display for ValidationError {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ match self {
+ ValidationError::MinAboveMax { min, max } => write!(
+ f,
+ "min_payment_size_msat {} is above max_payment_size_msat {}",
+ min, max
+ ),
+ ValidationError::Expired { valid_until } => {
+ write!(f, "opening fee params expired at {}", valid_until)
+ }
+ ValidationError::FeeOverflow { payment_size } => write!(
+ f,
+ "opening fee computation overflowed for payment size {}",
+ payment_size
+ ),
+ ValidationError::FeeNotBelowPaymentSize {
+ opening_fee,
+ payment_size,
+ } => write!(
+ f,
+ "opening fee {} is not less than payment size {}",
+ opening_fee, payment_size
+ ),
+ }
+ }
+}
+
+impl core::error::Error for ValidationError {}
+
+/// Maps a validation failure to the `lsps2.buy` error an LSP returns for it.
+impl From<ValidationError> for Error {
+ fn from(error: ValidationError) -> Self {
+ match error {
+ ValidationError::MinAboveMax { .. } | ValidationError::Expired { .. } => {
+ Error::InvalidOpeningFeeParams
+ }
+ ValidationError::FeeOverflow { .. } => Error::PaymentSizeTooLarge,
+ ValidationError::FeeNotBelowPaymentSize { .. } => Error::PaymentSizeTooSmall,
+ }
+ }
+}
+
+impl OpeningFeeParams {
+ /// Computes the opening fee for `payment_size` with these parameters, see
+ /// [`compute_opening_fee`]. Returns `None` on overflow.
+ pub fn opening_fee(&self, payment_size: Msat) -> Option<Msat> {
+ compute_opening_fee(
+ payment_size.msat(),
+ self.min_fee_msat.msat(),
+ u64::from(self.proportional.ppm()),
+ )
+ .map(Msat::from_msat)
+ }
+
+ /// Checks that `min_payment_size_msat <= max_payment_size_msat`; the
+ /// limits are inclusive, so otherwise no payment size is acceptable.
+ pub fn check_limits(&self) -> Result<(), ValidationError> {
+ if self.min_payment_size_msat > self.max_payment_size_msat {
+ return Err(ValidationError::MinAboveMax {
+ min: self.min_payment_size_msat,
+ max: self.max_payment_size_msat,
+ });
+ }
+ Ok(())
+ }
+
+ /// Returns whether `valid_until` is in the past at `now`.
+ pub fn is_expired_at(&self, now: &DateTime) -> bool {
+ *now > self.valid_until
+ }
+
+ /// Computes the opening fee for `payment_size` and checks it as the LSP
+ /// must when `payment_size_msat` is specified in `lsps2.buy`:
+ ///
+ /// > MUST compute the `opening_fee` and check that the computation did
+ /// > not hit an overflow failure.
+ /// > MUST check that the resulting `opening_fee` is strictly less than
+ /// > the `payment_size_msat`.
+ ///
+ /// Returns the opening fee.
+ pub fn check_payment_size(&self, payment_size: Msat) -> Result<Msat, ValidationError> {
+ let opening_fee = self
+ .opening_fee(payment_size)
+ .ok_or(ValidationError::FeeOverflow { payment_size })?;
+ if opening_fee >= payment_size {
+ return Err(ValidationError::FeeNotBelowPaymentSize {
+ opening_fee,
+ payment_size,
+ });
+ }
+ Ok(opening_fee)
+ }
+
+ /// Runs the checks an LSP does on `lsps2.buy`, except the promise check
+ /// which only the LSP that issued the promise can do:
+ ///
+ /// > LSPs MUST check that the `opening_fee_params.valid_until` is not a
+ /// > past datetime.
+ ///
+ /// and, if `payment_size` is given, [`Self::check_payment_size`].
+ /// Returns the opening fee if `payment_size` is given.
+ pub fn validate(
+ &self,
+ now: &DateTime,
+ payment_size: Option<Msat>,
+ ) -> Result<Option<Msat>, ValidationError> {
+ if self.is_expired_at(now) {
+ return Err(ValidationError::Expired {
+ valid_until: self.valid_until,
+ });
+ }
+ payment_size
+ .map(|size| self.check_payment_size(size))
+ .transpose()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono::{TimeZone, Utc};
+
+ fn datetime(year: i32) -> DateTime {
+ Utc.with_ymd_and_hms(year, 1, 1, 0, 0, 0).unwrap().into()
+ }
+
+ fn now() -> DateTime {
+ datetime(2026)
+ }
+
+ fn params() -> OpeningFeeParams {
+ OpeningFeeParams {
+ min_fee_msat: Msat::from_msat(1000),
+ proportional: Ppm::from_ppm(1000), // 0.1%
+ valid_until: datetime(2027),
+ min_lifetime: 144, // blocks
+ max_client_to_self_delay: 2016, // blocks
+ min_payment_size_msat: Msat::from_msat(1000), // 1 Sat
+ max_payment_size_msat: Msat::from_msat(100_000_000_000), // 1 BTC
+ promise: Promise::try_from("promise").unwrap(),
+ }
+ }
+
+ #[test]
+ fn test_validate_success_minimal() {
+ assert_eq!(params().validate(&now(), None), Ok(None));
+ }
+
+ #[test]
+ fn test_validate_success_with_payment_size() {
+ // max(1000, ceil(10_000_000 * 1000 / 1_000_000)) = 10_000
+ let fee = params().validate(&now(), Some(Msat::from_msat(10_000_000)));
+ assert_eq!(fee, Ok(Some(Msat::from_msat(10_000))));
+ }
+
+ #[test]
+ fn test_validate_expired_timestamp() {
+ let p = OpeningFeeParams {
+ valid_until: datetime(2025),
+ ..params()
+ };
+ let err = p.validate(&now(), None).unwrap_err();
+ assert_eq!(
+ err,
+ ValidationError::Expired {
+ valid_until: datetime(2025)
+ }
+ );
+ assert_eq!(Error::from(err), Error::InvalidOpeningFeeParams);
+ }
+
+ #[test]
+ fn test_valid_until_is_inclusive() {
+ let p = params();
+ assert!(!p.is_expired_at(&p.valid_until));
+ }
+
+ #[test]
+ fn test_validate_payment_size_overflow() {
+ let p = OpeningFeeParams {
+ proportional: Ppm::from_ppm(u32::MAX),
+ ..params()
+ };
+ let err = p
+ .validate(&now(), Some(Msat::from_msat(u64::MAX)))
+ .unwrap_err();
+ assert!(matches!(err, ValidationError::FeeOverflow { .. }));
+ assert_eq!(Error::from(err), Error::PaymentSizeTooLarge);
+ }
+
+ #[test]
+ fn test_validate_opening_fee_equals_payment_size() {
+ // Same as min_fee_msat.
+ let err = params()
+ .validate(&now(), Some(Msat::from_msat(1000)))
+ .unwrap_err();
+ assert!(matches!(
+ err,
+ ValidationError::FeeNotBelowPaymentSize { .. }
+ ));
+ assert_eq!(Error::from(err), Error::PaymentSizeTooSmall);
+ }
+
+ #[test]
+ fn test_validate_opening_fee_greater_than_payment_size() {
+ // Less than min_fee_msat.
+ let err = params()
+ .validate(&now(), Some(Msat::from_msat(500)))
+ .unwrap_err();
+ assert!(matches!(
+ err,
+ ValidationError::FeeNotBelowPaymentSize { .. }
+ ));
+ }
+
+ #[test]
+ fn test_validate_large_payment_proportional_fee() {
+ // max(1000, 1_000_000_000 * 1000 / 1_000_000) = 1_000_000
+ let fee = params().validate(&now(), Some(Msat::from_msat(1_000_000_000)));
+ assert_eq!(fee, Ok(Some(Msat::from_msat(1_000_000))));
+ }
+
+ #[test]
+ fn test_validate_max_values() {
+ let p = OpeningFeeParams {
+ min_fee_msat: Msat::from_msat(u64::MAX / 1000),
+ proportional: Ppm::from_ppm(100),
+ min_lifetime: u32::MAX,
+ max_client_to_self_delay: u32::MAX,
+ min_payment_size_msat: Msat::from_msat(1),
+ max_payment_size_msat: Msat::from_msat(u64::MAX),
+ ..params()
+ };
+ assert_eq!(p.validate(&now(), None), Ok(None));
+ }
+
+ #[test]
+ fn test_check_limits() {
+ assert_eq!(params().check_limits(), Ok(()));
+
+ let equal = OpeningFeeParams {
+ min_payment_size_msat: Msat::from_msat(5000),
+ max_payment_size_msat: Msat::from_msat(5000),
+ ..params()
+ };
+ assert_eq!(equal.check_limits(), Ok(()));
+
+ let inverted = OpeningFeeParams {
+ min_payment_size_msat: Msat::from_msat(5001),
+ max_payment_size_msat: Msat::from_msat(5000),
+ ..params()
+ };
+ assert_eq!(
+ inverted.check_limits(),
+ Err(ValidationError::MinAboveMax {
+ min: Msat::from_msat(5001),
+ max: Msat::from_msat(5000),
+ })
+ );
+ }
+
+ #[test]
+ fn test_deny_unknown_fields() {
+ let mut json = serde_json::to_value(params()).unwrap();
+ json["extra"] = serde_json::json!(1);
+ assert!(serde_json::from_value::<OpeningFeeParams>(json).is_err());
+ }
+
+ #[test]
+ fn test_spec_example_roundtrip() {
+ // From bLIP-52 "Example `lsps2.get_info` result".
+ let json = r#"{
+ "min_fee_msat": "546000",
+ "proportional": 1200,
+ "valid_until": "2023-02-23T08:47:30.511Z",
+ "min_lifetime": 1008,
+ "max_client_to_self_delay": 2016,
+ "min_payment_size_msat": "1000",
+ "max_payment_size_msat": "1000000",
+ "promise": "abcdefghijklmnopqrstuvwxyz"
+ }"#;
+ let p: OpeningFeeParams = serde_json::from_str(json).unwrap();
+ assert_eq!(p.min_fee_msat, Msat::from_msat(546_000));
+ assert_eq!(p.proportional, Ppm::from_ppm(1200));
+ assert_eq!(
+ serde_json::to_value(&p).unwrap(),
+ serde_json::from_str::<serde_json::Value>(json).unwrap()
+ );
+ }
+}
### lsps-types/src/lsps2/promise.rs
@@ -0,0 +1,120 @@
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum PromiseError {
+ TooLong { length: usize, max: usize },
+}
+
+impl core::fmt::Display for PromiseError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ PromiseError::TooLong { length, max } => {
+ write!(
+ f,
+ "promise string is too long: {} bytes (max allowed {})",
+ length, max
+ )
+ }
+ }
+ }
+}
+
+impl core::error::Error for PromiseError {}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(try_from = "String")]
+pub struct Promise(pub String);
+
+impl Promise {
+ pub const MAX_BYTES: usize = 512;
+}
+
+impl TryFrom<String> for Promise {
+ type Error = PromiseError;
+
+ fn try_from(s: String) -> Result<Self, Self::Error> {
+ let len = s.len();
+ if len <= Promise::MAX_BYTES {
+ Ok(Promise(s))
+ } else {
+ Err(PromiseError::TooLong {
+ length: len,
+ max: Promise::MAX_BYTES,
+ })
+ }
+ }
+}
+
+impl TryFrom<&str> for Promise {
+ type Error = PromiseError;
+
+ fn try_from(s: &str) -> Result<Self, Self::Error> {
+ let len = s.len();
+ if len <= Promise::MAX_BYTES {
+ Ok(Promise(s.to_owned()))
+ } else {
+ Err(PromiseError::TooLong {
+ length: len,
+ max: Promise::MAX_BYTES,
+ })
+ }
+ }
+}
+
+impl core::fmt::Display for Promise {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.0)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // Helper struct for testing Serde
+ #[derive(Serialize, Deserialize, Debug, PartialEq)]
+ struct TestData {
+ label: String,
+ value: Promise,
+ }
+
+ #[test]
+ fn test_serde_promise_ok() {
+ let json = r#"{"label": "short", "value": "This is valid"}"#;
+ let result = serde_json::from_str::<TestData>(json);
+ assert!(result.is_ok());
+ let data = result.unwrap();
+ assert_eq!(data.value.0, "This is valid");
+ }
+
+ #[test]
+ fn test_serde_promise_too_long() {
+ let long_value = "a".repeat(513); // Exceeds 512 bytes
+ let json = format!(r#"{{"label": "long", "value": "{}"}}"#, long_value);
+ let result = serde_json::from_str::<TestData>(&json);
+ assert!(result.is_err());
+ // Check the error message relates to our PromiseError
+ assert!(
+ result
+ .unwrap_err()
+ .to_string()
+ .contains("promise string is too long")
+ );
+ }
+
+ #[test]
+ fn test_serde_promise_wrong_type() {
+ // Input JSON has a number where a string is expected for 'value'
+ let json = r#"{"label": "wrong_type", "value": 123}"#;
+ let result = serde_json::from_str::<TestData>(json);
+ assert!(result.is_err());
+ // This error occurs when Serde tries to deserialize 123 as the String
+ // required by `try_from = "String"`.
+ assert!(
+ result
+ .unwrap_err()
+ .to_string()
+ .contains("invalid type: integer")
+ );
+ }
+}Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.