From c1cbe585afd3457e3c35f7508e3744b7e3abde3a Mon Sep 17 00:00:00 2001 From: Oleh Fomenko Date: Fri, 20 Nov 2026 00:45:33 +0200 Subject: [PATCH 1/3] sdk: Allow setting an invoice expiry in receive Add an optional `expiry` (seconds) to `LspInvoiceRequest`. The plugin passes it to CLN's `invoice` when no JIT channel is needed, and forwards it to `lsps-lsps2-invoice` for JIT channels; CLN ignores it there for now. When choosing LSP fee offers, the plugin now picks the one with the latest `valid_until`. Exposed in gl-sdk `Node::receive` (default None in Kotlin/Swift/Python), gl-sdk-napi, gl-sdk-cli (`--expiry`) and glclient `lsp_invoice`. BREAKING CHANGE: Rust `Node::receive` takes a new `expiry` argument. --- Cargo.lock | 1 + libs/gl-client-py/glclient/__init__.py | 4 +- libs/gl-client-py/glclient/greenlight.proto | 2 + libs/gl-client-py/glclient/greenlight_pb2.py | 30 ++++---- libs/gl-client-py/glclient/greenlight_pb2.pyi | 10 ++- libs/gl-client-py/src/node.rs | 6 +- libs/gl-client-py/tests/test_plugin.py | 75 +++++++++++++++++++ .../proto/glclient/greenlight.proto | 2 + .../proto/glclient/greenlight.proto | 2 + libs/gl-plugin/Cargo.toml | 1 + libs/gl-plugin/src/node/mod.rs | 73 +++++++++++------- libs/gl-plugin/src/requests.rs | 9 ++- libs/gl-sdk-cli/src/node.rs | 9 ++- libs/gl-sdk-napi/src/lib.rs | 5 +- libs/gl-sdk/bindings/glsdk.swift | 27 ++++--- libs/gl-sdk/bindings/glsdkFFI.h | 2 +- libs/gl-sdk/glsdk/glsdk.py | 32 +++++--- libs/gl-sdk/src/node.rs | 4 + .../proto/glclient/greenlight.proto | 2 + libs/proto/glclient/greenlight.proto | 2 + 20 files changed, 227 insertions(+), 71 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7a279e23b..8f49e4eff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1563,6 +1563,7 @@ dependencies = [ "async-stream", "base64 0.21.7", "bytes", + "chrono", "clightningrpc", "cln-grpc", "cln-plugin", diff --git a/libs/gl-client-py/glclient/__init__.py b/libs/gl-client-py/glclient/__init__.py index a3b72eefc..bc40d5a99 100644 --- a/libs/gl-client-py/glclient/__init__.py +++ b/libs/gl-client-py/glclient/__init__.py @@ -569,10 +569,10 @@ def wait(self, subsystem, indexname, nextvalue: int) -> clnpb.WaitResponse: res = clnpb.WaitResponse return res.FromString(bytes(self.inner.call(uri, bytes(req)))) - def lsp_invoice(self, label: str, description: str, amount_msat: int | None = None): + def lsp_invoice(self, label: str, description: str, amount_msat: int | None = None, expiry: int | None = None): uri = "/greenlight.Node/LspInvoice" req = nodepb.LspInvoiceRequest( - label=label, description=description, amount_msat=amount_msat + label=label, description=description, amount_msat=amount_msat, expiry=expiry ).SerializeToString() res = nodepb.LspInvoiceResponse return res.FromString(bytes(self.inner.call(uri, bytes(req)))) diff --git a/libs/gl-client-py/glclient/greenlight.proto b/libs/gl-client-py/glclient/greenlight.proto index b11d03ae2..bf7be1d8a 100644 --- a/libs/gl-client-py/glclient/greenlight.proto +++ b/libs/gl-client-py/glclient/greenlight.proto @@ -244,7 +244,9 @@ message LspInvoiceRequest { uint64 amount_msat = 3; // 0 => Any string description = 4; string label = 5; + optional uint64 expiry = 6; } + message LspInvoiceResponse { string bolt11 = 1; uint32 created_index = 2; diff --git a/libs/gl-client-py/glclient/greenlight_pb2.py b/libs/gl-client-py/glclient/greenlight_pb2.py index d729b43ed..148b9b53e 100644 --- a/libs/gl-client-py/glclient/greenlight_pb2.py +++ b/libs/gl-client-py/glclient/greenlight_pb2.py @@ -24,7 +24,7 @@ -DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x19glclient/greenlight.proto\x12\ngreenlight\"H\n\x11HsmRequestContext\x12\x0f\n\x07node_id\x18\x01 \x01(\x0c\x12\x0c\n\x04\x64\x62id\x18\x02 \x01(\x04\x12\x14\n\x0c\x63\x61pabilities\x18\x03 \x01(\x04\"q\n\x0bHsmResponse\x12\x12\n\nrequest_id\x18\x01 \x01(\r\x12\x0b\n\x03raw\x18\x02 \x01(\x0c\x12\x32\n\x0csigner_state\x18\x05 \x03(\x0b\x32\x1c.greenlight.SignerStateEntry\x12\r\n\x05\x65rror\x18\x06 \x01(\t\"\xbf\x01\n\nHsmRequest\x12\x12\n\nrequest_id\x18\x01 \x01(\r\x12.\n\x07\x63ontext\x18\x02 \x01(\x0b\x32\x1d.greenlight.HsmRequestContext\x12\x0b\n\x03raw\x18\x03 \x01(\x0c\x12\x32\n\x0csigner_state\x18\x04 \x03(\x0b\x32\x1c.greenlight.SignerStateEntry\x12,\n\x08requests\x18\x05 \x03(\x0b\x32\x1a.greenlight.PendingRequest\"\x07\n\x05\x45mpty\"l\n\x06\x41mount\x12\x16\n\x0cmillisatoshi\x18\x01 \x01(\x04H\x00\x12\x11\n\x07satoshi\x18\x02 \x01(\x04H\x00\x12\x11\n\x07\x62itcoin\x18\x03 \x01(\x04H\x00\x12\r\n\x03\x61ll\x18\x04 \x01(\x08H\x00\x12\r\n\x03\x61ny\x18\x05 \x01(\x08H\x00\x42\x06\n\x04unit\"\x16\n\x14StreamIncomingFilter\"\'\n\x08TlvField\x12\x0c\n\x04type\x18\x01 \x01(\x04\x12\r\n\x05value\x18\x02 \x01(\x0c\"\xa5\x01\n\x0fOffChainPayment\x12\r\n\x05label\x18\x01 \x01(\t\x12\x10\n\x08preimage\x18\x02 \x01(\x0c\x12\"\n\x06\x61mount\x18\x03 \x01(\x0b\x32\x12.greenlight.Amount\x12\'\n\textratlvs\x18\x04 \x03(\x0b\x32\x14.greenlight.TlvField\x12\x14\n\x0cpayment_hash\x18\x05 \x01(\x0c\x12\x0e\n\x06\x62olt11\x18\x06 \x01(\t\"M\n\x0fIncomingPayment\x12/\n\x08offchain\x18\x01 \x01(\x0b\x32\x1b.greenlight.OffChainPaymentH\x00\x42\t\n\x07\x64\x65tails\"\x12\n\x10StreamLogRequest\"\x18\n\x08LogEntry\x12\x0c\n\x04line\x18\x01 \x01(\t\"R\n\x10SignerStateEntry\x12\x0f\n\x07version\x18\x01 \x01(\x04\x12\x0b\n\x03key\x18\x02 \x01(\t\x12\r\n\x05value\x18\x03 \x01(\x0c\x12\x11\n\tsignature\x18\x04 \x01(\x0c\"r\n\x0ePendingRequest\x12\x0f\n\x07request\x18\x01 \x01(\x0c\x12\x0b\n\x03uri\x18\x02 \x01(\t\x12\x11\n\tsignature\x18\x03 \x01(\x0c\x12\x0e\n\x06pubkey\x18\x04 \x01(\x0c\x12\x11\n\ttimestamp\x18\x05 \x01(\x04\x12\x0c\n\x04rune\x18\x06 \x01(\x0c\"=\n\nNodeConfig\x12/\n\x0bstartupmsgs\x18\x01 \x03(\x0b\x32\x1a.greenlight.StartupMessage\"!\n\x08GlConfig\x12\x15\n\rclose_to_addr\x18\x01 \x01(\t\"3\n\x0eStartupMessage\x12\x0f\n\x07request\x18\x01 \x01(\x0c\x12\x10\n\x08response\x18\x02 \x01(\x0c\"\x18\n\x16StreamCustommsgRequest\"-\n\tCustommsg\x12\x0f\n\x07peer_id\x18\x01 \x01(\x0c\x12\x0f\n\x07payload\x18\x02 \x01(\x0c\"\xa4\x01\n\x14TrampolinePayRequest\x12\x0e\n\x06\x62olt11\x18\x01 \x01(\t\x12\x1a\n\x12trampoline_node_id\x18\x02 \x01(\x0c\x12\x13\n\x0b\x61mount_msat\x18\x03 \x01(\x04\x12\r\n\x05label\x18\x04 \x01(\t\x12\x15\n\rmaxfeepercent\x18\x05 \x01(\x02\x12\x10\n\x08maxdelay\x18\x06 \x01(\r\x12\x13\n\x0b\x64\x65scription\x18\x07 \x01(\t\"\xd5\x01\n\x15TrampolinePayResponse\x12\x18\n\x10payment_preimage\x18\x01 \x01(\x0c\x12\x14\n\x0cpayment_hash\x18\x02 \x01(\x0c\x12\x12\n\ncreated_at\x18\x03 \x01(\x01\x12\r\n\x05parts\x18\x04 \x01(\r\x12\x13\n\x0b\x61mount_msat\x18\x05 \x01(\x04\x12\x18\n\x10\x61mount_sent_msat\x18\x06 \x01(\x04\x12\x13\n\x0b\x64\x65stination\x18\x07 \x01(\x0c\"%\n\tPayStatus\x12\x0c\n\x08\x43OMPLETE\x10\x00\x12\n\n\x06\x46\x41ILED\x10\x02\"k\n\x11LspInvoiceRequest\x12\x0e\n\x06lsp_id\x18\x01 \x01(\t\x12\r\n\x05token\x18\x02 \x01(\t\x12\x13\n\x0b\x61mount_msat\x18\x03 \x01(\x04\x12\x13\n\x0b\x64\x65scription\x18\x04 \x01(\t\x12\r\n\x05label\x18\x05 \x01(\t\"\x97\x01\n\x12LspInvoiceResponse\x12\x0e\n\x06\x62olt11\x18\x01 \x01(\t\x12\x15\n\rcreated_index\x18\x02 \x01(\r\x12\x12\n\nexpires_at\x18\x03 \x01(\r\x12\x14\n\x0cpayment_hash\x18\x04 \x01(\x0c\x12\x16\n\x0epayment_secret\x18\x05 \x01(\x0c\x12\x18\n\x10opening_fee_msat\x18\x06 \x01(\x04\"\x13\n\x11NodeEventsRequest\"E\n\tNodeEvent\x12/\n\x0cinvoice_paid\x18\x01 \x01(\x0b\x32\x17.greenlight.InvoicePaidH\x00\x42\x07\n\x05\x65vent\"\x92\x01\n\x0bInvoicePaid\x12\x14\n\x0cpayment_hash\x18\x01 \x01(\x0c\x12\x0e\n\x06\x62olt11\x18\x02 \x01(\t\x12\x10\n\x08preimage\x18\x03 \x01(\x0c\x12\r\n\x05label\x18\x04 \x01(\t\x12\x13\n\x0b\x61mount_msat\x18\x05 \x01(\x04\x12\'\n\textratlvs\x18\x06 \x03(\x0b\x32\x14.greenlight.TlvField2\xa6\x05\n\x04Node\x12M\n\nLspInvoice\x12\x1d.greenlight.LspInvoiceRequest\x1a\x1e.greenlight.LspInvoiceResponse\"\x00\x12S\n\x0eStreamIncoming\x12 .greenlight.StreamIncomingFilter\x1a\x1b.greenlight.IncomingPayment\"\x00\x30\x01\x12\x43\n\tStreamLog\x12\x1c.greenlight.StreamLogRequest\x1a\x14.greenlight.LogEntry\"\x00\x30\x01\x12P\n\x0fStreamCustommsg\x12\".greenlight.StreamCustommsgRequest\x1a\x15.greenlight.Custommsg\"\x00\x30\x01\x12L\n\x10StreamNodeEvents\x12\x1d.greenlight.NodeEventsRequest\x1a\x15.greenlight.NodeEvent\"\x00\x30\x01\x12\x42\n\x11StreamHsmRequests\x12\x11.greenlight.Empty\x1a\x16.greenlight.HsmRequest\"\x00\x30\x01\x12\x41\n\x11RespondHsmRequest\x12\x17.greenlight.HsmResponse\x1a\x11.greenlight.Empty\"\x00\x12\x36\n\tConfigure\x12\x14.greenlight.GlConfig\x1a\x11.greenlight.Empty\"\x00\x12V\n\rTrampolinePay\x12 .greenlight.TrampolinePayRequest\x1a!.greenlight.TrampolinePayResponse\"\x00\x32s\n\x03Hsm\x12<\n\x07Request\x12\x16.greenlight.HsmRequest\x1a\x17.greenlight.HsmResponse\"\x00\x12.\n\x04Ping\x12\x11.greenlight.Empty\x1a\x11.greenlight.Empty\"\x00\x62\x06proto3') +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x19glclient/greenlight.proto\x12\ngreenlight\"H\n\x11HsmRequestContext\x12\x0f\n\x07node_id\x18\x01 \x01(\x0c\x12\x0c\n\x04\x64\x62id\x18\x02 \x01(\x04\x12\x14\n\x0c\x63\x61pabilities\x18\x03 \x01(\x04\"q\n\x0bHsmResponse\x12\x12\n\nrequest_id\x18\x01 \x01(\r\x12\x0b\n\x03raw\x18\x02 \x01(\x0c\x12\x32\n\x0csigner_state\x18\x05 \x03(\x0b\x32\x1c.greenlight.SignerStateEntry\x12\r\n\x05\x65rror\x18\x06 \x01(\t\"\xbf\x01\n\nHsmRequest\x12\x12\n\nrequest_id\x18\x01 \x01(\r\x12.\n\x07\x63ontext\x18\x02 \x01(\x0b\x32\x1d.greenlight.HsmRequestContext\x12\x0b\n\x03raw\x18\x03 \x01(\x0c\x12\x32\n\x0csigner_state\x18\x04 \x03(\x0b\x32\x1c.greenlight.SignerStateEntry\x12,\n\x08requests\x18\x05 \x03(\x0b\x32\x1a.greenlight.PendingRequest\"\x07\n\x05\x45mpty\"l\n\x06\x41mount\x12\x16\n\x0cmillisatoshi\x18\x01 \x01(\x04H\x00\x12\x11\n\x07satoshi\x18\x02 \x01(\x04H\x00\x12\x11\n\x07\x62itcoin\x18\x03 \x01(\x04H\x00\x12\r\n\x03\x61ll\x18\x04 \x01(\x08H\x00\x12\r\n\x03\x61ny\x18\x05 \x01(\x08H\x00\x42\x06\n\x04unit\"\x16\n\x14StreamIncomingFilter\"\'\n\x08TlvField\x12\x0c\n\x04type\x18\x01 \x01(\x04\x12\r\n\x05value\x18\x02 \x01(\x0c\"\xa5\x01\n\x0fOffChainPayment\x12\r\n\x05label\x18\x01 \x01(\t\x12\x10\n\x08preimage\x18\x02 \x01(\x0c\x12\"\n\x06\x61mount\x18\x03 \x01(\x0b\x32\x12.greenlight.Amount\x12\'\n\textratlvs\x18\x04 \x03(\x0b\x32\x14.greenlight.TlvField\x12\x14\n\x0cpayment_hash\x18\x05 \x01(\x0c\x12\x0e\n\x06\x62olt11\x18\x06 \x01(\t\"M\n\x0fIncomingPayment\x12/\n\x08offchain\x18\x01 \x01(\x0b\x32\x1b.greenlight.OffChainPaymentH\x00\x42\t\n\x07\x64\x65tails\"\x12\n\x10StreamLogRequest\"\x18\n\x08LogEntry\x12\x0c\n\x04line\x18\x01 \x01(\t\"R\n\x10SignerStateEntry\x12\x0f\n\x07version\x18\x01 \x01(\x04\x12\x0b\n\x03key\x18\x02 \x01(\t\x12\r\n\x05value\x18\x03 \x01(\x0c\x12\x11\n\tsignature\x18\x04 \x01(\x0c\"r\n\x0ePendingRequest\x12\x0f\n\x07request\x18\x01 \x01(\x0c\x12\x0b\n\x03uri\x18\x02 \x01(\t\x12\x11\n\tsignature\x18\x03 \x01(\x0c\x12\x0e\n\x06pubkey\x18\x04 \x01(\x0c\x12\x11\n\ttimestamp\x18\x05 \x01(\x04\x12\x0c\n\x04rune\x18\x06 \x01(\x0c\"=\n\nNodeConfig\x12/\n\x0bstartupmsgs\x18\x01 \x03(\x0b\x32\x1a.greenlight.StartupMessage\"!\n\x08GlConfig\x12\x15\n\rclose_to_addr\x18\x01 \x01(\t\"3\n\x0eStartupMessage\x12\x0f\n\x07request\x18\x01 \x01(\x0c\x12\x10\n\x08response\x18\x02 \x01(\x0c\"\x18\n\x16StreamCustommsgRequest\"-\n\tCustommsg\x12\x0f\n\x07peer_id\x18\x01 \x01(\x0c\x12\x0f\n\x07payload\x18\x02 \x01(\x0c\"\xa4\x01\n\x14TrampolinePayRequest\x12\x0e\n\x06\x62olt11\x18\x01 \x01(\t\x12\x1a\n\x12trampoline_node_id\x18\x02 \x01(\x0c\x12\x13\n\x0b\x61mount_msat\x18\x03 \x01(\x04\x12\r\n\x05label\x18\x04 \x01(\t\x12\x15\n\rmaxfeepercent\x18\x05 \x01(\x02\x12\x10\n\x08maxdelay\x18\x06 \x01(\r\x12\x13\n\x0b\x64\x65scription\x18\x07 \x01(\t\"\xd5\x01\n\x15TrampolinePayResponse\x12\x18\n\x10payment_preimage\x18\x01 \x01(\x0c\x12\x14\n\x0cpayment_hash\x18\x02 \x01(\x0c\x12\x12\n\ncreated_at\x18\x03 \x01(\x01\x12\r\n\x05parts\x18\x04 \x01(\r\x12\x13\n\x0b\x61mount_msat\x18\x05 \x01(\x04\x12\x18\n\x10\x61mount_sent_msat\x18\x06 \x01(\x04\x12\x13\n\x0b\x64\x65stination\x18\x07 \x01(\x0c\"%\n\tPayStatus\x12\x0c\n\x08\x43OMPLETE\x10\x00\x12\n\n\x06\x46\x41ILED\x10\x02\"\x8b\x01\n\x11LspInvoiceRequest\x12\x0e\n\x06lsp_id\x18\x01 \x01(\t\x12\r\n\x05token\x18\x02 \x01(\t\x12\x13\n\x0b\x61mount_msat\x18\x03 \x01(\x04\x12\x13\n\x0b\x64\x65scription\x18\x04 \x01(\t\x12\r\n\x05label\x18\x05 \x01(\t\x12\x13\n\x06\x65xpiry\x18\x06 \x01(\x04H\x00\x88\x01\x01\x42\t\n\x07_expiry\"\x97\x01\n\x12LspInvoiceResponse\x12\x0e\n\x06\x62olt11\x18\x01 \x01(\t\x12\x15\n\rcreated_index\x18\x02 \x01(\r\x12\x12\n\nexpires_at\x18\x03 \x01(\r\x12\x14\n\x0cpayment_hash\x18\x04 \x01(\x0c\x12\x16\n\x0epayment_secret\x18\x05 \x01(\x0c\x12\x18\n\x10opening_fee_msat\x18\x06 \x01(\x04\"\x13\n\x11NodeEventsRequest\"E\n\tNodeEvent\x12/\n\x0cinvoice_paid\x18\x01 \x01(\x0b\x32\x17.greenlight.InvoicePaidH\x00\x42\x07\n\x05\x65vent\"\x92\x01\n\x0bInvoicePaid\x12\x14\n\x0cpayment_hash\x18\x01 \x01(\x0c\x12\x0e\n\x06\x62olt11\x18\x02 \x01(\t\x12\x10\n\x08preimage\x18\x03 \x01(\x0c\x12\r\n\x05label\x18\x04 \x01(\t\x12\x13\n\x0b\x61mount_msat\x18\x05 \x01(\x04\x12\'\n\textratlvs\x18\x06 \x03(\x0b\x32\x14.greenlight.TlvField2\xa6\x05\n\x04Node\x12M\n\nLspInvoice\x12\x1d.greenlight.LspInvoiceRequest\x1a\x1e.greenlight.LspInvoiceResponse\"\x00\x12S\n\x0eStreamIncoming\x12 .greenlight.StreamIncomingFilter\x1a\x1b.greenlight.IncomingPayment\"\x00\x30\x01\x12\x43\n\tStreamLog\x12\x1c.greenlight.StreamLogRequest\x1a\x14.greenlight.LogEntry\"\x00\x30\x01\x12P\n\x0fStreamCustommsg\x12\".greenlight.StreamCustommsgRequest\x1a\x15.greenlight.Custommsg\"\x00\x30\x01\x12L\n\x10StreamNodeEvents\x12\x1d.greenlight.NodeEventsRequest\x1a\x15.greenlight.NodeEvent\"\x00\x30\x01\x12\x42\n\x11StreamHsmRequests\x12\x11.greenlight.Empty\x1a\x16.greenlight.HsmRequest\"\x00\x30\x01\x12\x41\n\x11RespondHsmRequest\x12\x17.greenlight.HsmResponse\x1a\x11.greenlight.Empty\"\x00\x12\x36\n\tConfigure\x12\x14.greenlight.GlConfig\x1a\x11.greenlight.Empty\"\x00\x12V\n\rTrampolinePay\x12 .greenlight.TrampolinePayRequest\x1a!.greenlight.TrampolinePayResponse\"\x00\x32s\n\x03Hsm\x12<\n\x07Request\x12\x16.greenlight.HsmRequest\x1a\x17.greenlight.HsmResponse\"\x00\x12.\n\x04Ping\x12\x11.greenlight.Empty\x1a\x11.greenlight.Empty\"\x00\x62\x06proto3') _globals = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) @@ -73,18 +73,18 @@ _globals['_TRAMPOLINEPAYRESPONSE']._serialized_end=1706 _globals['_TRAMPOLINEPAYRESPONSE_PAYSTATUS']._serialized_start=1669 _globals['_TRAMPOLINEPAYRESPONSE_PAYSTATUS']._serialized_end=1706 - _globals['_LSPINVOICEREQUEST']._serialized_start=1708 - _globals['_LSPINVOICEREQUEST']._serialized_end=1815 - _globals['_LSPINVOICERESPONSE']._serialized_start=1818 - _globals['_LSPINVOICERESPONSE']._serialized_end=1969 - _globals['_NODEEVENTSREQUEST']._serialized_start=1971 - _globals['_NODEEVENTSREQUEST']._serialized_end=1990 - _globals['_NODEEVENT']._serialized_start=1992 - _globals['_NODEEVENT']._serialized_end=2061 - _globals['_INVOICEPAID']._serialized_start=2064 - _globals['_INVOICEPAID']._serialized_end=2210 - _globals['_NODE']._serialized_start=2213 - _globals['_NODE']._serialized_end=2891 - _globals['_HSM']._serialized_start=2893 - _globals['_HSM']._serialized_end=3008 + _globals['_LSPINVOICEREQUEST']._serialized_start=1709 + _globals['_LSPINVOICEREQUEST']._serialized_end=1848 + _globals['_LSPINVOICERESPONSE']._serialized_start=1851 + _globals['_LSPINVOICERESPONSE']._serialized_end=2002 + _globals['_NODEEVENTSREQUEST']._serialized_start=2004 + _globals['_NODEEVENTSREQUEST']._serialized_end=2023 + _globals['_NODEEVENT']._serialized_start=2025 + _globals['_NODEEVENT']._serialized_end=2094 + _globals['_INVOICEPAID']._serialized_start=2097 + _globals['_INVOICEPAID']._serialized_end=2243 + _globals['_NODE']._serialized_start=2246 + _globals['_NODE']._serialized_end=2924 + _globals['_HSM']._serialized_start=2926 + _globals['_HSM']._serialized_end=3041 # @@protoc_insertion_point(module_scope) diff --git a/libs/gl-client-py/glclient/greenlight_pb2.pyi b/libs/gl-client-py/glclient/greenlight_pb2.pyi index 6d9096681..466b8efa2 100644 --- a/libs/gl-client-py/glclient/greenlight_pb2.pyi +++ b/libs/gl-client-py/glclient/greenlight_pb2.pyi @@ -536,6 +536,7 @@ class LspInvoiceRequest(_message.Message): AMOUNT_MSAT_FIELD_NUMBER: _builtins.int DESCRIPTION_FIELD_NUMBER: _builtins.int LABEL_FIELD_NUMBER: _builtins.int + EXPIRY_FIELD_NUMBER: _builtins.int lsp_id: _builtins.str """len=0 => None, let the server decide.""" token: _builtins.str @@ -548,6 +549,7 @@ class LspInvoiceRequest(_message.Message): """ description: _builtins.str label: _builtins.str + expiry: _builtins.int def __init__( self, *, @@ -556,9 +558,15 @@ class LspInvoiceRequest(_message.Message): amount_msat: _builtins.int = ..., description: _builtins.str = ..., label: _builtins.str = ..., + expiry: _builtins.int | None = ..., ) -> None: ... - _ClearFieldArgType: _TypeAlias = _typing.Literal["amount_msat", b"amount_msat", "description", b"description", "label", b"label", "lsp_id", b"lsp_id", "token", b"token"] # noqa: Y015 + _HasFieldArgType: _TypeAlias = _typing.Literal["_expiry", b"_expiry", "expiry", b"expiry"] # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["_expiry", b"_expiry", "amount_msat", b"amount_msat", "description", b"description", "expiry", b"expiry", "label", b"label", "lsp_id", b"lsp_id", "token", b"token"] # noqa: Y015 def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + _WhichOneofReturnType__expiry: _TypeAlias = _typing.Literal["expiry"] # noqa: Y015 + _WhichOneofArgType__expiry: _TypeAlias = _typing.Literal["_expiry", b"_expiry"] # noqa: Y015 + def WhichOneof(self, oneof_group: _WhichOneofArgType__expiry) -> _WhichOneofReturnType__expiry | None: ... Global___LspInvoiceRequest: _TypeAlias = LspInvoiceRequest # noqa: Y015 diff --git a/libs/gl-client-py/src/node.rs b/libs/gl-client-py/src/node.rs index 0fbfc8145..fb2e63831 100644 --- a/libs/gl-client-py/src/node.rs +++ b/libs/gl-client-py/src/node.rs @@ -106,13 +106,15 @@ impl Node { description: String, amount_msat: Option, token: Option, + expiry: Option, ) -> PyResult> { let req = pb::LspInvoiceRequest { amount_msat: amount_msat.unwrap_or_default(), - description: description, - label: label, + description, + label, lsp_id: "".to_owned(), token: token.unwrap_or_default(), + expiry, }; let res = exec(async { self.client.clone().lsp_invoice(req).await }) diff --git a/libs/gl-client-py/tests/test_plugin.py b/libs/gl-client-py/tests/test_plugin.py index 405d02e87..974682ed6 100644 --- a/libs/gl-client-py/tests/test_plugin.py +++ b/libs/gl-client-py/tests/test_plugin.py @@ -259,3 +259,78 @@ def test_lsps_plugin_calls(clients, bitcoind, node_factory, lsps_server): # the LSPS2 fee parameters (min_fee_msat=1000, proportional=1000). # For 31337 msat: max(1000, ceil(31337 * 1000 / 1_000_000)) = 1000 assert res.opening_fee_msat == 1000 + + +def test_lsp_invoice_expiry(clients, bitcoind, node_factory, lsps_server): + """An invoice created with an `expiry` carries that expiry. + + ```ditaa + Payer --- LSP --- GL + ``` + + First the GL node receives a payment over a JIT channel opened by + the LSP. That gives it inbound capacity, so the next `lsp_invoice` + takes the plain-invoice path (no JIT negotiation), where the + requested `expiry` is passed to CLN's `invoice`. + """ + lsp = lsps_server + lsp.fundwallet(sats=2 * 10**6) + + # The payer has a channel to the LSP, so it can reach the GL node + # through the LSP via the invoice's route hint. + payer = node_factory.get_node() + payer.connect(lsp) + payer.fundchannel(lsp, 10**6) + + # The GL node, connected to the LSP but without any channel yet. + c = clients.new() + c.register() + signer = c.signer() + signer.run_in_thread() + gl = c.node() + gl.connect_peer(lsp.info["id"], f"localhost:{lsp.port}") + + # 1. Receive over a JIT channel. With no inbound capacity the plugin + # has to negotiate one with the LSP. + jit_amount_msat = 50_000_000 + jit = gl.lsp_invoice( + label="jit", description="jit", amount_msat=jit_amount_msat + ) + # Cheapest menu entry: max(1000, 50_000_000 * 1000 / 1_000_000) msat. + assert jit.opening_fee_msat == 50_000 + assert payer.rpc.pay(jit.bolt11)["status"] == "complete" + + bitcoind.generate_block(10) + # # 2. Wait until the JIT channel is usable for receiving, so the + # # plugin skips JIT negotiation. It requires 5% on top of the + # # invoice amount. + amount_msat = 10_000_000 + # + # def receivable_msat(): + # return sum( + # ch.receivable_msat.msat + # for ch in gl.list_peer_channels().channels + # if ch.peer_connected and ch.state == 2 # CHANNELD_NORMAL + # ) + # + # wait_for(lambda: receivable_msat() >= amount_msat * 105 // 100) + + # 3. The requested expiry ends up in the invoice. + expiry = 3600 + res = gl.lsp_invoice( + label="with-expiry", + description="with-expiry", + amount_msat=amount_msat, + expiry=expiry, + ) + assert res.opening_fee_msat == 0 # plain invoice, no JIT channel + assert payer.rpc.decode(res.bolt11)["expiry"] == expiry + + # 4. Without an expiry, CLN's default (one week) still applies. + res = gl.lsp_invoice( + label="default-expiry", + description="default-expiry", + amount_msat=amount_msat, + ) + assert res.opening_fee_msat == 0 + assert payer.rpc.decode(res.bolt11)["expiry"] == 7 * 24 * 3600 diff --git a/libs/gl-client/.resources/proto/glclient/greenlight.proto b/libs/gl-client/.resources/proto/glclient/greenlight.proto index b11d03ae2..bf7be1d8a 100644 --- a/libs/gl-client/.resources/proto/glclient/greenlight.proto +++ b/libs/gl-client/.resources/proto/glclient/greenlight.proto @@ -244,7 +244,9 @@ message LspInvoiceRequest { uint64 amount_msat = 3; // 0 => Any string description = 4; string label = 5; + optional uint64 expiry = 6; } + message LspInvoiceResponse { string bolt11 = 1; uint32 created_index = 2; diff --git a/libs/gl-plugin/.resources/proto/glclient/greenlight.proto b/libs/gl-plugin/.resources/proto/glclient/greenlight.proto index b11d03ae2..bf7be1d8a 100644 --- a/libs/gl-plugin/.resources/proto/glclient/greenlight.proto +++ b/libs/gl-plugin/.resources/proto/glclient/greenlight.proto @@ -244,7 +244,9 @@ message LspInvoiceRequest { uint64 amount_msat = 3; // 0 => Any string description = 4; string label = 5; + optional uint64 expiry = 6; } + message LspInvoiceResponse { string bolt11 = 1; uint32 created_index = 2; diff --git a/libs/gl-plugin/Cargo.toml b/libs/gl-plugin/Cargo.toml index c2e2b0795..d69536185 100644 --- a/libs/gl-plugin/Cargo.toml +++ b/libs/gl-plugin/Cargo.toml @@ -42,6 +42,7 @@ tokio-util = { version = "0.7", features = ["codec"] } tonic = { version = "0.11", features = ["tls", "transport"] } tower = { version = "0.4" } vls-protocol = { workspace = true } +chrono = { version = "0.4" } [build-dependencies] tonic-build = "0.11" diff --git a/libs/gl-plugin/src/node/mod.rs b/libs/gl-plugin/src/node/mod.rs index 016238be6..b7f8e551b 100644 --- a/libs/gl-plugin/src/node/mod.rs +++ b/libs/gl-plugin/src/node/mod.rs @@ -265,7 +265,7 @@ impl Node for PluginNodeServer { ), description: req.description.clone(), label: req.label.clone(), - expiry: None, + expiry: req.expiry, fallbacks: None, preimage: None, cltv: Some(144), @@ -338,7 +338,7 @@ impl Node for PluginNodeServer { .div_ceil(1_000_000); std::cmp::max(min_fee, proportional_fee) }; - + let requested_amount_msat = req.amount_msat.clone(); let invoice_label = req.label.clone(); @@ -879,27 +879,24 @@ impl Node for PluginNodeServer { /// Writes `LspInvoiceMeta` using datastore request. `LspInvoiceMeta` is useful for defining /// some additional information regarding invoice being requested trough Greenlight. -async fn write_lsp_invoice_meta(rpc: &mut ClnRpc, meta: JitRequestMeta) - -> Result<()> { +async fn write_lsp_invoice_meta(rpc: &mut ClnRpc, meta: JitRequestMeta) -> Result<()> { let record_serialized = serde_json::to_string(&meta).context("failed to serialize LspInvoiceMeta")?; let datastore_req = cln_rpc::model::requests::DatastoreRequest { - key: vec![ - "gl".to_string(), - "jit_channels".to_string(), - meta.label, - ], + key: vec!["gl".to_string(), "jit_channels".to_string(), meta.label], string: Some(record_serialized), hex: None, mode: Some(cln_rpc::model::requests::DatastoreMode::CREATE_OR_REPLACE), generation: None, }; - rpc.call_typed(&datastore_req).await.map_err( - |e| - anyhow!("Failed to store JIT channel negotiation data in datastore: {}", e) - )?; + rpc.call_typed(&datastore_req).await.map_err(|e| { + anyhow!( + "Failed to store JIT channel negotiation data in datastore: {}", + e + ) + })?; Ok(()) } @@ -914,19 +911,17 @@ struct Lsps2Offer { } /// Select the LSP and opening fee params to use for an LSPS2 invoice -/// negotiation. -/// -/// We flatten the params across all LSPs and pick the first available -/// pair. This way an LSP that got selected but returned an empty param -/// set is skipped in favor of the next LSP that actually returned -/// usable params, rather than ending up without valid opening params. -/// Returns `None` if no LSP returned any params at all. +/// negotiation. Returns `None` if no LSP returned any params at all. fn select_opening_params( lsps: Vec, ) -> Option<(String, crate::responses::OpeningFeeParams)> { lsps.into_iter() .flat_map(|l| l.params.into_iter().map(move |p| (l.node_id.clone(), p))) - .next() + .max_by_key(|(_, p)| { + p.valid_until + .parse::>() + .ok() + }) } impl PluginNodeServer { @@ -989,7 +984,10 @@ impl PluginNodeServer { tokio::time::timeout(RECONNECT_TIMEOUT, rpc.call_typed(&r)).await } Err(e) => { - warn!("Could not open RPC to connect to {}: {:?} (plugin)", &r.id, e); + warn!( + "Could not open RPC to connect to {}: {:?} (plugin)", + &r.id, e + ); return; } }; @@ -1355,6 +1353,19 @@ mod test { } } + fn param_with_time(min_fee_msat: &str, valid_until: String) -> OpeningFeeParams { + OpeningFeeParams { + min_fee_msat: min_fee_msat.to_string(), + proportional: 0, + valid_until, + min_lifetime: 144, + max_client_to_self_delay: 1024, + min_payment_size_msat: "0".to_string(), + max_payment_size_msat: "1000000000".to_string(), + promise: "promise".to_string(), + } + } + #[test] fn test_select_opening_params_empty() { // No LSPs at all -> nothing to select. @@ -1400,21 +1411,27 @@ mod test { } #[test] - fn test_select_opening_params_prefers_first_nonempty() { + fn test_select_opening_params_prefers_max_valid_until() { // When the first LSP does return params we keep using it. let lsps = vec![ Lsps2Offer { node_id: "lsp_first".to_string(), - params: vec![param("1"), param("2")], + params: vec![ + param_with_time("1", "2150-01-01T00:00:00Z".to_string()), + param_with_time("2", "2100-01-01T00:00:00Z".to_string()), + ], }, Lsps2Offer { node_id: "lsp_second".to_string(), - params: vec![param("3")], + params: vec![ + param_with_time("3", "2150-07-01T00:00:00Z".to_string()), + param_with_time("4", "2100-02-01T00:00:00Z".to_string()), + ], }, ]; - let (lsp_id, p) = select_opening_params(lsps).expect("first LSP has params"); - assert_eq!(lsp_id, "lsp_first"); - assert_eq!(p.min_fee_msat, "1"); + let (lsp_id, p) = select_opening_params(lsps).expect("expect valid offer"); + assert_eq!(lsp_id, "lsp_second"); + assert_eq!(p.min_fee_msat, "3"); } } diff --git a/libs/gl-plugin/src/requests.rs b/libs/gl-plugin/src/requests.rs index 5cc02f9a2..a6e86cef7 100644 --- a/libs/gl-plugin/src/requests.rs +++ b/libs/gl-plugin/src/requests.rs @@ -216,6 +216,8 @@ pub struct LspInvoiceRequest { pub amount_msat: cln_rpc::primitives::AmountOrAny, pub description: String, pub label: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub expiry: Option, } #[derive(Debug, Clone, Serialize)] @@ -226,6 +228,8 @@ pub struct LspInvoiceRequestV2 { pub amount_msat: cln_rpc::primitives::AmountOrAny, pub description: String, pub label: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub expiry: Option, } #[derive(Debug, Clone, Serialize)] @@ -253,6 +257,7 @@ impl From for LspInvoiceRequest { }, description: o.description, label: o.label, + expiry: o.expiry, } } } @@ -273,6 +278,7 @@ impl From for LspInvoiceRequestV2 { }, description: o.description, label: o.label, + expiry: o.expiry, } } } @@ -300,7 +306,6 @@ impl TypedRequest for LspGetinfoRequest { #[cfg(test)] mod test { - use super::*; #[test] fn test_invoice_response() { let tests = vec![ @@ -310,6 +315,7 @@ mod test { amount_msat: 0, description: "description".to_owned(), label: "label".to_owned(), + expiry: None, }), crate::pb::LspInvoiceRequest { lsp_id: "lsp_id".to_owned(), @@ -317,6 +323,7 @@ mod test { amount_msat: 1337, description: "description".to_owned(), label: "label".to_owned(), + expiry: Some(101010), }, ]; diff --git a/libs/gl-sdk-cli/src/node.rs b/libs/gl-sdk-cli/src/node.rs index 501feb152..37a1c3211 100644 --- a/libs/gl-sdk-cli/src/node.rs +++ b/libs/gl-sdk-cli/src/node.rs @@ -26,6 +26,9 @@ pub enum Command { /// Amount in millisatoshis (omit for any-amount invoice) #[arg(long)] amount_msat: Option, + /// Desired BOLT11 invoice expiry (default: node's default) + #[arg(long)] + expiry: Option, }, /// Pay a lightning invoice Send { @@ -65,7 +68,8 @@ pub fn handle(cmd: Command, data_dir: &DataDir) -> Result<()> { label, description, amount_msat, - } => receive(&node, label, description, amount_msat), + expiry, + } => receive(&node, label, description, amount_msat, expiry), Command::Send { invoice, amount_msat, @@ -109,8 +113,9 @@ fn receive( label: String, description: String, amount_msat: Option, + expiry: Option, ) -> Result<()> { - let res = node.receive(label, description, amount_msat)?; + let res = node.receive(label, description, amount_msat, expiry)?; output::print_json(&ReceiveOutput::from(res)); Ok(()) } diff --git a/libs/gl-sdk-napi/src/lib.rs b/libs/gl-sdk-napi/src/lib.rs index 887de054a..8dc9cf3cf 100644 --- a/libs/gl-sdk-napi/src/lib.rs +++ b/libs/gl-sdk-napi/src/lib.rs @@ -704,18 +704,21 @@ impl Node { /// * `label` - Unique label for this invoice /// * `description` - Invoice description /// * `amount_msat` - Optional amount in millisatoshis + /// * `expiry` - A desired BOLT11 invoice expiry in seconds #[napi] pub async fn receive( &self, label: String, description: String, amount_msat: Option, + expiry: Option, ) -> Result { let inner = self.inner.clone(); let amount = amount_msat.map(|a| a as u64); + let expiry = expiry.map(|a| a as u64); let response = tokio::task::spawn_blocking(move || { inner - .receive(label, description, amount) + .receive(label, description, amount, expiry) .map_err(|e| Error::from_reason(e.to_string())) }) .await diff --git a/libs/gl-sdk/bindings/glsdk.swift b/libs/gl-sdk/bindings/glsdk.swift index b10a33f9c..aac004307 100644 --- a/libs/gl-sdk/bindings/glsdk.swift +++ b/libs/gl-sdk/bindings/glsdk.swift @@ -1360,7 +1360,7 @@ public protocol NodeProtocol: AnyObject, Sendable { * opening, and when/if executed the payment will cause a channel * to be created, and the incoming payment to be forwarded. */ - func receive(label: String, description: String, amountMsat: UInt64?) throws -> ReceiveResponse + func receive(label: String, description: String, amountMsat: UInt64?, expiry: UInt64?) throws -> ReceiveResponse func send(invoice: String, amountMsat: UInt64?) throws -> SendResponse @@ -1781,12 +1781,13 @@ open func prepareOnchainSend(destination: String, amountOrAll: String, satPerVby * opening, and when/if executed the payment will cause a channel * to be created, and the incoming payment to be forwarded. */ -open func receive(label: String, description: String, amountMsat: UInt64?)throws -> ReceiveResponse { +open func receive(label: String, description: String, amountMsat: UInt64?, expiry: UInt64? = nil)throws -> ReceiveResponse { return try FfiConverterTypeReceiveResponse_lift(try rustCallWithError(FfiConverterTypeError_lift) { uniffi_glsdk_fn_method_node_receive(self.uniffiClonePointer(), FfiConverterString.lower(label), FfiConverterString.lower(description), - FfiConverterOptionUInt64.lower(amountMsat),$0 + FfiConverterOptionUInt64.lower(amountMsat), + FfiConverterOptionUInt64.lower(expiry),$0 ) }) } @@ -2335,8 +2336,12 @@ public protocol SchedulerProtocol: AnyObject, Sendable { * before it creates a node. It needs no credentials, and the * `node_id` is passed explicitly. * - * The answer is advisory and may change over time. Treat an - * error as "unknown" rather than as a negative answer. + * The answer is monotonic: once the node has been registered + * it is reported as available, and stays available regardless + * of the node's status or the provider's current capacity. + * Before registration the answer is advisory and may change + * over time. Treat an error as "unknown" rather than as a + * negative answer. */ func lightningAvailable(nodeId: Data) throws -> Bool @@ -2434,8 +2439,12 @@ public convenience init(network: Network)throws { * before it creates a node. It needs no credentials, and the * `node_id` is passed explicitly. * - * The answer is advisory and may change over time. Treat an - * error as "unknown" rather than as a negative answer. + * The answer is monotonic: once the node has been registered + * it is reported as available, and stays available regardless + * of the node's status or the provider's current capacity. + * Before registration the answer is advisory and may change + * over time. Treat an error as "unknown" rather than as a + * negative answer. */ open func lightningAvailable(nodeId: Data)throws -> Bool { return try FfiConverterBool.lift(try rustCallWithError(FfiConverterTypeError_lift) { @@ -9690,7 +9699,7 @@ private let initializationResult: InitializationResult = { if (uniffi_glsdk_checksum_method_node_prepare_onchain_send() != 37850) { return InitializationResult.apiChecksumMismatch } - if (uniffi_glsdk_checksum_method_node_receive() != 39761) { + if (uniffi_glsdk_checksum_method_node_receive() != 16076) { return InitializationResult.apiChecksumMismatch } if (uniffi_glsdk_checksum_method_node_send() != 4348) { @@ -9720,7 +9729,7 @@ private let initializationResult: InitializationResult = { if (uniffi_glsdk_checksum_method_nodeeventstream_next() != 12635) { return InitializationResult.apiChecksumMismatch } - if (uniffi_glsdk_checksum_method_scheduler_lightning_available() != 7327) { + if (uniffi_glsdk_checksum_method_scheduler_lightning_available() != 8721) { return InitializationResult.apiChecksumMismatch } if (uniffi_glsdk_checksum_method_scheduler_recover() != 55514) { diff --git a/libs/gl-sdk/bindings/glsdkFFI.h b/libs/gl-sdk/bindings/glsdkFFI.h index 327e93234..1ce2705bf 100644 --- a/libs/gl-sdk/bindings/glsdkFFI.h +++ b/libs/gl-sdk/bindings/glsdkFFI.h @@ -464,7 +464,7 @@ RustBuffer uniffi_glsdk_fn_method_node_prepare_onchain_send(void*_Nonnull ptr, R #endif #ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_NODE_RECEIVE #define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_NODE_RECEIVE -RustBuffer uniffi_glsdk_fn_method_node_receive(void*_Nonnull ptr, RustBuffer label, RustBuffer description, RustBuffer amount_msat, RustCallStatus *_Nonnull out_status +RustBuffer uniffi_glsdk_fn_method_node_receive(void*_Nonnull ptr, RustBuffer label, RustBuffer description, RustBuffer amount_msat, RustBuffer expiry, RustCallStatus *_Nonnull out_status ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_NODE_SEND diff --git a/libs/gl-sdk/glsdk/glsdk.py b/libs/gl-sdk/glsdk/glsdk.py index 86b90b14e..1cd96716b 100644 --- a/libs/gl-sdk/glsdk/glsdk.py +++ b/libs/gl-sdk/glsdk/glsdk.py @@ -514,7 +514,7 @@ def _uniffi_check_api_checksums(lib): raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_node_prepare_onchain_send() != 37850: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - if lib.uniffi_glsdk_checksum_method_node_receive() != 39761: + if lib.uniffi_glsdk_checksum_method_node_receive() != 16076: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_node_send() != 4348: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") @@ -534,7 +534,7 @@ def _uniffi_check_api_checksums(lib): raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_nodeeventstream_next() != 12635: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - if lib.uniffi_glsdk_checksum_method_scheduler_lightning_available() != 7327: + if lib.uniffi_glsdk_checksum_method_scheduler_lightning_available() != 8721: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_scheduler_recover() != 55514: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") @@ -898,6 +898,7 @@ class _UniffiVTableCallbackInterfaceNodeEventListener(ctypes.Structure): _UniffiRustBuffer, _UniffiRustBuffer, _UniffiRustBuffer, + _UniffiRustBuffer, ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_glsdk_fn_method_node_receive.restype = _UniffiRustBuffer @@ -7638,7 +7639,7 @@ def prepare_onchain_send(self, destination: "str",amount_or_all: "str",sat_per_v """ raise NotImplementedError - def receive(self, label: "str",description: "str",amount_msat: "typing.Optional[int]"): + def receive(self, label: "str",description: "str",amount_msat: "typing.Optional[int]",expiry: "typing.Union[object, typing.Optional[int]]" = _DEFAULT): """ Receive an off-chain payment. @@ -8136,7 +8137,7 @@ def prepare_onchain_send(self, destination: "str",amount_or_all: "str",sat_per_v - def receive(self, label: "str",description: "str",amount_msat: "typing.Optional[int]") -> "ReceiveResponse": + def receive(self, label: "str",description: "str",amount_msat: "typing.Optional[int]",expiry: "typing.Union[object, typing.Optional[int]]" = _DEFAULT) -> "ReceiveResponse": """ Receive an off-chain payment. @@ -8156,11 +8157,16 @@ def receive(self, label: "str",description: "str",amount_msat: "typing.Optional[ _UniffiConverterOptionalUInt64.check_lower(amount_msat) + if expiry is _DEFAULT: + expiry = None + _UniffiConverterOptionalUInt64.check_lower(expiry) + return _UniffiConverterTypeReceiveResponse.lift( _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_node_receive,self._uniffi_clone_pointer(), _UniffiConverterString.lower(label), _UniffiConverterString.lower(description), - _UniffiConverterOptionalUInt64.lower(amount_msat)) + _UniffiConverterOptionalUInt64.lower(amount_msat), + _UniffiConverterOptionalUInt64.lower(expiry)) ) @@ -8616,8 +8622,12 @@ def lightning_available(self, node_id: "bytes"): before it creates a node. It needs no credentials, and the `node_id` is passed explicitly. - The answer is advisory and may change over time. Treat an - error as "unknown" rather than as a negative answer. + The answer is monotonic: once the node has been registered + it is reported as available, and stays available regardless + of the node's status or the provider's current capacity. + Before registration the answer is advisory and may change + over time. Treat an error as "unknown" rather than as a + negative answer. """ raise NotImplementedError @@ -8685,8 +8695,12 @@ def lightning_available(self, node_id: "bytes") -> "bool": before it creates a node. It needs no credentials, and the `node_id` is passed explicitly. - The answer is advisory and may change over time. Treat an - error as "unknown" rather than as a negative answer. + The answer is monotonic: once the node has been registered + it is reported as available, and stays available regardless + of the node's status or the provider's current capacity. + Before registration the answer is advisory and may change + over time. Treat an error as "unknown" rather than as a + negative answer. """ _UniffiConverterBytes.check_lower(node_id) diff --git a/libs/gl-sdk/src/node.rs b/libs/gl-sdk/src/node.rs index 92a1fb575..656e890e9 100644 --- a/libs/gl-sdk/src/node.rs +++ b/libs/gl-sdk/src/node.rs @@ -119,11 +119,13 @@ impl Node { /// receive the requested funds, the node will negotiate an /// opening, and when/if executed the payment will cause a channel /// to be created, and the incoming payment to be forwarded. + #[uniffi::method(default(expiry = None))] pub fn receive( &self, label: String, description: String, amount_msat: Option, + expiry: Option, ) -> Result { self.check_connected()?; let mut gl_client = exec(self.get_gl_client())?.clone(); @@ -134,6 +136,7 @@ impl Node { label: label, lsp_id: "".to_owned(), token: "".to_owned(), + expiry: expiry, }; let res = exec(gl_client.lsp_invoice(req)) .map_err(|s| Error::rpc(s.to_string()))? @@ -1101,6 +1104,7 @@ impl Node { format!("lnurl-withdraw-{}", request.data.k1), description, Some(request.amount_msat), + None, )?; // Step 2: Build callback URL and submit invoice to service diff --git a/libs/gl-signerproxy/.resources/proto/glclient/greenlight.proto b/libs/gl-signerproxy/.resources/proto/glclient/greenlight.proto index b11d03ae2..bf7be1d8a 100644 --- a/libs/gl-signerproxy/.resources/proto/glclient/greenlight.proto +++ b/libs/gl-signerproxy/.resources/proto/glclient/greenlight.proto @@ -244,7 +244,9 @@ message LspInvoiceRequest { uint64 amount_msat = 3; // 0 => Any string description = 4; string label = 5; + optional uint64 expiry = 6; } + message LspInvoiceResponse { string bolt11 = 1; uint32 created_index = 2; diff --git a/libs/proto/glclient/greenlight.proto b/libs/proto/glclient/greenlight.proto index b11d03ae2..bf7be1d8a 100644 --- a/libs/proto/glclient/greenlight.proto +++ b/libs/proto/glclient/greenlight.proto @@ -244,7 +244,9 @@ message LspInvoiceRequest { uint64 amount_msat = 3; // 0 => Any string description = 4; string label = 5; + optional uint64 expiry = 6; } + message LspInvoiceResponse { string bolt11 = 1; uint32 created_index = 2; From 2b02a1a1e5070ed478eceb42df1aefe628f85eb0 Mon Sep 17 00:00:00 2001 From: Oleh Fomenko Date: Fri, 20 Nov 2026 17:12:38 +0200 Subject: [PATCH 2/3] gl-plugin: update logic for `select_opening_params`: searches for the first entry with `valid_until > now + expiry` if expiry was provided. --- libs/gl-plugin/src/node/mod.rs | 51 ++++++++++++++++++++++++---------- 1 file changed, 37 insertions(+), 14 deletions(-) diff --git a/libs/gl-plugin/src/node/mod.rs b/libs/gl-plugin/src/node/mod.rs index b7f8e551b..f82bede20 100644 --- a/libs/gl-plugin/src/node/mod.rs +++ b/libs/gl-plugin/src/node/mod.rs @@ -319,9 +319,10 @@ impl Node for PluginNodeServer { )); } - let (lsp_id, param) = select_opening_params(lsps).ok_or_else(|| { - Status::not_found("No opening params returned by any LSP, cannot create invoice.") - })?; + let (lsp_id, param) = select_opening_params(lsps, chrono::Utc::now(), req.expiry) + .ok_or_else(|| { + Status::not_found("No opening params returned by any LSP, cannot create invoice.") + })?; log::info!( "Selecting LSP {} with params {:?} for invoice negotiation", @@ -912,15 +913,20 @@ struct Lsps2Offer { /// Select the LSP and opening fee params to use for an LSPS2 invoice /// negotiation. Returns `None` if no LSP returned any params at all. +/// Mirrors the lsps-client logic. fn select_opening_params( lsps: Vec, + now: chrono::DateTime, + expiry: Option, ) -> Option<(String, crate::responses::OpeningFeeParams)> { + let fut_now = now + chrono::Duration::seconds(expiry.unwrap_or(60) as i64); + lsps.into_iter() .flat_map(|l| l.params.into_iter().map(move |p| (l.node_id.clone(), p))) - .max_by_key(|(_, p)| { + .find(|(_, p)| { p.valid_until .parse::>() - .ok() + .is_ok_and(|t| t > fut_now) }) } @@ -1369,7 +1375,7 @@ mod test { #[test] fn test_select_opening_params_empty() { // No LSPs at all -> nothing to select. - assert!(select_opening_params(vec![]).is_none()); + assert!(select_opening_params(vec![], chrono::Utc::now(), None).is_none()); } #[test] @@ -1388,7 +1394,8 @@ mod test { }, ]; - let (lsp_id, p) = select_opening_params(lsps).expect("should fall back to second LSP"); + let (lsp_id, p) = select_opening_params(lsps, chrono::Utc::now(), None) + .expect("should fall back to second LSP"); assert_eq!(lsp_id, "lsp_good"); assert_eq!(p.min_fee_msat, "100"); } @@ -1407,30 +1414,46 @@ mod test { }, ]; - assert!(select_opening_params(lsps).is_none()); + assert!(select_opening_params(lsps, chrono::Utc::now(), None).is_none()); } #[test] - fn test_select_opening_params_prefers_max_valid_until() { + fn test_select_opening_params_with_expiry() { + let now = chrono::Utc::now(); + // When the first LSP does return params we keep using it. let lsps = vec![ Lsps2Offer { node_id: "lsp_first".to_string(), params: vec![ - param_with_time("1", "2150-01-01T00:00:00Z".to_string()), - param_with_time("2", "2100-01-01T00:00:00Z".to_string()), + param_with_time("1", (now + chrono::Duration::hours(5)).to_string()), + param_with_time("2", (now + chrono::Duration::hours(3)).to_string()), ], }, Lsps2Offer { node_id: "lsp_second".to_string(), params: vec![ - param_with_time("3", "2150-07-01T00:00:00Z".to_string()), - param_with_time("4", "2100-02-01T00:00:00Z".to_string()), + param_with_time("3", (now + chrono::Duration::hours(7)).to_string()), + param_with_time("4", (now + chrono::Duration::hours(10)).to_string()), ], }, ]; - let (lsp_id, p) = select_opening_params(lsps).expect("expect valid offer"); + // No expiry + let (lsp_id, p) = + select_opening_params(lsps.clone(), chrono::Utc::now(), None).expect("expect offer exists"); + assert_eq!(lsp_id, "lsp_first"); + assert_eq!(p.min_fee_msat, "1"); + + // first valid more than 4 hors + let (lsp_id, p) = + select_opening_params(lsps.clone(), chrono::Utc::now(), Some(60*60*4)).expect("expect offer exists"); + assert_eq!(lsp_id, "lsp_first"); + assert_eq!(p.min_fee_msat, "1"); + + // first valid more than 5 hours (also - rime range non inclusion) + let (lsp_id, p) = + select_opening_params(lsps.clone(), chrono::Utc::now(), Some(60*60*5)).expect("expect offer exists"); assert_eq!(lsp_id, "lsp_second"); assert_eq!(p.min_fee_msat, "3"); } From ba6122db70581dc640226203a704d9ed161e7dd1 Mon Sep 17 00:00:00 2001 From: Oleh Fomenko Date: Fri, 20 Nov 2026 19:10:46 +0200 Subject: [PATCH 3/3] gl-client-py: fix tests for lsp_invoice with expiry --- libs/gl-client-py/tests/test_plugin.py | 54 +++++++------------------- 1 file changed, 15 insertions(+), 39 deletions(-) diff --git a/libs/gl-client-py/tests/test_plugin.py b/libs/gl-client-py/tests/test_plugin.py index 974682ed6..2edcb68c4 100644 --- a/libs/gl-client-py/tests/test_plugin.py +++ b/libs/gl-client-py/tests/test_plugin.py @@ -265,57 +265,33 @@ def test_lsp_invoice_expiry(clients, bitcoind, node_factory, lsps_server): """An invoice created with an `expiry` carries that expiry. ```ditaa - Payer --- LSP --- GL + LSP --- GL ``` - First the GL node receives a payment over a JIT channel opened by - the LSP. That gives it inbound capacity, so the next `lsp_invoice` - takes the plain-invoice path (no JIT negotiation), where the - requested `expiry` is passed to CLN's `invoice`. + Assume we already have a channel between LSP and GL node, which gives it + inbound capacity, so `lsp_invoice` takes the plain-invoice path (no + JIT negotiation), where the requested `expiry` is passed to CLN's + `invoice`. """ lsp = lsps_server lsp.fundwallet(sats=2 * 10**6) - # The payer has a channel to the LSP, so it can reach the GL node - # through the LSP via the invoice's route hint. - payer = node_factory.get_node() - payer.connect(lsp) - payer.fundchannel(lsp, 10**6) - - # The GL node, connected to the LSP but without any channel yet. c = clients.new() c.register() signer = c.signer() signer.run_in_thread() gl = c.node() gl.connect_peer(lsp.info["id"], f"localhost:{lsp.port}") + gl_id = gl.get_info().id.hex() - # 1. Receive over a JIT channel. With no inbound capacity the plugin - # has to negotiate one with the LSP. - jit_amount_msat = 50_000_000 - jit = gl.lsp_invoice( - label="jit", description="jit", amount_msat=jit_amount_msat - ) - # Cheapest menu entry: max(1000, 50_000_000 * 1000 / 1_000_000) msat. - assert jit.opening_fee_msat == 50_000 - assert payer.rpc.pay(jit.bolt11)["status"] == "complete" + # Fund channel between LSP and GL node (liquidity is on LSP side) + lsp.rpc.fundchannel(gl_id, 10**6) + bitcoind.generate_block(6, wait_for_mempool=1) + wait_for(lambda: lsp.rpc.listpeerchannels(gl_id)["channels"][0]["state"] == "CHANNELD_NORMAL") - bitcoind.generate_block(10) - # # 2. Wait until the JIT channel is usable for receiving, so the - # # plugin skips JIT negotiation. It requires 5% on top of the - # # invoice amount. amount_msat = 10_000_000 - # - # def receivable_msat(): - # return sum( - # ch.receivable_msat.msat - # for ch in gl.list_peer_channels().channels - # if ch.peer_connected and ch.state == 2 # CHANNELD_NORMAL - # ) - # - # wait_for(lambda: receivable_msat() >= amount_msat * 105 // 100) - - # 3. The requested expiry ends up in the invoice. + + # The requested expiry ends up in the invoice. expiry = 3600 res = gl.lsp_invoice( label="with-expiry", @@ -324,13 +300,13 @@ def test_lsp_invoice_expiry(clients, bitcoind, node_factory, lsps_server): expiry=expiry, ) assert res.opening_fee_msat == 0 # plain invoice, no JIT channel - assert payer.rpc.decode(res.bolt11)["expiry"] == expiry + assert lsp.rpc.decode(res.bolt11)["expiry"] == expiry - # 4. Without an expiry, CLN's default (one week) still applies. + # Without an expiry, CLN's default (one week) still applies. res = gl.lsp_invoice( label="default-expiry", description="default-expiry", amount_msat=amount_msat, ) assert res.opening_fee_msat == 0 - assert payer.rpc.decode(res.bolt11)["expiry"] == 7 * 24 * 3600 + assert lsp.rpc.decode(res.bolt11)["expiry"] == 7 * 24 * 3600