tests: mock LSPS2 service charges the opening fee from its params
What changed, and why it matters
This commit only changes test code. It updates a mock Lightning Service Provider (LSP) used in Core Lightning's test suite so that its simulated 'opening fee' follows the real bLIP-52 formula instead of being a hardcoded test value. No production wallet, node, or protocol code is touched, so it cannot directly affect real users or funds.
No security action required. Review as normal test-quality change.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The diff modifies tests/plugins/lsps2_mock.py and tests/test_cln_lsps.py. The mock plugin now imports lsps2_mock_fee.opening_fee and computes the LSPS2 opening fee from the advertised params (min_fee_msat + proportional * payment_size). It adds validation in lsps2.buy (error 202 when fee >= payment size, error 203 on overflow) and in the no-MPP+var-invoice path (fail HTLCs whose amount is outside payment-size limits, overflows, or leaves nothing to forward). Tests are updated to exercise these new fee checks. The change is purely in test infrastructure.
Changed components
tests/plugins/lsps2_mock.pytests/test_cln_lsps.pyInspect captured patch +152 / −33
### tests/plugins/lsps2_mock.py
@@ -9,7 +9,7 @@
- answers `lsps0.list_protocols`, `lsps2.get_info` and `lsps2.buy`,
- intercepts the HTLCs sent to a `jit_channel_scid`, opens a zero-conf
channel to the client and forwards the parts with the opening fee
- deducted.
+ deducted. The fee comes from lsps2_mock_fee.py.
What the mock does is driven by a config with one entry per phase:
`transport`, `list_protocols`, `get_info`, `buy`, `open` and `htlc`. Each
@@ -29,6 +29,7 @@
from copy import deepcopy
from datetime import datetime, timedelta, timezone
+from lsps2_mock_fee import FeeOverflow, opening_fee
from pyln.client import Plugin, RpcError, RpcException
from pyln.client.plugin import RequestState
@@ -78,7 +79,9 @@
"client_trusts_lsp": False,
},
"open": {"behavior": "honest", "capacity_sat": 100_000},
- "htlc": {"behavior": "honest", "fee_msat": 0},
+ # `fee_msat` is the fee to deduct; None deducts the opening fee computed
+ # from the session's params.
+ "htlc": {"behavior": "honest", "fee_msat": None},
}
REQUIRED = object()
@@ -124,7 +127,7 @@
"deduct": {"deductions": REQUIRED, "extra_fees": None},
# Forward only the parts with these indices, fail the others.
"forward_subset": {"parts": REQUIRED},
- # Deduct `fee_msat` again from payments after the session.
+ # Deduct the fee again from payments after the session.
"deduct_again": {},
},
}
@@ -141,11 +144,14 @@ def __init__(self, code, message, data=None):
class Session:
- def __init__(self, scid, peer_id, params, payment_size_msat):
+ def __init__(self, scid, peer_id, params, payment_size_msat, opening_fee_msat):
self.scid = scid
self.peer_id = peer_id
self.params = params
self.payment_size_msat = payment_size_msat
+ # Known at buy in MPP+fixed-invoice mode, set by the first HTLC in
+ # no-MPP+var-invoice mode.
+ self.opening_fee_msat = opening_fee_msat
# collecting -> opening -> forwarded
self.state = "collecting"
self.parts = []
@@ -158,6 +164,7 @@ def to_json(self):
"peer_id": self.peer_id,
"opening_fee_params": self.params,
"payment_size_msat": self.payment_size_msat,
+ "opening_fee_msat": self.opening_fee_msat,
"state": self.state,
"channel_id": self.channel_id,
}
@@ -442,6 +449,7 @@ def buy(peer_id, params):
raise LspsError(201, "invalid_opening_fee_params")
payment_size_msat = None
+ fee_msat = None
if "payment_size_msat" in params:
try:
payment_size_msat = int(params["payment_size_msat"])
@@ -451,11 +459,17 @@ def buy(peer_id, params):
raise LspsError(202, "payment_size_too_small")
if payment_size_msat > int(ofp["max_payment_size_msat"]):
raise LspsError(203, "payment_size_too_large")
+ try:
+ fee_msat = params_fee(ofp, payment_size_msat)
+ except FeeOverflow:
+ raise LspsError(203, "payment_size_too_large")
+ if fee_msat >= payment_size_msat:
+ raise LspsError(202, "payment_size_too_small")
with state.lock:
state.scid_counter += 1
scid = cfg["jit_channel_scid"] or f"{SCID_BLOCK}x{state.scid_counter}x0"
- session = Session(scid, peer_id, ofp, payment_size_msat)
+ session = Session(scid, peer_id, ofp, payment_size_msat, fee_msat)
state.sessions[scid] = session
record("buy", **session.to_json())
@@ -466,6 +480,12 @@ def buy(peer_id, params):
}
+def params_fee(ofp, payment_size_msat):
+ return opening_fee(
+ payment_size_msat, int(ofp["min_fee_msat"]), int(ofp["proportional"])
+ )
+
+
METHODS = {
"lsps0.list_protocols": list_protocols,
"lsps2.get_info": get_info,
@@ -505,6 +525,7 @@ def wrapper(session):
parts = {id(p): p for p in held + session.parts}.values()
fail_parts(
[p for p in parts if p["request"].state == RequestState.PENDING],
+ "error",
TEMPORARY_NODE_FAILURE,
)
session.parts = []
@@ -527,7 +548,7 @@ def open_channel(session):
if cfg["behavior"] == "never":
record("open_skipped", jit_channel_scid=session.scid)
with state.lock:
- fail_parts(session.parts)
+ fail_parts(session.parts, "open_skipped")
session.parts = []
session.state = "collecting"
return
@@ -548,6 +569,7 @@ def open_channel(session):
with state.lock:
fail_parts(
session.parts,
+ "open_failed",
UNKNOWN_NEXT_PEER if connected else TEMPORARY_CHANNEL_FAILURE,
)
session.parts = []
@@ -594,12 +616,13 @@ def on_channel_state_changed(channel_state_changed, **kwargs):
# --- HTLC interception and forwarding --------------------------------------
-def fail_parts(parts, failure_message=UNKNOWN_NEXT_PEER):
+def fail_parts(parts, reason, failure_message=UNKNOWN_NEXT_PEER):
for part in parts:
record(
"htlc",
payment_hash=part["htlc"]["payment_hash"],
decision="fail",
+ reason=reason,
failure_message=failure_message,
)
part["request"].set_result(
@@ -670,22 +693,52 @@ def release(session):
return
if cfg["behavior"] == "forward_subset":
- fail_parts([p for i, p in enumerate(parts) if i not in cfg["parts"]])
+ fail_parts(
+ [p for i, p in enumerate(parts) if i not in cfg["parts"]],
+ "forward_subset",
+ )
parts = [p for i, p in enumerate(parts) if i in cfg["parts"]]
- forward_with_fee(session, parts, cfg["fee_msat"])
+ forward_with_fee(session, parts, session_fee(session))
+
+
+def session_fee(session):
+ fee_msat = state.config["htlc"]["fee_msat"]
+ return session.opening_fee_msat if fee_msat is None else fee_msat
def forward_with_fee(session, parts, fee_msat):
amounts = [int(p["onion"]["forward_msat"]) for p in parts]
deductions = split_fee(amounts, fee_msat, session.htlc_minimum_msat)
if deductions is None:
- fail_parts(parts)
+ fail_parts(parts, "fee_exceeds_parts")
return
for part, deduction in zip(parts, deductions):
forward_part(session, part, deduction, deduction or None)
+def var_invoice_fee(session, amount_msat):
+ """no-MPP+var-invoice: the opening fee for the first HTLC, whose onion
+ amount is the payment size, or None if the LSP must fail it."""
+ ofp = session.params
+ if not (
+ int(ofp["min_payment_size_msat"])
+ <= amount_msat
+ <= int(ofp["max_payment_size_msat"])
+ ):
+ return None
+ try:
+ fee_msat = params_fee(ofp, amount_msat)
+ except FeeOverflow:
+ return None
+ # bLIP-52 requires opening_fee + htlc_minimum_msat <= htlc_value_msat.
+ # The channel's htlc_minimum_msat is only known once it is open, and
+ # release() checks it then; here use the 1 msat every HTLC needs.
+ if fee_msat + 1 > amount_msat:
+ return None
+ return fee_msat
+
+
def collected_enough(session):
if session.payment_size_msat is None:
# no-MPP+var-invoice: the first part is the payment.
@@ -707,11 +760,19 @@ def on_htlc_accepted(onion, htlc, request, **kwargs):
if session.state == "forwarded":
# The session is done; the jit_channel_scid is now just another
# alias of the channel.
- cfg = state.config["htlc"]
- fee_msat = cfg["fee_msat"] if cfg["behavior"] == "deduct_again" else 0
- forward_with_fee(session, [part], fee_msat)
+ again = state.config["htlc"]["behavior"] == "deduct_again"
+ forward_with_fee(session, [part], session_fee(session) if again else 0)
return
+ # In no-MPP+var-invoice mode the first part opens the channel, so a
+ # collecting session has no parts yet.
+ if session.payment_size_msat is None and session.state == "collecting":
+ fee_msat = var_invoice_fee(session, int(onion["forward_msat"]))
+ if fee_msat is None:
+ fail_parts([part], "payment_size")
+ return
+ session.opening_fee_msat = fee_msat
+
session.parts.append(part)
if session.state == "collecting" and collected_enough(session):
session.state = "opening"
### tests/test_cln_lsps.py
@@ -396,10 +396,10 @@ def lsps2_mock_nodes(node_factory, client_opts=None):
return l1, l2, l3
-def lsps2_mock_menu_entry(min_fee_msat):
+def lsps2_mock_menu_entry(min_fee_msat, proportional=0):
return {
"min_fee_msat": str(min_fee_msat),
- "proportional": 0,
+ "proportional": proportional,
"min_lifetime": 1008,
"max_client_to_self_delay": 2016,
"min_payment_size_msat": "1000",
@@ -578,20 +578,16 @@ def test_lsps2_mock_protocol_errors(node_factory):
def test_lsps2_mock_jit_channel_var_invoice(node_factory):
"""no-MPP+var-invoice: the mock opens a channel on the first HTLC and
- forwards it with the opening fee deducted."""
+ forwards it with the opening fee for its amount deducted."""
l1, l2, l3 = lsps2_mock_nodes(node_factory)
- fee_msat = 1_000_000
+ menu_entry = lsps2_mock_menu_entry(1000, proportional=10_000)
l2.rpc.call(
- "lsps2-mock-configure",
- {
- "config": {
- "get_info": {"menu": [lsps2_mock_menu_entry(fee_msat)]},
- "htlc": {"fee_msat": fee_msat},
- }
- },
+ "lsps2-mock-configure", {"config": {"get_info": {"menu": [menu_entry]}}}
)
amt = 10_000_000
+ fee_msat = lsps2_mock_fee.opening_fee(amt, 1000, 10_000)
+ assert fee_msat == 100_000
assert lsps2_mock_pay_var_invoice(l1, l2, l3, amt)["payment_preimage"]
fwd = only_one(lsps2_mock_forwards(l2))
@@ -606,20 +602,16 @@ def test_lsps2_mock_jit_channel_var_invoice(node_factory):
def test_lsps2_mock_jit_channel_mpp_fixed_invoice(node_factory):
"""MPP+fixed-invoice: the mock waits for all parts, then forwards them
- with the opening fee spread over the parts."""
+ with the opening fee for the payment size spread over the parts."""
l1, l2, l3 = lsps2_mock_nodes(node_factory)
- fee_msat = 1_500_000
+ menu_entry = lsps2_mock_menu_entry(1000, proportional=150_000)
l2.rpc.call(
- "lsps2-mock-configure",
- {
- "config": {
- "get_info": {"menu": [lsps2_mock_menu_entry(fee_msat)]},
- "htlc": {"fee_msat": fee_msat},
- }
- },
+ "lsps2-mock-configure", {"config": {"get_info": {"menu": [menu_entry]}}}
)
amt = 10_000_000
+ fee_msat = lsps2_mock_fee.opening_fee(amt, 1000, 150_000)
+ assert fee_msat == 1_500_000
inv = l1.rpc.lsps_lsps2_invoice(
lsp_id=l2.info["id"],
amount_msat=amt,
@@ -890,3 +882,69 @@ def test_lsps2_mock_fee():
fee(2**32, 0, 2**32)
with pytest.raises(ValueError):
fee(-1, 0, 0)
+
+
+def test_lsps2_mock_buy_fee_checks(node_factory):
+ """buy fails with 202 when the opening fee eats the payment and with 203
+ when computing it overflows."""
+ l1, l2 = node_factory.line_graph(
+ 2, fundchannel=False, opts=[{}, {"plugin": LSPS2_MOCK}]
+ )
+ u64_max = str(lsps2_mock_fee.U64_MAX)
+ menu = [
+ {**lsps2_mock_menu_entry(1_000_000), "max_payment_size_msat": u64_max},
+ {
+ **lsps2_mock_menu_entry(0, proportional=2**32 - 1),
+ "max_payment_size_msat": u64_max,
+ },
+ ]
+ l2.rpc.call("lsps2-mock-configure", {"config": {"get_info": {"menu": menu}}})
+ res = only_one(lsps2_mock_request(l1, l2, "lsps2.get_info", {}))
+ min_fee, proportional = res["result"]["opening_fee_params_menu"]
+
+ def buy(params, payment_size_msat):
+ return only_one(
+ lsps2_mock_request(
+ l1,
+ l2,
+ "lsps2.buy",
+ {
+ "opening_fee_params": params,
+ "payment_size_msat": str(payment_size_msat),
+ },
+ )
+ )
+
+ assert buy(min_fee, 1_000_000)["error"]["code"] == 202
+ assert "result" in buy(min_fee, 1_000_001)
+ with pytest.raises(lsps2_mock_fee.FeeOverflow):
+ lsps2_mock_fee.opening_fee(2**33, 0, 2**32 - 1)
+ assert buy(proportional, 2**33)["error"]["code"] == 203
+
+ sessions = l2.rpc.call("lsps2-mock-state")["sessions"]
+ assert only_one(sessions)["opening_fee_msat"] == 1_000_000
+
+
+@pytest.mark.parametrize("amt", [1000, 10_000_001])
+def test_lsps2_mock_var_invoice_payment_size(node_factory, amt):
+ """no-MPP+var-invoice: the mock fails a payment outside the size limits
+ or too small to carry the opening fee, without opening a channel."""
+ l1, l2, l3 = lsps2_mock_nodes(node_factory)
+ menu_entry = {
+ **lsps2_mock_menu_entry(1000),
+ "max_payment_size_msat": "10000000",
+ }
+ l2.rpc.call(
+ "lsps2-mock-configure", {"config": {"get_info": {"menu": [menu_entry]}}}
+ )
+
+ with pytest.raises(RpcError) as err:
+ lsps2_mock_pay_var_invoice(l1, l2, l3, amt)
+ # unknown_next_peer
+ assert err.value.error["data"]["failcode"] == 0x400A
+
+ fail = only_one(lsps2_mock_events(l2, "htlc"))
+ assert fail["decision"] == "fail"
+ assert fail["reason"] == "payment_size"
+ assert lsps2_mock_events(l2, "open") == []
+ assert l1.rpc.listpeerchannels()["channels"] == []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.