lsps-plugin: use lsps-types for the protocol types
What changed, and why it matters
This commit is a code cleanup in Core Lightning's LSPS (Lightning Service Provider Specification) plugin. It removes duplicated protocol type definitions and replaces them with a shared library called lsps-types. The only functional change mentioned is a stricter check on the 'promise' string, limiting it to printable ASCII characters without JSON escape characters. This is a hardening improvement, not an obvious vulnerability fix.
Treat as a routine refactoring/hardening commit. Review the lsps-types implementation of OpeningFeeParams::validate, verify_promise, and promise parsing to confirm the stricter character check is correctly enforced and that the shared library preserves the existing HMAC and fee-overflow semantics. No urgent mitigation is indicated by this commit alone.
Security signals we found
Refactoring to shared library reduces duplicated security-critical code (HMAC, fee validation)
HMAC promise verification extracted into separate verify_promise() function
Stricter promise character validation added by lsps-types (printable ASCII, no JSON escapes)
No changelog security entry; commit message says 'Changelog-None' and 'no behavior change' except promise restriction
Evidence from the diff
The commit refactors the lsps-plugin to depend on lsps-types for JSON-RPC, LSPS0, and LSPS2 protocol types and opening-fee computation, deleting local copies. Service-only code (policy API, datastore entry, JIT SCID generation, BOLT4 failure codes, HMAC promise) remains. The HMAC promise verification is split out of OpeningFeeParams::validate into a standalone verify_promise() called before validate(). The commit explicitly states the order of checks and error codes are unchanged. The one behavior change is that lsps-types now restricts the promise field to printable ASCII without JSON escapes, which hardens deserialization against unusual promise payloads.
Changed components
plugins/lsps-plugin/src/proto/jsonrpc.rsplugins/lsps-plugin/src/proto/lsps0.rsplugins/lsps-plugin/src/proto/lsps2.rsplugins/lsps-plugin/src/core/lsps2/service.rsplugins/lsps-plugin/src/core/lsps2/htlc.rsplugins/lsps-plugin/src/core/client.rsplugins/lsps-plugin/src/client.rsplugins/lsps-plugin/src/service.rsplugins/lsps-plugin/src/cln_adapters/rpc.rsplugins/lsps-plugin/Cargo.tomlCargo.lockInspect captured patch +101 / −1428
### Cargo.lock
@@ -537,6 +537,7 @@ dependencies = [
"cln-rpc",
"hex",
"log",
+ "lsps-types",
"rand 0.10.2",
"serde",
"serde_json",
### plugins/lsps-plugin/Cargo.toml
@@ -20,6 +20,7 @@ chrono = { version = "0.4.42", features = ["serde"] }
cln-plugin = { workspace = true }
cln-rpc = { workspace = true }
hex = "0.4"
+lsps-types = { workspace = true }
log = "0.4"
rand = "0.10"
serde = { version = "1.0", features = ["derive"] }
### plugins/lsps-plugin/src/client.rs
@@ -345,7 +345,7 @@ async fn on_lsps_lsps2_invoice(
.find(|params| {
// Basic validation on client side: check expiry and promise length
let fut_now = Utc::now() + Duration::minutes(1); // Add some extra time for network delay
- let expiry_valid = params.valid_until > fut_now;
+ let expiry_valid = params.valid_until.as_chrono() > fut_now;
if !expiry_valid {
warn!("Ignoring expired fee params from LSP {:?}", params);
}
@@ -406,7 +406,7 @@ async fn on_lsps_lsps2_invoice(
// We define the invoice expiry here to avoid cloning `selected_params`
// as they are about to be moved to the `Lsps2BuyRequest`.
- let expiry = (selected_params.valid_until - Utc::now()).num_seconds();
+ let expiry = (selected_params.valid_until.as_chrono() - Utc::now()).num_seconds();
if expiry <= 10 {
return Err(anyhow!(
"Invoice lifetime is too short, options are valid until: {}",
@@ -485,7 +485,7 @@ async fn on_lsps_lsps2_invoice(
// 5. Approve jit_channel_scid for a jit channel opening.
let appr_req = ClnRpcLsps2Approve {
lsp_id: req.lsp_id,
- jit_channel_scid: buy_res.jit_channel_scid,
+ jit_channel_scid: ShortChannelId::from(buy_res.jit_channel_scid.to_u64()),
payment_hash: public_inv.payment_hash.to_string(),
client_trusts_lsp: Some(buy_res.client_trusts_lsp),
};
### plugins/lsps-plugin/src/cln_adapters/rpc.rs
@@ -3,7 +3,7 @@ use crate::{
Blockheight, BlockheightProvider, DatastoreProvider, LightningProvider, Lsps2OfferProvider,
},
proto::{
- lsps0::Msat,
+ lsps0::{Msat, ShortChannelId},
lsps2::{
DatastoreEntry, Lsps2PolicyGetChannelCapacityRequest,
Lsps2PolicyGetChannelCapacityResponse, Lsps2PolicyGetInfoRequest,
@@ -23,7 +23,7 @@ use cln_rpc::{
},
responses::ListdatastoreResponse,
},
- primitives::{AmountSat, AmountSatOrAll, ChannelState, Sha256, ShortChannelId},
+ primitives::{AmountSat, AmountSatOrAll, ChannelState, Sha256},
};
use core::fmt;
use serde::Serialize;
### plugins/lsps-plugin/src/core/client.rs
@@ -3,7 +3,7 @@ use bitcoin::secp256k1::PublicKey;
use crate::{
core::transport::{self, Transport},
proto::{
- jsonrpc::{JsonRpcRequest, JsonRpcResponse},
+ jsonrpc::{JsonRpcRequestExt as _, JsonRpcResponse},
lsps0::{Lsps0listProtocolsRequest, Lsps0listProtocolsResponse, Msat},
lsps2::{
Lsps2BuyRequest, Lsps2BuyResponse, Lsps2GetInfoRequest, Lsps2GetInfoResponse,
### plugins/lsps-plugin/src/core/lsps2/htlc.rs
@@ -120,12 +120,12 @@ impl<A: DatastoreProvider + Lsps2OfferProvider + LightningProvider> HtlcAccepted
}
// B) Is the fee option menu still valid?
- if Utc::now() >= ds_rec.opening_fee_params.valid_until {
+ if Utc::now() >= ds_rec.opening_fee_params.valid_until.as_chrono() {
// Not valid anymore, remove from DS and fail HTLC.
let _ = self.api.del_buy_request(&onion.short_channel_id).await;
return Ok(HtlcDecision::Reject {
reason: RejectReason::OfferExpired {
- valid_until: ds_rec.opening_fee_params.valid_until,
+ valid_until: ds_rec.opening_fee_params.valid_until.as_chrono(),
},
});
}
@@ -270,7 +270,7 @@ mod tests {
OpeningFeeParams {
min_fee_msat: Msat(2_000),
proportional: Ppm(10_000), // 1%
- valid_until: Utc.with_ymd_and_hms(2100, 1, 1, 0, 0, 0).unwrap(),
+ valid_until: Utc.with_ymd_and_hms(2100, 1, 1, 0, 0, 0).unwrap().into(),
min_lifetime: 1000,
max_client_to_self_delay: 2016,
min_payment_size_msat: Msat(1_000_000),
@@ -281,7 +281,7 @@ mod tests {
fn expired_opening_fee_params() -> OpeningFeeParams {
OpeningFeeParams {
- valid_until: Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap(),
+ valid_until: Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
..valid_opening_fee_params()
}
}
### plugins/lsps-plugin/src/core/lsps2/service.rs
@@ -8,14 +8,15 @@ use crate::{
jsonrpc::{RpcError, RpcErrorExt as _},
lsps0::{LSPS0RpcErrorExt as _, ShortChannelId},
lsps2::{
- Lsps2BuyRequest, Lsps2BuyResponse, Lsps2GetInfoRequest, Lsps2GetInfoResponse,
- Lsps2PolicyGetInfoRequest, OpeningFeeParams, ShortChannelIdJITExt,
+ Error, Lsps2BuyRequest, Lsps2BuyResponse, Lsps2GetInfoRequest, Lsps2GetInfoResponse,
+ Lsps2PolicyGetInfoRequest, OpeningFeeParams, ShortChannelIdJITExt, verify_promise,
},
},
register_handler,
};
use async_trait::async_trait;
use bitcoin::secp256k1::PublicKey;
+use chrono::Utc;
use std::sync::Arc;
const DEFAULT_CLTV_EXPIRY_DELTA: u32 = 144;
@@ -100,10 +101,15 @@ impl<A: DatastoreProvider + BlockheightProvider + Lsps2OfferProvider + 'static>
) -> core::result::Result<Lsps2BuyResponse, RpcError> {
let fee_params = request.opening_fee_params;
- // FIXME: In the future we should replace the \`None\` with a meaningful
- // value that reflects the inbound capacity for this node from the
- // public network for a better pre-condition check on the payment_size.
- fee_params.validate(&self.promise_secret, request.payment_size_msat, None)?;
+ // FIXME: In the future we should also check the inbound capacity for
+ // this node from the public network for a better pre-condition check
+ // on the payment_size.
+ if !verify_promise(&fee_params, &self.promise_secret) {
+ return Err(Error::InvalidOpeningFeeParams.into());
+ }
+ fee_params
+ .validate(&Utc::now().into(), request.payment_size_msat)
+ .map_err(Error::from)?;
// Generate a tmp scid to identify jit channel request in htlc.
let blockheight = self
@@ -164,7 +170,7 @@ mod tests {
PolicyOpeningFeeParams {
min_fee_msat: Msat(2_000),
proportional: Ppm(10_000),
- valid_until: Utc.with_ymd_and_hms(2100, 1, 1, 0, 0, 0).unwrap(),
+ valid_until: Utc.with_ymd_and_hms(2100, 1, 1, 0, 0, 0).unwrap().into(),
min_lifetime: 1000,
max_client_to_self_delay: 2016,
min_payment_size_msat: Msat(1_000_000),
@@ -178,7 +184,7 @@ mod tests {
fn expired_opening_fee_params(secret: &[u8; 32]) -> OpeningFeeParams {
let mut policy = test_policy_params();
- policy.valid_until = Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap();
+ policy.valid_until = Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into();
policy.with_promise(secret)
}
@@ -343,7 +349,7 @@ mod tests {
let params = &response.opening_fee_params_menu[0];
assert_eq!(params.min_fee_msat, Msat(2_000));
assert_eq!(params.proportional, Ppm(10_000));
- assert!(!params.promise.0.is_empty());
+ assert!(!params.promise.as_str().is_empty());
}
#[tokio::test]
### plugins/lsps-plugin/src/proto/jsonrpc.rs
@@ -1,42 +1,16 @@
-use rand::{TryRng, rngs::SysRng};
-use serde::{Deserialize, Serialize, de::DeserializeOwned};
-use serde_json::{self, Value};
-use std::fmt;
+pub use lsps_types::jsonrpc::*;
-// Constants for JSON-RPC error codes.
-pub const PARSE_ERROR: i64 = -32700;
-pub const INVALID_REQUEST: i64 = -32600;
-pub const METHOD_NOT_FOUND: i64 = -32601;
-pub const INVALID_PARAMS: i64 = -32602;
-pub const INTERNAL_ERROR: i64 = -32603;
+use rand::{TryRng, rngs::SysRng};
-/// Trait for types that can be converted into JSON-RPC request objects.
-///
-/// Implementing this trait allows a struct to be used as a typed JSON-RPC
-/// request, with an associated method name and automatic conversion to the
-/// request format.
-pub trait JsonRpcRequest: Serialize {
- const METHOD: &'static str;
- fn into_request(self) -> RequestObject<Self>
- where
- Self: Sized,
- {
- Self::into_request_with_id(self, Some(generate_random_id()))
- }
-
- fn into_request_with_id(self, id: Option<String>) -> RequestObject<Self>
- where
- Self: Sized,
- {
- RequestObject {
- jsonrpc: "2.0".into(),
- method: Self::METHOD.into(),
- params: Some(self),
- id,
- }
+/// Builds JSON-RPC request objects with a random `id`.
+pub trait JsonRpcRequestExt: JsonRpcRequest + Sized {
+ fn into_request(self) -> RequestObject<Self> {
+ self.into_request_with_id(Some(generate_random_id()))
}
}
+impl<T: JsonRpcRequest> JsonRpcRequestExt for T {}
+
/// Generates a random ID for JSON-RPC requests.
///
/// Uses a secure random number generator to create a hex-encoded ID. Falls back
@@ -56,510 +30,22 @@ fn generate_random_id() -> String {
}
}
-/// # RequestObject
-///
-/// Represents a JSON-RPC 2.0 Request object, as defined in section 4 of the
-/// specification. This structure encapsulates all necessary information for
-/// a remote procedure call.
-///
-/// # Type Parameters
-///
-/// * `T`: The type of the `params` field. This *MUST* implement `Serialize`
-/// to allow it to be encoded as JSON. Typically this will be a struct
-/// implementing the `JsonRpcRequest` trait.
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
-pub struct RequestObject<T> {
- /// **REQUIRED**. MUST be `"2.0"`.
- pub jsonrpc: String,
- /// **REQUIRED**. The method to be invoked.
- pub method: String,
- /// A struct containing the method parameters.
- #[serde(skip_serializing_if = "is_none_or_null")]
- pub params: Option<T>,
- /// An identifier established by the Client that MUST contain a String.
- /// # Note: this is special to LSPS0, might change to match the more general
- /// JSON-RPC 2.0 sepec if needed.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub id: Option<String>,
-}
-
-impl<T> RequestObject<T>
-where
- T: Serialize,
-{
- /// Returns the inner data object contained by params for handling or future
- /// processing.
- pub fn into_inner(self) -> Option<T> {
- self.params
- }
-}
-
-/// Helper function to check if params is None or would serialize to null.
-fn is_none_or_null<T: Serialize>(opt: &Option<T>) -> bool {
- match opt {
- None => true,
- Some(val) => match serde_json::to_value(&val) {
- Ok(Value::Null) => true,
- _ => false,
- },
- }
-}
-
-#[derive(Clone, Debug, PartialEq)]
-pub struct JsonRpcResponse<R = ()> {
- id: String,
- body: JsonRpcResponseBody<R>,
-}
-
-impl JsonRpcResponse<()> {
- pub fn error<T: Into<String>>(error: RpcError, id: T) -> Self {
- Self {
- id: id.into(),
- body: JsonRpcResponseBody::Error { error },
- }
- }
-}
-
-impl<R> JsonRpcResponse<R> {
- pub fn success<T: Into<String>>(result: R, id: T) -> Self {
- Self {
- id: id.into(),
- body: JsonRpcResponseBody::Success { result },
- }
- }
-
- pub fn into_result(self) -> std::result::Result<R, RpcError> {
- self.body.into_result()
- }
-
- pub fn as_result(&self) -> std::result::Result<&R, &RpcError> {
- self.body.as_result()
- }
-
- pub fn is_ok(&self) -> bool {
- self.body.is_ok()
- }
-
- pub fn is_err(&self) -> bool {
- self.body.is_err()
- }
-
- pub fn map<U, F>(self, f: F) -> JsonRpcResponse<U>
- where
- F: FnOnce(R) -> U,
- {
- JsonRpcResponse {
- id: self.id,
- body: self.body.map(f),
- }
- }
-
- pub fn unwrap(self) -> R {
- self.body.unwrap()
- }
-
- pub fn expect(self, msg: &str) -> R {
- self.body.expect(msg)
- }
-
- pub fn unwrap_err(self) -> RpcError {
- self.body.unwrap_err()
- }
-
- pub fn expect_err(self, msg: &str) -> RpcError {
- self.body.expect_err(msg)
- }
-}
-
-// Custom Serialize to match JSON-RPC 2.0 wire format
-impl<R: Serialize> Serialize for JsonRpcResponse<R> {
- fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
- where
- S: serde::Serializer,
- {
- use serde::ser::SerializeStruct;
-
- let mut state = serializer.serialize_struct("JsonRpcResponse", 3)?;
- state.serialize_field("jsonrpc", "2.0")?;
- state.serialize_field("id", &self.id)?;
-
- match &self.body {
- JsonRpcResponseBody::Success { result } => {
- state.serialize_field("result", result)?;
- }
- JsonRpcResponseBody::Error { error } => {
- state.serialize_field("error", error)?;
- }
- }
-
- state.end()
- }
-}
-
-// Custom Deserialize from JSON-RPC 2.0 wire format
-impl<'de, R: DeserializeOwned> Deserialize<'de> for JsonRpcResponse<R> {
- fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
- where
- D: serde::Deserializer<'de>,
- {
- #[derive(Deserialize)]
- struct RawResponse<R> {
- jsonrpc: String,
- result: Option<R>,
- error: Option<RpcError>,
- id: String,
- }
-
- let raw = RawResponse::deserialize(deserializer)?;
-
- if raw.jsonrpc != "2.0" {
- return Err(serde::de::Error::custom(format!(
- "Invalid JSON-RPC version: {}",
- raw.jsonrpc
- )));
- }
-
- let body = match (raw.result, raw.error) {
- (Some(result), None) => JsonRpcResponseBody::Success { result },
- (None, Some(error)) => JsonRpcResponseBody::Error { error },
- (Some(_), Some(_)) => {
- return Err(serde::de::Error::custom(
- "Response cannot have both result and error",
- ));
- }
- (None, None) => {
- return Err(serde::de::Error::custom(
- "Response must have either result or error",
- ));
- }
- };
-
- Ok(JsonRpcResponse { id: raw.id, body })
- }
-}
-
-#[derive(Clone, Debug, PartialEq)]
-pub enum JsonRpcResponseBody<R> {
- Success { result: R },
- Error { error: RpcError },
-}
-
-impl<R> JsonRpcResponseBody<R> {
- pub fn into_result(self) -> std::result::Result<R, RpcError> {
- match self {
- Self::Success { result } => Ok(result),
- Self::Error { error } => Err(error),
- }
- }
-
- pub fn as_result(&self) -> std::result::Result<&R, &RpcError> {
- match self {
- Self::Success { result } => Ok(result),
- Self::Error { error } => Err(error),
- }
- }
-
- pub fn is_ok(&self) -> bool {
- matches!(self, JsonRpcResponseBody::Success { .. })
- }
-
- pub fn is_err(&self) -> bool {
- matches!(self, JsonRpcResponseBody::Error { .. })
- }
-
- pub fn map<U, F>(self, f: F) -> JsonRpcResponseBody<U>
- where
- F: FnOnce(R) -> U,
- {
- match self {
- Self::Success { result } => JsonRpcResponseBody::Success { result: f(result) },
- Self::Error { error } => JsonRpcResponseBody::Error { error },
- }
- }
-
- pub fn unwrap(self) -> R {
- match self {
- Self::Success { result } => result,
- Self::Error { error } => panic!("Called unwrap on RPC Error: {}", error),
- }
- }
-
- pub fn expect(self, msg: &str) -> R {
- match self {
- Self::Success { result } => result,
- Self::Error { error } => panic!("{}: {}", msg, error),
- }
- }
-
- pub fn unwrap_err(self) -> RpcError {
- match self {
- JsonRpcResponseBody::Success { .. } => {
- panic!("Called unwrap_err on RPC Success")
- }
- JsonRpcResponseBody::Error { error } => error,
- }
- }
-
- pub fn expect_err(self, msg: &str) -> RpcError {
- match self {
- JsonRpcResponseBody::Success { .. } => panic!("{}", msg),
- JsonRpcResponseBody::Error { error } => error,
- }
- }
-}
-
-/// Macro to generate RpcError helper methods for protocol-specific error codes
-///
-/// This generates two methods for each error code:
-/// - `method_name(message)` - Creates error without data
-/// - `method_name_with_data(message, data)` - Creates error with data
-macro_rules! rpc_error_methods {
- ($($method:ident, $method_with_data:ident => $code:expr),* $(,)?) => {
- $(
- fn $method<T: std::fmt::Display>(message: T) -> $crate::proto::jsonrpc::RpcError {
- $crate::proto::jsonrpc::RpcError {
- code: $code,
- message: message.to_string(),
- data: None,
- }
- }
-
- fn $method_with_data<T: std::fmt::Display>(
- message: T,
- data: serde_json::Value,
- ) -> $crate::proto::jsonrpc::RpcError {
- $crate::proto::jsonrpc::RpcError {
- code: $code,
- message: message.to_string(),
- data: Some(data),
- }
- }
-
- )*
- };
-}
-
-/// # RpcError
-///
-/// Represents an error object in a JSON-RPC 2.0 Response object (section 5.1).
-/// Provides structured information about an error that occurred during the
-/// method invocation.
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
-pub struct RpcError {
- /// **REQUIRED**. An integer indicating the type of error.
- pub code: i64,
- /// **REQUIRED**. A string containing a short description of the error.
- pub message: String,
- /// A primitive that can be either Primitive or Structured type if there
- /// were.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub data: Option<Value>,
-}
-
-impl RpcError {
- /// Reserved for implementation-defined server-errors.
- pub fn custom_error<T: core::fmt::Display>(code: i64, message: T) -> Self {
- RpcError {
- code,
- message: message.to_string(),
- data: None,
- }
- }
-
- /// Reserved for implementation-defined server-errors.
- pub fn custom_error_with_data<T: core::fmt::Display>(
- code: i64,
- message: T,
- data: serde_json::Value,
- ) -> Self {
- RpcError {
- code,
- message: message.to_string(),
- data: Some(data),
- }
- }
-}
-
-pub trait RpcErrorExt {
- rpc_error_methods! {
- parse_error, parse_error_with_data => PARSE_ERROR,
- internal_error, internal_error_with_data => INTERNAL_ERROR,
- invalid_params, invalid_params_with_data => INVALID_PARAMS,
- method_not_found, method_not_found_with_data => METHOD_NOT_FOUND,
- invalid_request, invalid_request_with_data => INVALID_REQUEST,
- }
-}
-
-impl RpcErrorExt for RpcError {}
-
-impl fmt::Display for RpcError {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(
- f,
- "JSON-RPC Error (code: {}, message: {}, data: {:?})",
- self.code, self.message, self.data
- )
- }
-}
-
-impl std::error::Error for RpcError {}
-
#[cfg(test)]
-mod test_message_serialization {
+mod tests {
use super::*;
- use serde_json::json;
+ use serde::{Deserialize, Serialize};
#[test]
- fn test_empty_params_serialization() {
- // Empty params should serialize to `"params":{}` instead of
- // `"params":null`.
+ fn test_into_request_sets_random_id() {
#[derive(Debug, Serialize, Deserialize)]
pub struct SayHelloRequest;
impl JsonRpcRequest for SayHelloRequest {
const METHOD: &'static str = "say_hello";
}
- let rpc_request = SayHelloRequest.into_request();
- assert!(
- !serde_json::to_string(&rpc_request)
- .expect("could not convert to json")
- .contains("\"params\"")
- );
- }
-
- #[test]
- fn test_request_serialization_and_deserialization() {
- // Ensure that we correctly serialize to a valid JSON-RPC 2.0 request.
- #[derive(Default, Debug, Serialize, Deserialize)]
- pub struct SayNameRequest {
- name: String,
- age: i32,
- }
- impl JsonRpcRequest for SayNameRequest {
- const METHOD: &'static str = "say_name";
- }
- let rpc_request = SayNameRequest {
- name: "Satoshi".to_string(),
- age: 99,
- }
- .into_request_with_id(Some("unique-id-123".into()));
-
- let json_value: serde_json::Value = serde_json::to_value(&rpc_request).unwrap();
- let expected_value: serde_json::Value = serde_json::json!({
- "jsonrpc": "2.0",
- "method": "say_name",
- "params": {
- "name": "Satoshi",
- "age": 99
- },
- "id": "unique-id-123"
- });
- assert_eq!(json_value, expected_value);
-
- let request: RequestObject<serde_json::Value> = serde_json::from_value(json_value).unwrap();
- assert_eq!(request.method, "say_name");
- assert_eq!(request.jsonrpc, "2.0");
-
- let request: RequestObject<SayNameRequest> =
- serde_json::from_value(expected_value).unwrap();
- let inner = request.into_inner();
- assert_eq!(inner.unwrap().name, rpc_request.params.unwrap().name);
- }
-
- #[test]
- fn test_response_deserialization() {
- // Check that we can convert a JSON-RPC response into a typed result.
- #[derive(Debug, Serialize, Deserialize, PartialEq)]
- pub struct SayNameResponse {
- name: String,
- age: i32,
- message: String,
- }
-
- let json_response = r#"
- {
- "jsonrpc": "2.0",
- "result": {
- "age": 99,
- "message": "Hello Satoshi!",
- "name": "Satoshi"
- },
- "id": "unique-id-123"
- }"#;
-
- let response: JsonRpcResponse<SayNameResponse> =
- serde_json::from_str(json_response).unwrap();
-
- let result = response.into_result().unwrap();
- assert_eq!(
- result,
- SayNameResponse {
- name: "Satoshi".into(),
- age: 99,
- message: "Hello Satoshi!".into(),
- }
- );
- }
-
- #[test]
- fn test_empty_result() {
- // Check that we correctly deserialize an empty result.
- #[derive(Debug, Serialize, Deserialize, PartialEq)]
- pub struct DummyResponse {}
-
- let json_response = r#"
- {
- "jsonrpc": "2.0",
- "result": {},
- "id": "unique-id-123"
- }"#;
-
- let response: JsonRpcResponse<DummyResponse> = serde_json::from_str(json_response).unwrap();
- let result = response.into_result().unwrap();
- assert_eq!(result, DummyResponse {});
- }
- #[test]
- fn test_error_deserialization() {
- // Check that we deserialize an error if we got one.
- #[derive(Debug, Serialize, Deserialize, PartialEq)]
- pub struct DummyResponse {}
-
- let json_response = r#"
- {
- "jsonrpc": "2.0",
- "id": "unique-id-123",
- "error": {
- "code": -32099,
- "message": "something bad happened",
- "data": {
- "f1": "v1",
- "f2": 2
- }
- }
- }"#;
-
- let response: JsonRpcResponse<DummyResponse> = serde_json::from_str(json_response).unwrap();
- assert!(response.is_err());
-
- let err = response.into_result().unwrap_err();
- assert!(matches!(err, RpcError { .. }));
- assert_eq!(err.message, "something bad happened");
- assert_eq!(err.data, Some(serde_json::json!({"f1":"v1","f2":2})));
- }
-
- #[test]
- fn test_error_serialization() {
- let error = RpcError::invalid_request("Invalid request");
- let serialized = serde_json::to_string(&error).unwrap();
- assert_eq!(serialized, r#"{"code":-32600,"message":"Invalid request"}"#);
-
- let error_with_data = RpcError::internal_error_with_data(
- "Internal server error",
- json!({"details": "Something went wrong"}),
- );
- let serialized_with_data = serde_json::to_string(&error_with_data).unwrap();
- assert_eq!(
- serialized_with_data,
- r#"{"code":-32603,"message":"Internal server error","data":{"details":"Something went wrong"}}"#
- );
+ let a = SayHelloRequest.into_request();
+ let b = SayHelloRequest.into_request();
+ assert_eq!(a.method, "say_hello");
+ assert_eq!(a.id.as_ref().map(String::len), Some(20));
+ assert_ne!(a.id, b.id);
}
}
### plugins/lsps-plugin/src/proto/lsps0.rs
@@ -1,313 +1 @@
-use crate::proto::jsonrpc::{JsonRpcRequest, RpcError};
-use core::fmt;
-use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
-use thiserror::Error;
-
-const MSAT_PER_SAT: u64 = 1_000;
-
-// Optional feature bet to set according to LSPS0.
-pub const LSP_FEATURE_BIT: usize = 729;
-
-// Required message type for BOLT8 transport.
-pub const LSPS0_MESSAGE_TYPE: u16 = 37913;
-
-// Lsps0 specific error codes defined in BLIP-50.
-// Are in the range 00000 to 00099.
-pub mod error_codes {
- pub const CLIENT_REJECTED: i64 = 001;
-}
-
-pub trait LSPS0RpcErrorExt {
- rpc_error_methods! {
- client_rejected, client_rejected_with_data => error_codes::CLIENT_REJECTED,
- }
-}
-
-impl LSPS0RpcErrorExt for RpcError {}
-
-#[derive(Error, Debug)]
-pub enum Error {
- #[error("invalid message type: got {type_}")]
- InvalidMessageType { type_: u16 },
- #[error("Invalid UTF-8 in message payload")]
- InvalidUtf8(#[from] std::string::FromUtf8Error),
- #[error("message too short: expected at least 2 bytes for type field, got {0}")]
- TooShort(usize),
-}
-
-pub type Result<T> = std::result::Result<T, Error>;
-
-/// Encode raw payload bytes into an LSPS0 frame.
-///
-/// Format:
-/// [0-1] Message type: 37913 (0x9419) as big-endian u16
-/// [2..] Payload bytes
-pub fn encode_frame(payload: &[u8]) -> Vec<u8> {
- let mut bytes = Vec::with_capacity(2 + payload.len());
- bytes.extend_from_slice(&LSPS0_MESSAGE_TYPE.to_be_bytes());
- bytes.extend_from_slice(payload);
- bytes
-}
-
-/// Decode an LSPS0 frame and return the raw payload bytes.
-///
-/// Validates that the header matches the LSPS0 message type (37913).
-pub fn decode_frame(bytes: &[u8]) -> Result<&[u8]> {
- if bytes.len() < 2 {
- return Err(Error::TooShort(bytes.len()));
- }
- let message_type = u16::from_be_bytes([bytes[0], bytes[1]]);
- if message_type != LSPS0_MESSAGE_TYPE {
- return Err(Error::InvalidMessageType {
- type_: message_type,
- });
- }
- Ok(&bytes[2..])
-}
-
-/// Represents a monetary amount as defined in LSPS0.msat. Is converted to a
-/// `String` in json messages with a suffix `_msat` or `_sat` and internally
-/// represented as Millisatoshi `u64`.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
-pub struct Msat(pub u64);
-
-impl Msat {
- /// Constructs a new `Msat` struct from a `u64` msat value.
- pub fn from_msat(msat: u64) -> Self {
- Msat(msat)
- }
-
- /// Construct a new `Msat` struct from a `u64` sat value.
- pub fn from_sat(sat: u64) -> Self {
- Msat(sat * MSAT_PER_SAT)
- }
-
- /// Returns the sat amount of the field. Is a floored integer division e.g
- /// 100678 becomes 100.
- pub fn to_sats_floor(&self) -> u64 {
- self.0 / 1000
- }
-
- /// Returns the msat value as `u64`. Is the inner value of `Msat`.
- pub fn msat(&self) -> u64 {
- self.0
- }
-}
-
-impl core::fmt::Display for Msat {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}_msat", self.0)
- }
-}
-
-impl Serialize for Msat {
- fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
- where
- S: Serializer,
- {
- serializer.serialize_str(&self.0.to_string())
- }
-}
-
-impl<'de> Deserialize<'de> for Msat {
- fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
- where
- D: Deserializer<'de>,
- {
- struct MsatVisitor;
-
- impl<'de> de::Visitor<'de> for MsatVisitor {
- type Value = Msat;
-
- fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
- formatter.write_str("a string representing a number")
- }
-
- fn visit_str<E>(self, value: &str) -> std::result::Result<Msat, E>
- where
- E: de::Error,
- {
- value
- .parse::<u64>()
- .map(Msat::from_msat)
- .map_err(|_| E::custom(format!("Invalid number string: {}", value)))
- }
-
- // Also handle if JSON mistakenly has a number instead of string
- fn visit_u64<E>(self, value: u64) -> std::result::Result<Msat, E>
- where
- E: de::Error,
- {
- Ok(Msat::from_msat(value))
- }
-
- fn visit_i64<E>(self, value: i64) -> std::result::Result<Msat, E>
- where
- E: de::Error,
- {
- if value < 0 {
- Err(E::custom("Msat cannot be negative"))
- } else {
- Ok(Msat::from_msat(value as u64))
- }
- }
- }
-
- deserializer.deserialize_any(MsatVisitor)
- }
-}
-
-/// Represents parts-per-million as defined in LSPS0.ppm. Gets it's own type
-/// from the rationals: "This is its own type so that fractions can be expressed
-/// using this type, instead of as a floating-point type which might lose
-/// accuracy when serialized into text.". Having it as a separate type also
-/// provides more clarity.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
-#[serde(transparent)] // Key attribute! Serialize/Deserialize as the inner u32
-pub struct Ppm(pub u32); // u32 is sufficient as 1,000,000 fits easily (spec definition)
-
-impl Ppm {
- /// Constructs a new `Ppm` from a u32.
- pub const fn from_ppm(value: u32) -> Self {
- Ppm(value)
- }
-
- /// Applies the proportion to a base amount (e.g., in msats).
- pub fn apply_to(&self, base_msat: u64) -> u64 {
- // Careful about integer division order and potential overflow
- (base_msat as u128 * self.0 as u128 / 1_000_000) as u64
- }
-
- /// Returns the ppm.
- pub fn ppm(&self) -> u32 {
- self.0
- }
-}
-
-impl core::fmt::Display for Ppm {
- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
- write!(f, "{}ppm", self.0)
- }
-}
-
-/// Represents a short channel id as defined in LSPS0.scid. Matches with the
-/// implementation in cln_rpc.
-pub type ShortChannelId = cln_rpc::primitives::ShortChannelId;
-
-/// Represents a datetime as defined in LSPS0.datetime. Uses ISO8601 in UTC
-/// timezone.
-pub type DateTime = chrono::DateTime<chrono::Utc>;
-
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-pub struct Lsps0listProtocolsRequest {}
-
-impl JsonRpcRequest for Lsps0listProtocolsRequest {
- const METHOD: &'static str = "lsps0.list_protocols";
-}
-
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-pub struct Lsps0listProtocolsResponse {
- pub protocols: Vec<u8>,
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- const TEST_JSON: &str = r#"{"jsonrpc":"2.0","method":"test","id":"1"}"#;
-
- #[derive(Debug, Serialize, Deserialize)]
- struct TestMessage {
- amount: Msat,
- }
-
- #[test]
- fn test_encode_frame() {
- let json = TEST_JSON.as_bytes();
- let wire_bytes = encode_frame(json);
-
- assert_eq!(wire_bytes.len(), 2 + json.len());
- assert_eq!(wire_bytes[0], 0x94);
- assert_eq!(wire_bytes[1], 0x19);
- assert_eq!(&wire_bytes[2..], json);
- }
-
- #[test]
- fn test_encode_decode_frame_roundtrip() {
- let json = TEST_JSON.as_bytes();
- let wire_bytes = encode_frame(json);
- let decoded = decode_frame(&wire_bytes).expect("should decode the frame");
-
- assert_eq!(decoded, json)
- }
-
- #[test]
- fn test_decode_empty_frame() {
- let result = decode_frame(&[]);
- assert!(matches!(result, Err(Error::TooShort(0))));
- }
-
- #[test]
- fn test_decode_single_byte_frame() {
- let result = decode_frame(&[0x94]);
- assert!(matches!(result, Err(Error::TooShort(1))));
- }
-
- #[test]
- fn test_decode_frame_with_wrong_message_type() {
- let bytes = vec![0x00, 0x01, b'{', b'}'];
- let result = decode_frame(&bytes);
- assert!(matches!(
- result,
- Err(Error::InvalidMessageType { type_: 1 })
- ));
- }
-
- /// Test serialization of a struct containing Msat.
- #[test]
- fn test_msat_serialization() {
- let msg = TestMessage {
- amount: Msat(12345000),
- };
-
- let expected_amount_json = r#""amount":"12345000""#;
-
- // Assert that the field gets serialized as string.
- let json_string = serde_json::to_string(&msg).expect("Serialization failed");
- assert!(
- json_string.contains(expected_amount_json),
- "Serialized JSON should contain '{}'",
- expected_amount_json
- );
-
- // Parse back to generic json value and check field.
- let json_value: serde_json::Value =
- serde_json::from_str(&json_string).expect("Failed to parse JSON back");
- assert_eq!(
- json_value
- .get("amount")
- .expect("JSON should have 'amount' field"),
- &serde_json::Value::String("12345000".to_string()),
- "JSON 'amount' field should have the correct string value"
- );
- }
-
- /// Test deserialization into a struct containing Msat.
- #[test]
- fn test_msat_deserialization_and_errors() {
- // Case 1: Input string uses "_msat" suffix
- let json_ok = r#"{"amount":"987654321"}"#;
- let expected_value_msat = Msat(987654321);
- let message1: TestMessage =
- serde_json::from_str(json_ok).expect("Deserialization from string failed");
- assert_eq!(message1.amount, expected_value_msat);
-
- // Case 2: Non-numeric Value before suffix
- let json_non_numeric = r#"{"amount":"abc"}"#;
- let result_non_numeric = serde_json::from_str::<TestMessage>(json_non_numeric);
- assert!(
- result_non_numeric.is_err(),
- "Deserialization should fail for non-numeric value"
- );
- }
-}
+pub use lsps_types::lsps0::*;
### plugins/lsps-plugin/src/proto/lsps2.rs
@@ -1,65 +1,14 @@
-use crate::proto::{
- jsonrpc::{JsonRpcRequest, RpcError},
- lsps0::{DateTime, Msat, Ppm, ShortChannelId},
-};
+pub use lsps_types::lsps2::*;
+
+use crate::proto::lsps0::{DateTime, Msat, Ppm, ShortChannelId};
use bitcoin::hashes::{Hash, HashEngine, Hmac, HmacEngine, sha256};
-use chrono::Utc;
-use log::debug;
use serde::{Deserialize, Serialize};
pub mod failure_codes {
pub const TEMPORARY_CHANNEL_FAILURE: &'static str = "1007";
pub const UNKNOWN_NEXT_PEER: &'static str = "4010";
}
-// Lsps2 specific error codes defined in BLIP-52.
-// Are in the range 00200 to 00299.
-pub mod error_codes {
- pub const INVALID_OPENING_FEE_PARAMS: i64 = 201;
- pub const PAYMENT_SIZE_TOO_SMALL: i64 = 202;
- pub const PAYMENT_SIZE_TOO_LARGE: i64 = 203;
-}
-
-#[derive(Clone, Debug, PartialEq)]
-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! {
- 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 {}
-
pub trait ShortChannelIdJITExt {
fn generate_jit(blockheight: u32, distance: u32) -> Self;
}
@@ -77,189 +26,6 @@ impl ShortChannelIdJITExt for ShortChannelId {
}
}
-#[derive(Clone, Debug, PartialEq, 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, Serialize, Deserialize)]
-pub struct Lsps2GetInfoResponse {
- pub opening_fee_params_menu: Vec<OpeningFeeParams>,
-}
-
-#[derive(Clone, Debug, PartialEq)]
-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, 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)
- }
-}
-
-/// Represents a set of parameters for calculating the opening fee for a JIT
-/// channel.
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-#[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
-}
-
-impl OpeningFeeParams {
- pub fn validate(
- &self,
- secret: &[u8],
- payment_size_msat: Option<Msat>,
- receivable: Option<Msat>,
- ) -> Result<(), Error> {
- // LSPs MUST check that the opening_fee_params.promise does in fact
- // prove that it previously promised the specified opening_fee_params.
- let mut hmac = HmacEngine::<sha256::Hash>::new(&secret);
- hmac.input(&self.min_fee_msat.msat().to_be_bytes());
- hmac.input(&self.proportional.ppm().to_be_bytes());
- hmac.input(self.valid_until.to_rfc3339().as_bytes());
- hmac.input(&self.min_lifetime.to_be_bytes());
- hmac.input(&self.max_client_to_self_delay.to_be_bytes());
- hmac.input(&self.min_payment_size_msat.msat().to_be_bytes());
- hmac.input(&self.max_payment_size_msat.msat().to_be_bytes());
- let promise: String = Hmac::from_engine(hmac)
- .to_byte_array()
- .iter()
- .map(|b| format!("{:02x}", b))
- .collect();
- if self.promise != Promise(promise) {
- return Err(Error::InvalidOpeningFeeParams);
- }
-
- // LSPs MUST check that the opening_fee_params.valid_until is not a past
- // datetime.
- let now = Utc::now();
- if now > self.valid_until {
- debug!("Got invalid opening fee params: timeout, {:?}", self);
- return Err(Error::InvalidOpeningFeeParams);
- }
-
- // If the payment_size_msat is specified in the request, the LSP:
- // - 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.
- // - SHOULD check that it has sufficient incoming liquidity from the
- // public network to be able to receive at least
- // payment_size_msat.
- if let Some(payment_size_msat) = payment_size_msat {
- let opening_fee = compute_opening_fee(
- payment_size_msat.msat(),
- self.min_fee_msat.msat(),
- self.proportional.ppm() as u64,
- )
- .ok_or(Error::PaymentSizeTooLarge)?;
- if opening_fee >= payment_size_msat.msat() {
- return Err(Error::PaymentSizeTooSmall);
- }
-
- if let Some(rec) = receivable {
- if opening_fee >= rec.msat() {
- return Err(Error::PaymentSizeTooLarge);
- }
- }
- }
-
- Ok(())
- }
-}
-
-#[derive(Debug, Clone, 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, Serialize, Deserialize, PartialEq)]
-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,
-}
-
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Lsps2PolicyGetInfoRequest {
#[serde(skip_serializing_if = "Option::is_none")]
@@ -306,10 +72,10 @@ pub struct PolicyOpeningFeeParams {
impl PolicyOpeningFeeParams {
pub fn get_hmac_hex(&self, secret: &[u8]) -> String {
- let mut hmac = HmacEngine::<sha256::Hash>::new(&secret);
+ let mut hmac = HmacEngine::<sha256::Hash>::new(secret);
hmac.input(&self.min_fee_msat.msat().to_be_bytes());
hmac.input(&self.proportional.ppm().to_be_bytes());
- hmac.input(self.valid_until.to_rfc3339().as_bytes());
+ hmac.input(self.valid_until.as_chrono().to_rfc3339().as_bytes());
hmac.input(&self.min_lifetime.to_be_bytes());
hmac.input(&self.max_client_to_self_delay.to_be_bytes());
hmac.input(&self.min_payment_size_msat.msat().to_be_bytes());
@@ -331,11 +97,32 @@ impl PolicyOpeningFeeParams {
max_client_to_self_delay: self.max_client_to_self_delay,
min_payment_size_msat: self.min_payment_size_msat,
max_payment_size_msat: self.max_payment_size_msat,
- promise: Promise(self.get_hmac_hex(secret)),
+ promise: Promise::try_from(self.get_hmac_hex(secret))
+ .expect("hex HMAC is a valid promise"),
+ }
+ }
+}
+
+impl From<&OpeningFeeParams> for PolicyOpeningFeeParams {
+ fn from(params: &OpeningFeeParams) -> Self {
+ PolicyOpeningFeeParams {
+ min_fee_msat: params.min_fee_msat,
+ proportional: params.proportional,
+ valid_until: params.valid_until,
+ min_lifetime: params.min_lifetime,
+ max_client_to_self_delay: params.max_client_to_self_delay,
+ min_payment_size_msat: params.min_payment_size_msat,
+ max_payment_size_msat: params.max_payment_size_msat,
}
}
}
+/// LSPs MUST check that the opening_fee_params.promise does in fact prove
+/// that it previously promised the specified opening_fee_params.
+pub fn verify_promise(params: &OpeningFeeParams, secret: &[u8]) -> bool {
+ PolicyOpeningFeeParams::from(params).get_hmac_hex(secret) == params.promise.as_str()
+}
+
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DatastoreEntry {
pub peer_id: cln_rpc::primitives::PublicKey,
@@ -344,349 +131,54 @@ pub struct DatastoreEntry {
pub expected_payment_size: Option<Msat>,
}
-/// 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))
-}
-
#[cfg(test)]
mod tests {
- use chrono::Duration;
+ use chrono::{Duration, Utc};
use super::*;
- // Helper struct for testing Serde
- #[derive(Serialize, Deserialize, Debug, PartialEq)]
- struct TestData {
- label: String,
- value: Promise,
- }
+ const SECRET: &[u8; 32] = b"test_secret_key_32_bytes_long___";
- // Helper function to create valid opening fee params
- fn create_valid_opening_fee_params(secret: &[u8]) -> OpeningFeeParams {
- let params = OpeningFeeParams {
+ fn policy() -> PolicyOpeningFeeParams {
+ PolicyOpeningFeeParams {
min_fee_msat: Msat::from_msat(1000),
- proportional: Ppm::from_ppm(1000), // 0.1%
- valid_until: Utc::now() + Duration::hours(1), // Valid for 1 hour
- 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("placeholder".to_string()), // Will be replaced
- };
-
- // Compute the correct promise
- let mut hmac = HmacEngine::<sha256::Hash>::new(secret);
- hmac.input(¶ms.min_fee_msat.msat().to_be_bytes());
- hmac.input(¶ms.proportional.ppm().to_be_bytes());
- hmac.input(params.valid_until.to_rfc3339().as_bytes());
- hmac.input(¶ms.min_lifetime.to_be_bytes());
- hmac.input(¶ms.max_client_to_self_delay.to_be_bytes());
- hmac.input(¶ms.min_payment_size_msat.msat().to_be_bytes());
- hmac.input(¶ms.max_payment_size_msat.msat().to_be_bytes());
- let promise: String = Hmac::from_engine(hmac)
- .to_byte_array()
- .iter()
- .map(|b| format!("{:02x}", b))
- .collect();
-
- OpeningFeeParams {
- promise: Promise(promise),
- ..params
+ proportional: Ppm::from_ppm(1000),
+ valid_until: (Utc::now() + Duration::hours(1)).into(),
+ min_lifetime: 144,
+ max_client_to_self_delay: 2016,
+ min_payment_size_msat: Msat::from_msat(1000),
+ max_payment_size_msat: Msat::from_msat(100_000_000_000),
}
}
#[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");
+ fn test_verify_promise_success() {
+ let params = policy().with_promise(SECRET);
+ assert_eq!(params.promise.as_str().len(), 64);
+ assert!(verify_promise(¶ms, SECRET));
}
#[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")
- );
- }
-
- #[test]
- fn test_validate_success_minimal() {
- let secret = b"test_secret_key_32_bytes_long___";
- let params = create_valid_opening_fee_params(secret);
-
- let result = params.validate(secret, None, None);
- assert!(
- result.is_ok(),
- "Valid params with no payment_size should succeed"
- );
- }
-
- #[test]
- fn test_validate_success_with_payment_size() {
- let secret = b"test_secret_key_32_bytes_long___";
- let params = create_valid_opening_fee_params(secret);
- let payment_size = Msat::from_msat(10_000_000); // 10M msat
-
- let result = params.validate(secret, Some(payment_size), None);
- assert!(
- result.is_ok(),
- "Valid params with valid payment_size should succeed"
- );
- }
-
- #[test]
- fn test_validate_success_with_payment_size_and_receivable() {
- let secret = b"test_secret_key_32_bytes_long___";
- let params = create_valid_opening_fee_params(secret);
- let payment_size = Msat::from_msat(10_000_000); // 10M msat
- let receivable = Msat::from_msat(50_000_000); // 50M msat
-
- let result = params.validate(secret, Some(payment_size), Some(receivable));
- assert!(
- result.is_ok(),
- "Valid params with payment_size and receivable should succeed"
- );
- }
-
- #[test]
- fn test_validate_invalid_promise() {
- let secret = b"test_secret_key_32_bytes_long___";
- let mut params = create_valid_opening_fee_params(secret);
+ fn test_verify_promise_changed_param() {
+ let mut params = policy().with_promise(SECRET);
params.min_fee_msat = Msat(10);
-
- let result = params.validate(secret, None, None);
- assert!(
- matches!(result, Err(Error::InvalidOpeningFeeParams)),
- "Invalid promise should fail validation"
- );
- }
-
- #[test]
- fn test_validate_wrong_secret() {
- let secret1 = b"test_secret_key_32_bytes_long___";
- let secret2 = b"different_secret_key_32_bytes___";
- let params = create_valid_opening_fee_params(secret1);
-
- let result = params.validate(secret2, None, None);
- assert!(
- matches!(result, Err(Error::InvalidOpeningFeeParams)),
- "Wrong secret should fail validation"
- );
- }
-
- #[test]
- fn test_validate_expired_timestamp() {
- let secret = b"test_secret_key_32_bytes_long___";
- let mut params = create_valid_opening_fee_params(secret);
- params.valid_until = Utc::now() - Duration::hours(1); // Expired 1 hour ago
-
- // Recompute promise with expired timestamp
- let mut hmac = HmacEngine::<sha256::Hash>::new(secret);
- hmac.input(¶ms.min_fee_msat.msat().to_be_bytes());
- hmac.input(¶ms.proportional.ppm().to_be_bytes());
- hmac.input(params.valid_until.to_rfc3339().as_bytes());
- hmac.input(¶ms.min_lifetime.to_be_bytes());
- hmac.input(¶ms.max_client_to_self_delay.to_be_bytes());
- hmac.input(¶ms.min_payment_size_msat.msat().to_be_bytes());
- hmac.input(¶ms.max_payment_size_msat.msat().to_be_bytes());
- let promise: String = Hmac::from_engine(hmac)
- .to_byte_array()
- .iter()
- .map(|b| format!("{:02x}", b))
- .collect();
- params.promise = Promise(promise);
-
- let result = params.validate(secret, None, None);
- assert!(
- matches!(result, Err(Error::InvalidOpeningFeeParams)),
- "Expired timestamp should fail validation"
- );
+ assert!(!verify_promise(¶ms, SECRET));
}
#[test]
- fn test_validate_payment_size_overflow() {
- let secret = b"test_secret_key_32_bytes_long___";
- let mut params = create_valid_opening_fee_params(secret);
- // Set proportional fee high enough to cause overflow
- params.proportional = Ppm::from_ppm(u32::MAX);
-
- // Recompute promise
- let mut hmac = HmacEngine::<sha256::Hash>::new(secret);
- hmac.input(¶ms.min_fee_msat.msat().to_be_bytes());
- hmac.input(¶ms.proportional.ppm().to_be_bytes());
- hmac.input(params.valid_until.to_rfc3339().as_bytes());
- hmac.input(¶ms.min_lifetime.to_be_bytes());
- hmac.input(¶ms.max_client_to_self_delay.to_be_bytes());
- hmac.input(¶ms.min_payment_size_msat.msat().to_be_bytes());
- hmac.input(¶ms.max_payment_size_msat.msat().to_be_bytes());
- let promise: String = Hmac::from_engine(hmac)
- .to_byte_array()
- .iter()
- .map(|b| format!("{:02x}", b))
- .collect();
- params.promise = Promise(promise);
-
- let payment_size = Msat::from_msat(u64::MAX);
- let result = params.validate(secret, Some(payment_size), None);
- assert!(
- matches!(result, Err(Error::PaymentSizeTooLarge)),
- "Overflow in fee calculation should return PaymentSizeTooLarge"
- );
- }
-
- #[test]
- fn test_validate_opening_fee_equals_payment_size() {
- let secret = b"test_secret_key_32_bytes_long___";
- let params = create_valid_opening_fee_params(secret);
-
- // Find a payment size where opening fee equals payment size
- // With min_fee_msat = 1000 and proportional = 1000 (0.1%)
- // The opening fee will be max(1000, payment * 1000 / 1_000_000)
- // So for small payments, fee = 1000
- let payment_size = Msat::from_msat(1000); // Same as min_fee_msat
-
- let result = params.validate(secret, Some(payment_size), None);
- assert!(
- matches!(result, Err(Error::PaymentSizeTooSmall)),
- "Opening fee equal to payment size should fail"
- );
- }
-
- #[test]
- fn test_validate_opening_fee_greater_than_payment_size() {
- let secret = b"test_secret_key_32_bytes_long___";
- let params = create_valid_opening_fee_params(secret);
-
- // Payment size smaller than minimum fee
- let payment_size = Msat::from_msat(500); // Less than min_fee_msat (1000)
-
- let result = params.validate(secret, Some(payment_size), None);
- assert!(
- matches!(result, Err(Error::PaymentSizeTooSmall)),
- "Opening fee greater than payment size should fail"
- );
+ fn test_verify_promise_wrong_secret() {
+ let params = policy().with_promise(SECRET);
+ assert!(!verify_promise(
+ ¶ms,
+ b"different_secret_key_32_bytes___"
+ ));
}
#[test]
- fn test_validate_opening_fee_equals_receivable() {
- let secret = b"test_secret_key_32_bytes_long___";
- let params = create_valid_opening_fee_params(secret);
-
- let payment_size = Msat::from_msat(10_000_000); // 10M msat
- let receivable = Msat::from_msat(1000); // Same as min_fee_msat
-
- let result = params.validate(secret, Some(payment_size), Some(receivable));
- assert!(
- matches!(result, Err(Error::PaymentSizeTooLarge)),
- "Opening fee equal to receivable should fail"
- );
- }
-
- #[test]
- fn test_validate_opening_fee_greater_than_receivable() {
- let secret = b"test_secret_key_32_bytes_long___";
- let params = create_valid_opening_fee_params(secret);
-
- let payment_size = Msat::from_msat(10_000_000); // 10M msat
- let receivable = Msat::from_msat(500); // Less than min_fee_msat (1000)
-
- let result = params.validate(secret, Some(payment_size), Some(receivable));
- assert!(
- matches!(result, Err(Error::PaymentSizeTooLarge)),
- "Opening fee greater than receivable should fail"
- );
- }
-
- #[test]
- fn test_validate_large_payment_proportional_fee() {
- let secret = b"test_secret_key_32_bytes_long___";
- let params = create_valid_opening_fee_params(secret);
-
- // Large payment where proportional fee dominates
- // Opening fee = max(1000, 1_000_000_000 * 1000 / 1_000_000) = max(1000, 1_000_000) = 1_000_000
- let payment_size = Msat::from_msat(1_000_000_000);
-
- let result = params.validate(secret, Some(payment_size), None);
- assert!(
- result.is_ok(),
- "Large payment with proportional fee should succeed"
- );
- }
-
- #[test]
- fn test_validate_max_values() {
- let secret = b"test_secret_key_32_bytes_long___";
- let mut params = OpeningFeeParams {
- min_fee_msat: Msat::from_msat(u64::MAX / 1000), // Avoid overflow
- proportional: Ppm::from_ppm(100), // Small proportional to avoid overflow
- valid_until: Utc::now() + Duration::hours(1),
- 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),
- promise: Promise("placeholder".to_string()),
- };
-
- // Compute promise
- let mut hmac = HmacEngine::<sha256::Hash>::new(secret);
- hmac.input(¶ms.min_fee_msat.msat().to_be_bytes());
- hmac.input(¶ms.proportional.ppm().to_be_bytes());
- hmac.input(params.valid_until.to_rfc3339().as_bytes());
- hmac.input(¶ms.min_lifetime.to_be_bytes());
- hmac.input(¶ms.max_client_to_self_delay.to_be_bytes());
- hmac.input(¶ms.min_payment_size_msat.msat().to_be_bytes());
- hmac.input(¶ms.max_payment_size_msat.msat().to_be_bytes());
- let promise: String = Hmac::from_engine(hmac)
- .to_byte_array()
- .iter()
- .map(|b| format!("{:02x}", b))
- .collect();
- params.promise = Promise(promise);
-
- let result = params.validate(secret, None, None);
- assert!(result.is_ok(), "Maximum safe values should be valid");
+ fn test_verify_promise_survives_serde() {
+ let params = policy().with_promise(SECRET);
+ let json = serde_json::to_string(¶ms).unwrap();
+ let back: OpeningFeeParams = serde_json::from_str(&json).unwrap();
+ assert!(verify_promise(&back, SECRET));
}
}
### plugins/lsps-plugin/src/proto/mod.rs
@@ -1,4 +1,3 @@
-#[macro_use]
pub mod jsonrpc;
pub mod lsps0;
pub mod lsps2;
### plugins/lsps-plugin/src/service.rs
@@ -12,7 +12,7 @@ use cln_lsps::{
},
server::LspsService,
},
- proto::lsps0::{LSPS0_MESSAGE_TYPE, Msat},
+ proto::lsps0::{LSPS0_MESSAGE_TYPE, Msat, ShortChannelId},
};
use cln_plugin::{HookBuilder, HookFilter, Plugin, options};
use log::{debug, error, trace};
@@ -175,7 +175,7 @@ async fn handle_htlc_inner(
let handler = HtlcAcceptedHookHandler::new(api, 1000);
let onion = Onion {
- short_channel_id,
+ short_channel_id: ShortChannelId::from(short_channel_id.to_u64()),
payload: req.onion.payload,
};
Why this scored 24/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.