From 3aee7101c034afe4c98900fa6859ecdbf5aca0ff Mon Sep 17 00:00:00 2001 From: sputn1ck Date: Tue, 24 Nov 2026 16:42:19 +0100 Subject: [PATCH 1/5] rpc: Define explicit active-channel receive requests Persist the selected rail and expose it to callers without changing ordinary receive semantics. --- rpc/swapclientrpc/AGENTS.md | 11 +++++++++++ rpc/swapclientrpc/CLAUDE.md | 11 +++++++++++ rpc/swapclientrpc/swap_client.proto | 12 ++++++++++++ rpc/wavewalletrpc/AGENTS.md | 5 +++++ rpc/wavewalletrpc/CLAUDE.md | 5 +++++ rpc/wavewalletrpc/wallet.proto | 13 +++++++++++++ rpc/wavewalletrpc/wallet.yaml | 3 +++ .../migrations/000005_ark_channel_receive.down.sql | 3 +++ .../migrations/000005_ark_channel_receive.up.sql | 10 ++++++++++ sdk/swaps/queries/swaps.sql | 13 ++++++++++--- sdk/swaps/store.go | 2 +- swaprpc/AGENTS.md | 8 ++++++++ swaprpc/CLAUDE.md | 8 ++++++++ swaprpc/swap.proto | 4 ++++ 14 files changed, 104 insertions(+), 4 deletions(-) create mode 100644 sdk/swaps/migrations/000005_ark_channel_receive.down.sql create mode 100644 sdk/swaps/migrations/000005_ark_channel_receive.up.sql diff --git a/rpc/swapclientrpc/AGENTS.md b/rpc/swapclientrpc/AGENTS.md index 33aa666c7..cd12f1877 100644 --- a/rpc/swapclientrpc/AGENTS.md +++ b/rpc/swapclientrpc/AGENTS.md @@ -14,6 +14,14 @@ credit funding/redemption/listing). Registered only in swapruntime builds. - Request/response messages (`QuotePayRequest`, `StartPayRequest`, `CreateCreditRequest`, `ListCreditsRequest`, etc.) and enums (`SwapState`, `SwapDirection`, `CreditOperationState`, ...). +- `SwapSettlementType` — Identifies the completed settlement rail. In addition + to `LIGHTNING`, `IN_ARK`, `CREDIT`, and `MIXED`, `ARK_CHANNEL` means a + receive completed through an Ark-backed native Lightning channel. +- `SwapSummary` — Flat durable view of one swap. Receive summaries expose + the existing `channel_id` reserved by an `active_channel_only` request and + `reserved_scid` for the virtual SCID advertised in the invoice. Before + exposing a channel-only invoice, clients must check that the response has + a channel ID: older daemons may ignore the request flag. ## Relationships @@ -25,6 +33,9 @@ credit funding/redemption/listing). Registered only in swapruntime builds. - Generated from `swap_client.proto` via `make rpc`; do not hand-edit any `.pb.go` / `.pb.gw.go` file. +- `SwapSummary` field 29 is reserved under the retired name + `channel_backing_fee_sat`. Reserved field numbers and names are part of the + wire contract and must never be reused. ## Deep Docs diff --git a/rpc/swapclientrpc/CLAUDE.md b/rpc/swapclientrpc/CLAUDE.md index 33aa666c7..cd12f1877 100644 --- a/rpc/swapclientrpc/CLAUDE.md +++ b/rpc/swapclientrpc/CLAUDE.md @@ -14,6 +14,14 @@ credit funding/redemption/listing). Registered only in swapruntime builds. - Request/response messages (`QuotePayRequest`, `StartPayRequest`, `CreateCreditRequest`, `ListCreditsRequest`, etc.) and enums (`SwapState`, `SwapDirection`, `CreditOperationState`, ...). +- `SwapSettlementType` — Identifies the completed settlement rail. In addition + to `LIGHTNING`, `IN_ARK`, `CREDIT`, and `MIXED`, `ARK_CHANNEL` means a + receive completed through an Ark-backed native Lightning channel. +- `SwapSummary` — Flat durable view of one swap. Receive summaries expose + the existing `channel_id` reserved by an `active_channel_only` request and + `reserved_scid` for the virtual SCID advertised in the invoice. Before + exposing a channel-only invoice, clients must check that the response has + a channel ID: older daemons may ignore the request flag. ## Relationships @@ -25,6 +33,9 @@ credit funding/redemption/listing). Registered only in swapruntime builds. - Generated from `swap_client.proto` via `make rpc`; do not hand-edit any `.pb.go` / `.pb.gw.go` file. +- `SwapSummary` field 29 is reserved under the retired name + `channel_backing_fee_sat`. Reserved field numbers and names are part of the + wire contract and must never be reused. ## Deep Docs diff --git a/rpc/swapclientrpc/swap_client.proto b/rpc/swapclientrpc/swap_client.proto index 410f3bdd0..18a546f1e 100644 --- a/rpc/swapclientrpc/swap_client.proto +++ b/rpc/swapclientrpc/swap_client.proto @@ -57,6 +57,7 @@ enum SwapSettlementType { SWAP_SETTLEMENT_TYPE_IN_ARK = 2; SWAP_SETTLEMENT_TYPE_CREDIT = 3; SWAP_SETTLEMENT_TYPE_MIXED = 4; + SWAP_SETTLEMENT_TYPE_ARK_CHANNEL = 5; } enum CreditFundingSource { @@ -273,6 +274,9 @@ message StartReceiveRequest { // memo is an optional human-readable label to embed as the BOLT-11 // invoice description. string memo = 3; + + // Only issue an invoice bound to an existing active channel. + bool active_channel_only = 4; } message StartReceiveResponse { @@ -451,4 +455,12 @@ message SwapSummary { // memo is the invoice memo a receive was created with. It is empty for // pays and for receives stored before memos were recorded. string memo = 27; + // Virtual short channel ID advertised in the receive invoice. + uint64 reserved_scid = 28; + + reserved 29; + reserved "channel_backing_fee_sat"; + + // Active channel selected for this receive; empty for vHTLC swaps. + bytes channel_id = 30; } diff --git a/rpc/wavewalletrpc/AGENTS.md b/rpc/wavewalletrpc/AGENTS.md index b4f363e9a..c8e75baa7 100644 --- a/rpc/wavewalletrpc/AGENTS.md +++ b/rpc/wavewalletrpc/AGENTS.md @@ -81,6 +81,11 @@ registration or estimate transaction confirmation. - `ExitMode` — which of the two exits an `Exit` call actually ran (`COOPERATIVE` / `UNILATERAL`). `EXIT_MODE_UNSPECIFIED` is what an older daemon sends; clients must treat it as "unknown", not as a default. +- `ActivitySwapTrace` — `InspectActivity`'s per-swap drill-down. It includes + the internal channel correlators that `List` omits: `channel_id` identifies + the existing Ark-backed Lightning channel reserved for a channel invoice, and `reserved_scid` is the virtual SCID advertised in the + invoice. Field 23 is reserved under the retired name + `channel_backing_fee_sat`. - `FailureDomain` / `Reason*` constants (`failure_reasons.go`) — the `google.rpc.ErrorInfo` domain/reason wire contract for failed wallet RPCs; existing reason values MUST NOT be renamed. diff --git a/rpc/wavewalletrpc/CLAUDE.md b/rpc/wavewalletrpc/CLAUDE.md index b4f363e9a..c8e75baa7 100644 --- a/rpc/wavewalletrpc/CLAUDE.md +++ b/rpc/wavewalletrpc/CLAUDE.md @@ -81,6 +81,11 @@ registration or estimate transaction confirmation. - `ExitMode` — which of the two exits an `Exit` call actually ran (`COOPERATIVE` / `UNILATERAL`). `EXIT_MODE_UNSPECIFIED` is what an older daemon sends; clients must treat it as "unknown", not as a default. +- `ActivitySwapTrace` — `InspectActivity`'s per-swap drill-down. It includes + the internal channel correlators that `List` omits: `channel_id` identifies + the existing Ark-backed Lightning channel reserved for a channel invoice, and `reserved_scid` is the virtual SCID advertised in the + invoice. Field 23 is reserved under the retired name + `channel_backing_fee_sat`. - `FailureDomain` / `Reason*` constants (`failure_reasons.go`) — the `google.rpc.ErrorInfo` domain/reason wire contract for failed wallet RPCs; existing reason values MUST NOT be renamed. diff --git a/rpc/wavewalletrpc/wallet.proto b/rpc/wavewalletrpc/wallet.proto index a8b9e9c14..3b6cef2fa 100644 --- a/rpc/wavewalletrpc/wallet.proto +++ b/rpc/wavewalletrpc/wallet.proto @@ -54,6 +54,10 @@ service WalletService { // start any new receive under a fresh request_id. rpc LookupRecv (LookupRecvRequest) returns (RecvResponse); + // RecvOnActiveChannel requires an existing Ark channel with inbound + // liquidity. Never creates a channel or falls back to a swap or credit. + rpc RecvOnActiveChannel (RecvRequest) returns (RecvResponse); + // List returns the unified wallet view selected by ListRequest.view: // ACTIVITY (default) is the merged WalletEntry stream; VTXOS is the // live VTXO inventory; ONCHAIN is the boarding-plus-sweep on-chain @@ -856,6 +860,15 @@ message ActivitySwapTrace { // revealed it. For a completed pay swap this is the proof of payment for // the paid invoice; it is empty until the preimage is durably known. string preimage = 20; + + // Active channel selected for this receive; empty for vHTLC swaps. + bytes channel_id = 21; + + // Virtual short channel ID advertised in the receive invoice. + uint64 reserved_scid = 22; + + reserved 23; + reserved "channel_backing_fee_sat"; } // ActivityVTXOTrace describes one VTXO movement correlated to a wallet activity diff --git a/rpc/wavewalletrpc/wallet.yaml b/rpc/wavewalletrpc/wallet.yaml index 29cefc3d3..6b3dfd289 100644 --- a/rpc/wavewalletrpc/wallet.yaml +++ b/rpc/wavewalletrpc/wallet.yaml @@ -21,6 +21,9 @@ http: - selector: wavewalletrpc.WalletService.LookupRecv post: /v1/wallet/lookup-recv body: "*" + - selector: wavewalletrpc.WalletService.RecvOnActiveChannel + post: /v1/wallet/recv-on-active-channel + body: "*" - selector: wavewalletrpc.WalletService.List post: /v1/wallet/list body: "*" diff --git a/sdk/swaps/migrations/000005_ark_channel_receive.down.sql b/sdk/swaps/migrations/000005_ark_channel_receive.down.sql new file mode 100644 index 000000000..006931931 --- /dev/null +++ b/sdk/swaps/migrations/000005_ark_channel_receive.down.sql @@ -0,0 +1,3 @@ +ALTER TABLE receive_swaps DROP COLUMN channel_id; +ALTER TABLE receive_swaps DROP COLUMN channel_receive_enabled; +ALTER TABLE receive_swaps DROP COLUMN reserved_scid; diff --git a/sdk/swaps/migrations/000005_ark_channel_receive.up.sql b/sdk/swaps/migrations/000005_ark_channel_receive.up.sql new file mode 100644 index 000000000..4e81867b5 --- /dev/null +++ b/sdk/swaps/migrations/000005_ark_channel_receive.up.sql @@ -0,0 +1,10 @@ +-- Persist the future-channel identity and ownership needed to resume direct +-- private settlement after restart. +ALTER TABLE receive_swaps + ADD COLUMN reserved_scid BLOB; + +ALTER TABLE receive_swaps + ADD COLUMN channel_receive_enabled BOOLEAN NOT NULL DEFAULT FALSE; + +ALTER TABLE receive_swaps + ADD COLUMN channel_id BLOB; diff --git a/sdk/swaps/queries/swaps.sql b/sdk/swaps/queries/swaps.sql index 944129abd..a180ce1b5 100644 --- a/sdk/swaps/queries/swaps.sql +++ b/sdk/swaps/queries/swaps.sql @@ -10,11 +10,12 @@ INSERT INTO receive_swaps ( pending_htlc_ack_cursor, claim_receive_pubkey, claim_receive_pkscript, claim_session_id, claim_recovery_id, intervention_reason, requested_amount_sat, available_credit_sat, attached_credit_sat, - dust_limit_sat, created_at_unix, updated_at_unix, request_id, memo + dust_limit_sat, reserved_scid, channel_receive_enabled, channel_id, + created_at_unix, updated_at_unix, request_id, memo ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, - $29, $30, $31, $32, $33, $34 + $29, $30, $31, $32, $33, $34, $35, $36, $37 ) ON CONFLICT (payment_hash) DO NOTHING; @@ -50,6 +51,9 @@ INSERT INTO receive_swaps ( available_credit_sat, attached_credit_sat, dust_limit_sat, + reserved_scid, + channel_receive_enabled, + channel_id, created_at_unix, updated_at_unix, request_id, @@ -57,7 +61,7 @@ INSERT INTO receive_swaps ( ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, - $29, $30, $31, $32, $33, $34 + $29, $30, $31, $32, $33, $34, $35, $36, $37 ) ON CONFLICT (payment_hash) DO UPDATE SET amount_sat = EXCLUDED.amount_sat, @@ -90,6 +94,9 @@ ON CONFLICT (payment_hash) DO UPDATE SET available_credit_sat = EXCLUDED.available_credit_sat, attached_credit_sat = EXCLUDED.attached_credit_sat, dust_limit_sat = EXCLUDED.dust_limit_sat, + reserved_scid = EXCLUDED.reserved_scid, + channel_receive_enabled = EXCLUDED.channel_receive_enabled, + channel_id = EXCLUDED.channel_id, updated_at_unix = EXCLUDED.updated_at_unix; -- name: GetReceiveSwap :one diff --git a/sdk/swaps/store.go b/sdk/swaps/store.go index 71f065566..339e37eed 100644 --- a/sdk/swaps/store.go +++ b/sdk/swaps/store.go @@ -38,7 +38,7 @@ const ( defaultConnMaxLifetime = 10 * time.Minute // LatestMigrationVersion is the latest swap-client schema migration. - LatestMigrationVersion uint = 4 + LatestMigrationVersion uint = 5 ) //go:embed migrations/*.sql diff --git a/swaprpc/AGENTS.md b/swaprpc/AGENTS.md index fb2296f33..62132793e 100644 --- a/swaprpc/AGENTS.md +++ b/swaprpc/AGENTS.md @@ -88,6 +88,14 @@ because they are part of the wire contract, not of either side's logic. - `SettlementType.SETTLEMENT_TYPE_UNSPECIFIED` (0) is treated as Lightning for backward compatibility with older server responses; do not repurpose the zero value. +- The final hop returned by `RequestChannelId` is the reserved virtual SCID + shared by the optional Ark-channel rail and the ordinary vHTLC rail. The + server quote does not claim that the channel rail won; that outcome is + reported later by the daemon's `swapclientrpc` settlement type. +- `RequestChannelIdRequest` field 7 and `RequestChannelIdResponse` field 10 + are reserved under the retired name `channel_backing_fee_sat`. Receives no + longer negotiate that legacy fee reserve on the wire. Never reuse reserved + field numbers or names. - `SwapMailboxEvent` is a proto oneof: read the populated variant, don't assume `OutSwapHtlcEvent` is the only case as new event kinds are added. diff --git a/swaprpc/CLAUDE.md b/swaprpc/CLAUDE.md index fb2296f33..62132793e 100644 --- a/swaprpc/CLAUDE.md +++ b/swaprpc/CLAUDE.md @@ -88,6 +88,14 @@ because they are part of the wire contract, not of either side's logic. - `SettlementType.SETTLEMENT_TYPE_UNSPECIFIED` (0) is treated as Lightning for backward compatibility with older server responses; do not repurpose the zero value. +- The final hop returned by `RequestChannelId` is the reserved virtual SCID + shared by the optional Ark-channel rail and the ordinary vHTLC rail. The + server quote does not claim that the channel rail won; that outcome is + reported later by the daemon's `swapclientrpc` settlement type. +- `RequestChannelIdRequest` field 7 and `RequestChannelIdResponse` field 10 + are reserved under the retired name `channel_backing_fee_sat`. Receives no + longer negotiate that legacy fee reserve on the wire. Never reuse reserved + field numbers or names. - `SwapMailboxEvent` is a proto oneof: read the populated variant, don't assume `OutSwapHtlcEvent` is the only case as new event kinds are added. diff --git a/swaprpc/swap.proto b/swaprpc/swap.proto index 1799c17f1..74e1a6c53 100644 --- a/swaprpc/swap.proto +++ b/swaprpc/swap.proto @@ -192,6 +192,8 @@ message RequestChannelIdRequest { // involving the wallet. Send it only over an authenticated transport. // This key does not authorize Ark operations or derive the preimage. bytes invoice_routing_key = 9; + + reserved "channel_backing_fee_sat"; } // RequestChannelIdResponse returns the route hint paths for one receive @@ -240,6 +242,8 @@ message RequestChannelIdResponse { // invoice_routing_pubkey confirms the service registered the supplied // key. The wallet must check it before exposing a probe-capable invoice. bytes invoice_routing_pubkey = 10; + + reserved "channel_backing_fee_sat"; } // AcknowledgeOutSwapHtlcRequest confirms that the receiver has validated and From adae5f486b8dabb50e086d3675fcc412bbb4587d Mon Sep 17 00:00:00 2001 From: sputn1ck Date: Tue, 24 Nov 2026 16:42:19 +0100 Subject: [PATCH 2/5] rpc: Generate active-channel receive bindings Keep generated wallet, SDK and storage bindings aligned with the explicit channel request and settlement types. --- .../devrpc/registry_generated.go | 7 + rpc/restclient/clients.go | 12 ++ rpc/swapclientrpc/swap_client.pb.go | 55 +++++-- rpc/wavewalletrpc/wallet.pb.go | 110 +++++++------ rpc/wavewalletrpc/wallet.pb.gw.go | 146 +++++++++++++----- rpc/wavewalletrpc/wallet_grpc.pb.go | 82 +++++++--- rpc/wavewalletrpc/wallet_mailboxrpc.pb.go | 35 +++++ sdk/swaps/sqlc/models.go | 3 + sdk/swaps/sqlc/swaps.sql.go | 45 +++++- swaprpc/swap.pb.go | 6 +- waved/rpc_auth.go | 5 +- waved/rpc_auth_test.go | 1 + 12 files changed, 382 insertions(+), 125 deletions(-) diff --git a/cmd/wavecli/waveclicommands/devrpc/registry_generated.go b/cmd/wavecli/waveclicommands/devrpc/registry_generated.go index a9485c7ff..d16dca88b 100644 --- a/cmd/wavecli/waveclicommands/devrpc/registry_generated.go +++ b/cmd/wavecli/waveclicommands/devrpc/registry_generated.go @@ -550,6 +550,13 @@ func generatedRegistry() []serviceSpec { Output: "wavewalletrpc.RecvResponse", Comments: "", }, + { + Name: "RecvOnActiveChannel", + Aliases: []string{"recv-on-active-channel"}, + Input: "wavewalletrpc.RecvRequest", + Output: "wavewalletrpc.RecvResponse", + Comments: "", + }, { Name: "List", Aliases: []string{"list"}, diff --git a/rpc/restclient/clients.go b/rpc/restclient/clients.go index 441209286..5d4acbdfd 100644 --- a/rpc/restclient/clients.go +++ b/rpc/restclient/clients.go @@ -1240,6 +1240,18 @@ func (c *WalletServiceClient) LookupRecv(ctx context.Context, return out, err } +// RecvOnActiveChannel requires the dedicated endpoint; an older daemon +// must reject this call rather than minting an ordinary receive invoice. +func (c *WalletServiceClient) RecvOnActiveChannel(ctx context.Context, + in *wavewalletrpc.RecvRequest, _ ...grpc.CallOption) ( + *wavewalletrpc.RecvResponse, error) { + + out := new(wavewalletrpc.RecvResponse) + err := c.client.Post(ctx, "/v1/wallet/recv-on-active-channel", in, out) + + return out, err +} + // List returns a wallet list view. func (c *WalletServiceClient) List(ctx context.Context, in *wavewalletrpc.ListRequest, _ ...grpc.CallOption) ( diff --git a/rpc/swapclientrpc/swap_client.pb.go b/rpc/swapclientrpc/swap_client.pb.go index 6784700c9..bdba2599a 100644 --- a/rpc/swapclientrpc/swap_client.pb.go +++ b/rpc/swapclientrpc/swap_client.pb.go @@ -78,6 +78,7 @@ const ( SwapSettlementType_SWAP_SETTLEMENT_TYPE_IN_ARK SwapSettlementType = 2 SwapSettlementType_SWAP_SETTLEMENT_TYPE_CREDIT SwapSettlementType = 3 SwapSettlementType_SWAP_SETTLEMENT_TYPE_MIXED SwapSettlementType = 4 + SwapSettlementType_SWAP_SETTLEMENT_TYPE_ARK_CHANNEL SwapSettlementType = 5 ) // Enum value maps for SwapSettlementType. @@ -88,6 +89,7 @@ var ( 2: "SWAP_SETTLEMENT_TYPE_IN_ARK", 3: "SWAP_SETTLEMENT_TYPE_CREDIT", 4: "SWAP_SETTLEMENT_TYPE_MIXED", + 5: "SWAP_SETTLEMENT_TYPE_ARK_CHANNEL", } SwapSettlementType_value = map[string]int32{ "SWAP_SETTLEMENT_TYPE_UNSPECIFIED": 0, @@ -95,6 +97,7 @@ var ( "SWAP_SETTLEMENT_TYPE_IN_ARK": 2, "SWAP_SETTLEMENT_TYPE_CREDIT": 3, "SWAP_SETTLEMENT_TYPE_MIXED": 4, + "SWAP_SETTLEMENT_TYPE_ARK_CHANNEL": 5, } ) @@ -1437,9 +1440,11 @@ type StartReceiveRequest struct { IdempotencyKey string `protobuf:"bytes,2,opt,name=idempotency_key,json=idempotencyKey,proto3" json:"idempotency_key,omitempty"` // memo is an optional human-readable label to embed as the BOLT-11 // invoice description. - Memo string `protobuf:"bytes,3,opt,name=memo,proto3" json:"memo,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + Memo string `protobuf:"bytes,3,opt,name=memo,proto3" json:"memo,omitempty"` + // Only issue an invoice bound to an existing active channel. + ActiveChannelOnly bool `protobuf:"varint,4,opt,name=active_channel_only,json=activeChannelOnly,proto3" json:"active_channel_only,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *StartReceiveRequest) Reset() { @@ -1493,6 +1498,13 @@ func (x *StartReceiveRequest) GetMemo() string { return "" } +func (x *StartReceiveRequest) GetActiveChannelOnly() bool { + if x != nil { + return x.ActiveChannelOnly + } + return false +} + type StartReceiveResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // payment_hash is the Lightning payment hash committed into the invoice and @@ -2070,7 +2082,11 @@ type SwapSummary struct { AvailableCreditSat uint64 `protobuf:"varint,26,opt,name=available_credit_sat,json=availableCreditSat,proto3" json:"available_credit_sat,omitempty"` // memo is the invoice memo a receive was created with. It is empty for // pays and for receives stored before memos were recorded. - Memo string `protobuf:"bytes,27,opt,name=memo,proto3" json:"memo,omitempty"` + Memo string `protobuf:"bytes,27,opt,name=memo,proto3" json:"memo,omitempty"` + // Virtual short channel ID advertised in the receive invoice. + ReservedScid uint64 `protobuf:"varint,28,opt,name=reserved_scid,json=reservedScid,proto3" json:"reserved_scid,omitempty"` + // Active channel selected for this receive; empty for vHTLC swaps. + ChannelId []byte `protobuf:"bytes,30,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -2294,6 +2310,20 @@ func (x *SwapSummary) GetMemo() string { return "" } +func (x *SwapSummary) GetReservedScid() uint64 { + if x != nil { + return x.ReservedScid + } + return 0 +} + +func (x *SwapSummary) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + var File_swap_client_proto protoreflect.FileDescriptor const file_swap_client_proto_rawDesc = "" + @@ -2393,12 +2423,13 @@ const file_swap_client_proto_rawDesc = "" + "\tdirection\x18\x03 \x01(\tR\tdirection\x12\x1d\n" + "\n" + "amount_sat\x18\x04 \x01(\x04R\tamountSat\x12&\n" + - "\x0fcreated_at_unix\x18\x05 \x01(\x03R\rcreatedAtUnix\"q\n" + + "\x0fcreated_at_unix\x18\x05 \x01(\x03R\rcreatedAtUnix\"\xa1\x01\n" + "\x13StartReceiveRequest\x12\x1d\n" + "\n" + "amount_sat\x18\x01 \x01(\x03R\tamountSat\x12'\n" + "\x0fidempotency_key\x18\x02 \x01(\tR\x0eidempotencyKey\x12\x12\n" + - "\x04memo\x18\x03 \x01(\tR\x04memo\"\xb3\x03\n" + + "\x04memo\x18\x03 \x01(\tR\x04memo\x12.\n" + + "\x13active_channel_only\x18\x04 \x01(\bR\x11activeChannelOnly\"\xb3\x03\n" + "\x14StartReceiveResponse\x12!\n" + "\fpayment_hash\x18\x01 \x01(\tR\vpaymentHash\x12\x18\n" + "\ainvoice\x18\x02 \x01(\tR\ainvoice\x12.\n" + @@ -2427,7 +2458,7 @@ const file_swap_client_proto_rawDesc = "" + "\x10include_existing\x18\x01 \x01(\bR\x0fincludeExisting\x12!\n" + "\fpending_only\x18\x02 \x01(\bR\vpendingOnly\"H\n" + "\x16SubscribeSwapsResponse\x12.\n" + - "\x04swap\x18\x01 \x01(\v2\x1a.swapclientrpc.SwapSummaryR\x04swap\"\xde\b\n" + + "\x04swap\x18\x01 \x01(\v2\x1a.swapclientrpc.SwapSummaryR\x04swap\"\xc1\t\n" + "\vSwapSummary\x12:\n" + "\tdirection\x18\x01 \x01(\x0e2\x1c.swapclientrpc.SwapDirectionR\tdirection\x12!\n" + "\fpayment_hash\x18\x02 \x01(\tR\vpaymentHash\x12.\n" + @@ -2457,17 +2488,21 @@ const file_swap_client_proto_rawDesc = "" + "\x13attached_credit_sat\x18\x18 \x01(\x04R\x11attachedCreditSat\x12$\n" + "\x0edust_limit_sat\x18\x19 \x01(\x04R\fdustLimitSat\x120\n" + "\x14available_credit_sat\x18\x1a \x01(\x04R\x12availableCreditSat\x12\x12\n" + - "\x04memo\x18\x1b \x01(\tR\x04memo*c\n" + + "\x04memo\x18\x1b \x01(\tR\x04memo\x12#\n" + + "\rreserved_scid\x18\x1c \x01(\x04R\freservedScid\x12\x1d\n" + + "\n" + + "channel_id\x18\x1e \x01(\fR\tchannelIdJ\x04\b\x1d\x10\x1eR\x17channel_backing_fee_sat*c\n" + "\rSwapDirection\x12\x1e\n" + "\x1aSWAP_DIRECTION_UNSPECIFIED\x10\x00\x12\x16\n" + "\x12SWAP_DIRECTION_PAY\x10\x01\x12\x1a\n" + - "\x16SWAP_DIRECTION_RECEIVE\x10\x02*\xc0\x01\n" + + "\x16SWAP_DIRECTION_RECEIVE\x10\x02*\xe6\x01\n" + "\x12SwapSettlementType\x12$\n" + " SWAP_SETTLEMENT_TYPE_UNSPECIFIED\x10\x00\x12\"\n" + "\x1eSWAP_SETTLEMENT_TYPE_LIGHTNING\x10\x01\x12\x1f\n" + "\x1bSWAP_SETTLEMENT_TYPE_IN_ARK\x10\x02\x12\x1f\n" + "\x1bSWAP_SETTLEMENT_TYPE_CREDIT\x10\x03\x12\x1e\n" + - "\x1aSWAP_SETTLEMENT_TYPE_MIXED\x10\x04*\x8e\x01\n" + + "\x1aSWAP_SETTLEMENT_TYPE_MIXED\x10\x04\x12$\n" + + " SWAP_SETTLEMENT_TYPE_ARK_CHANNEL\x10\x05*\x8e\x01\n" + "\x13CreditFundingSource\x12%\n" + "!CREDIT_FUNDING_SOURCE_UNSPECIFIED\x10\x00\x12+\n" + "'CREDIT_FUNDING_SOURCE_LIGHTNING_RECEIVE\x10\x01\x12#\n" + diff --git a/rpc/wavewalletrpc/wallet.pb.go b/rpc/wavewalletrpc/wallet.pb.go index 86ac3fb0b..a69201cb6 100644 --- a/rpc/wavewalletrpc/wallet.pb.go +++ b/rpc/wavewalletrpc/wallet.pb.go @@ -2759,7 +2759,11 @@ type ActivitySwapTrace struct { // preimage is the hex-encoded Lightning payment preimage once the swap // revealed it. For a completed pay swap this is the proof of payment for // the paid invoice; it is empty until the preimage is durably known. - Preimage string `protobuf:"bytes,20,opt,name=preimage,proto3" json:"preimage,omitempty"` + Preimage string `protobuf:"bytes,20,opt,name=preimage,proto3" json:"preimage,omitempty"` + // Active channel selected for this receive; empty for vHTLC swaps. + ChannelId []byte `protobuf:"bytes,21,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + // Virtual short channel ID advertised in the receive invoice. + ReservedScid uint64 `protobuf:"varint,22,opt,name=reserved_scid,json=reservedScid,proto3" json:"reserved_scid,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -2934,6 +2938,20 @@ func (x *ActivitySwapTrace) GetPreimage() string { return "" } +func (x *ActivitySwapTrace) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +func (x *ActivitySwapTrace) GetReservedScid() uint64 { + if x != nil { + return x.ReservedScid + } + return 0 +} + // ActivityVTXOTrace describes one VTXO movement correlated to a wallet activity // entry. type ActivityVTXOTrace struct { @@ -7197,7 +7215,7 @@ const file_wallet_proto_rawDesc = "" + "\x05vtxos\x18\x03 \x03(\v2 .wavewalletrpc.ActivityVTXOTraceR\x05vtxos\x12C\n" + "\vledger_rows\x18\x04 \x03(\v2\".wavewalletrpc.ActivityLedgerTraceR\n" + "ledgerRows\x12\x14\n" + - "\x05notes\x18\x05 \x03(\tR\x05notes\"\xdc\x05\n" + + "\x05notes\x18\x05 \x03(\tR\x05notes\"\xbf\x06\n" + "\x11ActivitySwapTrace\x12!\n" + "\fpayment_hash\x18\x01 \x01(\tR\vpaymentHash\x12\x1c\n" + "\tdirection\x18\x02 \x01(\tR\tdirection\x12\x14\n" + @@ -7220,7 +7238,10 @@ const file_wallet_proto_rawDesc = "" + "\x0frefund_locktime\x18\x11 \x01(\rR\x0erefundLocktime\x12'\n" + "\x0fsettlement_type\x18\x12 \x01(\tR\x0esettlementType\x12#\n" + "\rsender_pubkey\x18\x13 \x01(\tR\fsenderPubkey\x12\x1a\n" + - "\bpreimage\x18\x14 \x01(\tR\bpreimage\"\xc4\x01\n" + + "\bpreimage\x18\x14 \x01(\tR\bpreimage\x12\x1d\n" + + "\n" + + "channel_id\x18\x15 \x01(\fR\tchannelId\x12#\n" + + "\rreserved_scid\x18\x16 \x01(\x04R\freservedScidJ\x04\b\x17\x10\x18R\x17channel_backing_fee_sat\"\xc4\x01\n" + "\x11ActivityVTXOTrace\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x12\x1d\n" + "\n" + @@ -7596,7 +7617,7 @@ const file_wallet_proto_rawDesc = "" + "\x1aENTRY_FAILURE_CODE_EXPIRED\x10\x02\x12\x1f\n" + "\x1bENTRY_FAILURE_CODE_REFUNDED\x10\x03\x12)\n" + "%ENTRY_FAILURE_CODE_NEEDS_INTERVENTION\x10\x04\x12\x1d\n" + - "\x19ENTRY_FAILURE_CODE_FAILED\x10\x052\x9b\f\n" + + "\x19ENTRY_FAILURE_CODE_FAILED\x10\x052\xeb\f\n" + "\rWalletService\x12E\n" + "\x06Create\x12\x1c.wavewalletrpc.CreateRequest\x1a\x1d.wavewalletrpc.CreateResponse\x12E\n" + "\x06Unlock\x12\x1c.wavewalletrpc.UnlockRequest\x1a\x1d.wavewalletrpc.UnlockResponse\x12T\n" + @@ -7604,7 +7625,8 @@ const file_wallet_proto_rawDesc = "" + "\x04Send\x12\x1a.wavewalletrpc.SendRequest\x1a\x1b.wavewalletrpc.SendResponse\x12?\n" + "\x04Recv\x12\x1a.wavewalletrpc.RecvRequest\x1a\x1b.wavewalletrpc.RecvResponse\x12K\n" + "\n" + - "LookupRecv\x12 .wavewalletrpc.LookupRecvRequest\x1a\x1b.wavewalletrpc.RecvResponse\x12?\n" + + "LookupRecv\x12 .wavewalletrpc.LookupRecvRequest\x1a\x1b.wavewalletrpc.RecvResponse\x12N\n" + + "\x13RecvOnActiveChannel\x12\x1a.wavewalletrpc.RecvRequest\x1a\x1b.wavewalletrpc.RecvResponse\x12?\n" + "\x04List\x12\x1a.wavewalletrpc.ListRequest\x1a\x1b.wavewalletrpc.ListResponse\x12H\n" + "\aDeposit\x12\x1d.wavewalletrpc.DepositRequest\x1a\x1e.wavewalletrpc.DepositResponse\x12H\n" + "\aBalance\x12\x1d.wavewalletrpc.BalanceRequest\x1a\x1e.wavewalletrpc.BalanceResponse\x12E\n" + @@ -7786,44 +7808,46 @@ var file_wallet_proto_depIdxs = []int32{ 17, // 59: wavewalletrpc.WalletService.Send:input_type -> wavewalletrpc.SendRequest 19, // 60: wavewalletrpc.WalletService.Recv:input_type -> wavewalletrpc.RecvRequest 20, // 61: wavewalletrpc.WalletService.LookupRecv:input_type -> wavewalletrpc.LookupRecvRequest - 24, // 62: wavewalletrpc.WalletService.List:input_type -> wavewalletrpc.ListRequest - 36, // 63: wavewalletrpc.WalletService.Deposit:input_type -> wavewalletrpc.DepositRequest - 38, // 64: wavewalletrpc.WalletService.Balance:input_type -> wavewalletrpc.BalanceRequest - 40, // 65: wavewalletrpc.WalletService.Status:input_type -> wavewalletrpc.StatusRequest - 51, // 66: wavewalletrpc.WalletService.Refresh:input_type -> wavewalletrpc.RefreshRequest - 54, // 67: wavewalletrpc.WalletService.GetExitPlan:input_type -> wavewalletrpc.GetExitPlanRequest - 42, // 68: wavewalletrpc.WalletService.ExportExit:input_type -> wavewalletrpc.ExportExitRequest - 44, // 69: wavewalletrpc.WalletService.ExportExits:input_type -> wavewalletrpc.ExportExitsRequest - 57, // 70: wavewalletrpc.WalletService.SweepWallet:input_type -> wavewalletrpc.SweepWalletRequest - 60, // 71: wavewalletrpc.WalletService.Exit:input_type -> wavewalletrpc.ExitRequest - 62, // 72: wavewalletrpc.WalletService.ExitBatch:input_type -> wavewalletrpc.ExitBatchRequest - 65, // 73: wavewalletrpc.WalletService.ExitStatus:input_type -> wavewalletrpc.ExitStatusRequest - 70, // 74: wavewalletrpc.WalletService.ExitSummary:input_type -> wavewalletrpc.ExitSummaryRequest - 73, // 75: wavewalletrpc.WalletService.SubscribeWallet:input_type -> wavewalletrpc.SubscribeWalletRequest - 31, // 76: wavewalletrpc.WalletInspectionService.InspectActivity:input_type -> wavewalletrpc.InspectActivityRequest - 12, // 77: wavewalletrpc.WalletService.Create:output_type -> wavewalletrpc.CreateResponse - 14, // 78: wavewalletrpc.WalletService.Unlock:output_type -> wavewalletrpc.UnlockResponse - 16, // 79: wavewalletrpc.WalletService.PrepareSend:output_type -> wavewalletrpc.PrepareSendResponse - 18, // 80: wavewalletrpc.WalletService.Send:output_type -> wavewalletrpc.SendResponse - 21, // 81: wavewalletrpc.WalletService.Recv:output_type -> wavewalletrpc.RecvResponse - 21, // 82: wavewalletrpc.WalletService.LookupRecv:output_type -> wavewalletrpc.RecvResponse - 25, // 83: wavewalletrpc.WalletService.List:output_type -> wavewalletrpc.ListResponse - 37, // 84: wavewalletrpc.WalletService.Deposit:output_type -> wavewalletrpc.DepositResponse - 39, // 85: wavewalletrpc.WalletService.Balance:output_type -> wavewalletrpc.BalanceResponse - 41, // 86: wavewalletrpc.WalletService.Status:output_type -> wavewalletrpc.StatusResponse - 52, // 87: wavewalletrpc.WalletService.Refresh:output_type -> wavewalletrpc.RefreshResponse - 56, // 88: wavewalletrpc.WalletService.GetExitPlan:output_type -> wavewalletrpc.GetExitPlanResponse - 43, // 89: wavewalletrpc.WalletService.ExportExit:output_type -> wavewalletrpc.ExportExitResponse - 45, // 90: wavewalletrpc.WalletService.ExportExits:output_type -> wavewalletrpc.ExportExitsResponse - 59, // 91: wavewalletrpc.WalletService.SweepWallet:output_type -> wavewalletrpc.SweepWalletResponse - 61, // 92: wavewalletrpc.WalletService.Exit:output_type -> wavewalletrpc.ExitResponse - 64, // 93: wavewalletrpc.WalletService.ExitBatch:output_type -> wavewalletrpc.ExitBatchResponse - 69, // 94: wavewalletrpc.WalletService.ExitStatus:output_type -> wavewalletrpc.ExitStatusResponse - 72, // 95: wavewalletrpc.WalletService.ExitSummary:output_type -> wavewalletrpc.ExitSummaryResponse - 74, // 96: wavewalletrpc.WalletService.SubscribeWallet:output_type -> wavewalletrpc.SubscribeWalletResponse - 32, // 97: wavewalletrpc.WalletInspectionService.InspectActivity:output_type -> wavewalletrpc.InspectActivityResponse - 77, // [77:98] is the sub-list for method output_type - 56, // [56:77] is the sub-list for method input_type + 19, // 62: wavewalletrpc.WalletService.RecvOnActiveChannel:input_type -> wavewalletrpc.RecvRequest + 24, // 63: wavewalletrpc.WalletService.List:input_type -> wavewalletrpc.ListRequest + 36, // 64: wavewalletrpc.WalletService.Deposit:input_type -> wavewalletrpc.DepositRequest + 38, // 65: wavewalletrpc.WalletService.Balance:input_type -> wavewalletrpc.BalanceRequest + 40, // 66: wavewalletrpc.WalletService.Status:input_type -> wavewalletrpc.StatusRequest + 51, // 67: wavewalletrpc.WalletService.Refresh:input_type -> wavewalletrpc.RefreshRequest + 54, // 68: wavewalletrpc.WalletService.GetExitPlan:input_type -> wavewalletrpc.GetExitPlanRequest + 42, // 69: wavewalletrpc.WalletService.ExportExit:input_type -> wavewalletrpc.ExportExitRequest + 44, // 70: wavewalletrpc.WalletService.ExportExits:input_type -> wavewalletrpc.ExportExitsRequest + 57, // 71: wavewalletrpc.WalletService.SweepWallet:input_type -> wavewalletrpc.SweepWalletRequest + 60, // 72: wavewalletrpc.WalletService.Exit:input_type -> wavewalletrpc.ExitRequest + 62, // 73: wavewalletrpc.WalletService.ExitBatch:input_type -> wavewalletrpc.ExitBatchRequest + 65, // 74: wavewalletrpc.WalletService.ExitStatus:input_type -> wavewalletrpc.ExitStatusRequest + 70, // 75: wavewalletrpc.WalletService.ExitSummary:input_type -> wavewalletrpc.ExitSummaryRequest + 73, // 76: wavewalletrpc.WalletService.SubscribeWallet:input_type -> wavewalletrpc.SubscribeWalletRequest + 31, // 77: wavewalletrpc.WalletInspectionService.InspectActivity:input_type -> wavewalletrpc.InspectActivityRequest + 12, // 78: wavewalletrpc.WalletService.Create:output_type -> wavewalletrpc.CreateResponse + 14, // 79: wavewalletrpc.WalletService.Unlock:output_type -> wavewalletrpc.UnlockResponse + 16, // 80: wavewalletrpc.WalletService.PrepareSend:output_type -> wavewalletrpc.PrepareSendResponse + 18, // 81: wavewalletrpc.WalletService.Send:output_type -> wavewalletrpc.SendResponse + 21, // 82: wavewalletrpc.WalletService.Recv:output_type -> wavewalletrpc.RecvResponse + 21, // 83: wavewalletrpc.WalletService.LookupRecv:output_type -> wavewalletrpc.RecvResponse + 21, // 84: wavewalletrpc.WalletService.RecvOnActiveChannel:output_type -> wavewalletrpc.RecvResponse + 25, // 85: wavewalletrpc.WalletService.List:output_type -> wavewalletrpc.ListResponse + 37, // 86: wavewalletrpc.WalletService.Deposit:output_type -> wavewalletrpc.DepositResponse + 39, // 87: wavewalletrpc.WalletService.Balance:output_type -> wavewalletrpc.BalanceResponse + 41, // 88: wavewalletrpc.WalletService.Status:output_type -> wavewalletrpc.StatusResponse + 52, // 89: wavewalletrpc.WalletService.Refresh:output_type -> wavewalletrpc.RefreshResponse + 56, // 90: wavewalletrpc.WalletService.GetExitPlan:output_type -> wavewalletrpc.GetExitPlanResponse + 43, // 91: wavewalletrpc.WalletService.ExportExit:output_type -> wavewalletrpc.ExportExitResponse + 45, // 92: wavewalletrpc.WalletService.ExportExits:output_type -> wavewalletrpc.ExportExitsResponse + 59, // 93: wavewalletrpc.WalletService.SweepWallet:output_type -> wavewalletrpc.SweepWalletResponse + 61, // 94: wavewalletrpc.WalletService.Exit:output_type -> wavewalletrpc.ExitResponse + 64, // 95: wavewalletrpc.WalletService.ExitBatch:output_type -> wavewalletrpc.ExitBatchResponse + 69, // 96: wavewalletrpc.WalletService.ExitStatus:output_type -> wavewalletrpc.ExitStatusResponse + 72, // 97: wavewalletrpc.WalletService.ExitSummary:output_type -> wavewalletrpc.ExitSummaryResponse + 74, // 98: wavewalletrpc.WalletService.SubscribeWallet:output_type -> wavewalletrpc.SubscribeWalletResponse + 32, // 99: wavewalletrpc.WalletInspectionService.InspectActivity:output_type -> wavewalletrpc.InspectActivityResponse + 78, // [78:100] is the sub-list for method output_type + 56, // [56:78] is the sub-list for method input_type 56, // [56:56] is the sub-list for extension type_name 56, // [56:56] is the sub-list for extension extendee 0, // [0:56] is the sub-list for field type_name diff --git a/rpc/wavewalletrpc/wallet.pb.gw.go b/rpc/wavewalletrpc/wallet.pb.gw.go index e5ae93ddd..8a7a384a7 100644 --- a/rpc/wavewalletrpc/wallet.pb.gw.go +++ b/rpc/wavewalletrpc/wallet.pb.gw.go @@ -197,6 +197,33 @@ func local_request_WalletService_LookupRecv_0(ctx context.Context, marshaler run return msg, metadata, err } +func request_WalletService_RecvOnActiveChannel_0(ctx context.Context, marshaler runtime.Marshaler, client WalletServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq RecvRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } + msg, err := client.RecvOnActiveChannel(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_WalletService_RecvOnActiveChannel_0(ctx context.Context, marshaler runtime.Marshaler, server WalletServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq RecvRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + msg, err := server.RecvOnActiveChannel(ctx, &protoReq) + return msg, metadata, err +} + func request_WalletService_List_0(ctx context.Context, marshaler runtime.Marshaler, client WalletServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq ListRequest @@ -724,6 +751,26 @@ func RegisterWalletServiceHandlerServer(ctx context.Context, mux *runtime.ServeM } forward_WalletService_LookupRecv_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) + mux.Handle(http.MethodPost, pattern_WalletService_RecvOnActiveChannel_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/wavewalletrpc.WalletService/RecvOnActiveChannel", runtime.WithHTTPPathPattern("/v1/wallet/recv-on-active-channel")) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_WalletService_RecvOnActiveChannel_0(annotatedContext, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) + if err != nil { + runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) + return + } + forward_WalletService_RecvOnActiveChannel_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) mux.Handle(http.MethodPost, pattern_WalletService_List_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -1163,6 +1210,23 @@ func RegisterWalletServiceHandlerClient(ctx context.Context, mux *runtime.ServeM } forward_WalletService_LookupRecv_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) + mux.Handle(http.MethodPost, pattern_WalletService_RecvOnActiveChannel_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/wavewalletrpc.WalletService/RecvOnActiveChannel", runtime.WithHTTPPathPattern("/v1/wallet/recv-on-active-channel")) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_WalletService_RecvOnActiveChannel_0(annotatedContext, inboundMarshaler, client, req, pathParams) + annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) + if err != nil { + runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) + return + } + forward_WalletService_RecvOnActiveChannel_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) mux.Handle(http.MethodPost, pattern_WalletService_List_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -1405,49 +1469,51 @@ func RegisterWalletServiceHandlerClient(ctx context.Context, mux *runtime.ServeM } var ( - pattern_WalletService_Create_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "create"}, "")) - pattern_WalletService_Unlock_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "unlock"}, "")) - pattern_WalletService_PrepareSend_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "prepare-send"}, "")) - pattern_WalletService_Send_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "send"}, "")) - pattern_WalletService_Recv_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "recv"}, "")) - pattern_WalletService_LookupRecv_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "lookup-recv"}, "")) - pattern_WalletService_List_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "list"}, "")) - pattern_WalletService_Deposit_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "deposit"}, "")) - pattern_WalletService_Balance_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "balance"}, "")) - pattern_WalletService_Status_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "status"}, "")) - pattern_WalletService_Refresh_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "refresh"}, "")) - pattern_WalletService_GetExitPlan_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "exit-plan"}, "")) - pattern_WalletService_ExportExit_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "exit-export"}, "")) - pattern_WalletService_ExportExits_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "exits-export"}, "")) - pattern_WalletService_SweepWallet_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "sweep-wallet"}, "")) - pattern_WalletService_Exit_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "exit"}, "")) - pattern_WalletService_ExitBatch_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "exit-batch"}, "")) - pattern_WalletService_ExitStatus_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "exit-status"}, "")) - pattern_WalletService_ExitSummary_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "exit-summary"}, "")) - pattern_WalletService_SubscribeWallet_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "subscribe"}, "")) + pattern_WalletService_Create_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "create"}, "")) + pattern_WalletService_Unlock_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "unlock"}, "")) + pattern_WalletService_PrepareSend_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "prepare-send"}, "")) + pattern_WalletService_Send_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "send"}, "")) + pattern_WalletService_Recv_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "recv"}, "")) + pattern_WalletService_LookupRecv_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "lookup-recv"}, "")) + pattern_WalletService_RecvOnActiveChannel_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "recv-on-active-channel"}, "")) + pattern_WalletService_List_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "list"}, "")) + pattern_WalletService_Deposit_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "deposit"}, "")) + pattern_WalletService_Balance_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "balance"}, "")) + pattern_WalletService_Status_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "status"}, "")) + pattern_WalletService_Refresh_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "refresh"}, "")) + pattern_WalletService_GetExitPlan_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "exit-plan"}, "")) + pattern_WalletService_ExportExit_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "exit-export"}, "")) + pattern_WalletService_ExportExits_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "exits-export"}, "")) + pattern_WalletService_SweepWallet_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "sweep-wallet"}, "")) + pattern_WalletService_Exit_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "exit"}, "")) + pattern_WalletService_ExitBatch_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "exit-batch"}, "")) + pattern_WalletService_ExitStatus_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "exit-status"}, "")) + pattern_WalletService_ExitSummary_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "exit-summary"}, "")) + pattern_WalletService_SubscribeWallet_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "wallet", "subscribe"}, "")) ) var ( - forward_WalletService_Create_0 = runtime.ForwardResponseMessage - forward_WalletService_Unlock_0 = runtime.ForwardResponseMessage - forward_WalletService_PrepareSend_0 = runtime.ForwardResponseMessage - forward_WalletService_Send_0 = runtime.ForwardResponseMessage - forward_WalletService_Recv_0 = runtime.ForwardResponseMessage - forward_WalletService_LookupRecv_0 = runtime.ForwardResponseMessage - forward_WalletService_List_0 = runtime.ForwardResponseMessage - forward_WalletService_Deposit_0 = runtime.ForwardResponseMessage - forward_WalletService_Balance_0 = runtime.ForwardResponseMessage - forward_WalletService_Status_0 = runtime.ForwardResponseMessage - forward_WalletService_Refresh_0 = runtime.ForwardResponseMessage - forward_WalletService_GetExitPlan_0 = runtime.ForwardResponseMessage - forward_WalletService_ExportExit_0 = runtime.ForwardResponseMessage - forward_WalletService_ExportExits_0 = runtime.ForwardResponseMessage - forward_WalletService_SweepWallet_0 = runtime.ForwardResponseMessage - forward_WalletService_Exit_0 = runtime.ForwardResponseMessage - forward_WalletService_ExitBatch_0 = runtime.ForwardResponseMessage - forward_WalletService_ExitStatus_0 = runtime.ForwardResponseMessage - forward_WalletService_ExitSummary_0 = runtime.ForwardResponseMessage - forward_WalletService_SubscribeWallet_0 = runtime.ForwardResponseStream + forward_WalletService_Create_0 = runtime.ForwardResponseMessage + forward_WalletService_Unlock_0 = runtime.ForwardResponseMessage + forward_WalletService_PrepareSend_0 = runtime.ForwardResponseMessage + forward_WalletService_Send_0 = runtime.ForwardResponseMessage + forward_WalletService_Recv_0 = runtime.ForwardResponseMessage + forward_WalletService_LookupRecv_0 = runtime.ForwardResponseMessage + forward_WalletService_RecvOnActiveChannel_0 = runtime.ForwardResponseMessage + forward_WalletService_List_0 = runtime.ForwardResponseMessage + forward_WalletService_Deposit_0 = runtime.ForwardResponseMessage + forward_WalletService_Balance_0 = runtime.ForwardResponseMessage + forward_WalletService_Status_0 = runtime.ForwardResponseMessage + forward_WalletService_Refresh_0 = runtime.ForwardResponseMessage + forward_WalletService_GetExitPlan_0 = runtime.ForwardResponseMessage + forward_WalletService_ExportExit_0 = runtime.ForwardResponseMessage + forward_WalletService_ExportExits_0 = runtime.ForwardResponseMessage + forward_WalletService_SweepWallet_0 = runtime.ForwardResponseMessage + forward_WalletService_Exit_0 = runtime.ForwardResponseMessage + forward_WalletService_ExitBatch_0 = runtime.ForwardResponseMessage + forward_WalletService_ExitStatus_0 = runtime.ForwardResponseMessage + forward_WalletService_ExitSummary_0 = runtime.ForwardResponseMessage + forward_WalletService_SubscribeWallet_0 = runtime.ForwardResponseStream ) // RegisterWalletInspectionServiceHandlerFromEndpoint is same as RegisterWalletInspectionServiceHandler but diff --git a/rpc/wavewalletrpc/wallet_grpc.pb.go b/rpc/wavewalletrpc/wallet_grpc.pb.go index 2447a0a06..a77e9d221 100644 --- a/rpc/wavewalletrpc/wallet_grpc.pb.go +++ b/rpc/wavewalletrpc/wallet_grpc.pb.go @@ -19,26 +19,27 @@ import ( const _ = grpc.SupportPackageIsVersion9 const ( - WalletService_Create_FullMethodName = "/wavewalletrpc.WalletService/Create" - WalletService_Unlock_FullMethodName = "/wavewalletrpc.WalletService/Unlock" - WalletService_PrepareSend_FullMethodName = "/wavewalletrpc.WalletService/PrepareSend" - WalletService_Send_FullMethodName = "/wavewalletrpc.WalletService/Send" - WalletService_Recv_FullMethodName = "/wavewalletrpc.WalletService/Recv" - WalletService_LookupRecv_FullMethodName = "/wavewalletrpc.WalletService/LookupRecv" - WalletService_List_FullMethodName = "/wavewalletrpc.WalletService/List" - WalletService_Deposit_FullMethodName = "/wavewalletrpc.WalletService/Deposit" - WalletService_Balance_FullMethodName = "/wavewalletrpc.WalletService/Balance" - WalletService_Status_FullMethodName = "/wavewalletrpc.WalletService/Status" - WalletService_Refresh_FullMethodName = "/wavewalletrpc.WalletService/Refresh" - WalletService_GetExitPlan_FullMethodName = "/wavewalletrpc.WalletService/GetExitPlan" - WalletService_ExportExit_FullMethodName = "/wavewalletrpc.WalletService/ExportExit" - WalletService_ExportExits_FullMethodName = "/wavewalletrpc.WalletService/ExportExits" - WalletService_SweepWallet_FullMethodName = "/wavewalletrpc.WalletService/SweepWallet" - WalletService_Exit_FullMethodName = "/wavewalletrpc.WalletService/Exit" - WalletService_ExitBatch_FullMethodName = "/wavewalletrpc.WalletService/ExitBatch" - WalletService_ExitStatus_FullMethodName = "/wavewalletrpc.WalletService/ExitStatus" - WalletService_ExitSummary_FullMethodName = "/wavewalletrpc.WalletService/ExitSummary" - WalletService_SubscribeWallet_FullMethodName = "/wavewalletrpc.WalletService/SubscribeWallet" + WalletService_Create_FullMethodName = "/wavewalletrpc.WalletService/Create" + WalletService_Unlock_FullMethodName = "/wavewalletrpc.WalletService/Unlock" + WalletService_PrepareSend_FullMethodName = "/wavewalletrpc.WalletService/PrepareSend" + WalletService_Send_FullMethodName = "/wavewalletrpc.WalletService/Send" + WalletService_Recv_FullMethodName = "/wavewalletrpc.WalletService/Recv" + WalletService_LookupRecv_FullMethodName = "/wavewalletrpc.WalletService/LookupRecv" + WalletService_RecvOnActiveChannel_FullMethodName = "/wavewalletrpc.WalletService/RecvOnActiveChannel" + WalletService_List_FullMethodName = "/wavewalletrpc.WalletService/List" + WalletService_Deposit_FullMethodName = "/wavewalletrpc.WalletService/Deposit" + WalletService_Balance_FullMethodName = "/wavewalletrpc.WalletService/Balance" + WalletService_Status_FullMethodName = "/wavewalletrpc.WalletService/Status" + WalletService_Refresh_FullMethodName = "/wavewalletrpc.WalletService/Refresh" + WalletService_GetExitPlan_FullMethodName = "/wavewalletrpc.WalletService/GetExitPlan" + WalletService_ExportExit_FullMethodName = "/wavewalletrpc.WalletService/ExportExit" + WalletService_ExportExits_FullMethodName = "/wavewalletrpc.WalletService/ExportExits" + WalletService_SweepWallet_FullMethodName = "/wavewalletrpc.WalletService/SweepWallet" + WalletService_Exit_FullMethodName = "/wavewalletrpc.WalletService/Exit" + WalletService_ExitBatch_FullMethodName = "/wavewalletrpc.WalletService/ExitBatch" + WalletService_ExitStatus_FullMethodName = "/wavewalletrpc.WalletService/ExitStatus" + WalletService_ExitSummary_FullMethodName = "/wavewalletrpc.WalletService/ExitSummary" + WalletService_SubscribeWallet_FullMethodName = "/wavewalletrpc.WalletService/SubscribeWallet" ) // WalletServiceClient is the client API for WalletService service. @@ -89,6 +90,9 @@ type WalletServiceClient interface { // also reads as NotFound, and a Recv retried under its ID may fail, so // start any new receive under a fresh request_id. LookupRecv(ctx context.Context, in *LookupRecvRequest, opts ...grpc.CallOption) (*RecvResponse, error) + // RecvOnActiveChannel requires an existing Ark channel with inbound + // liquidity. Never creates a channel or falls back to a swap or credit. + RecvOnActiveChannel(ctx context.Context, in *RecvRequest, opts ...grpc.CallOption) (*RecvResponse, error) // List returns the unified wallet view selected by ListRequest.view: // ACTIVITY (default) is the merged WalletEntry stream; VTXOS is the // live VTXO inventory; ONCHAIN is the boarding-plus-sweep on-chain @@ -224,6 +228,16 @@ func (c *walletServiceClient) LookupRecv(ctx context.Context, in *LookupRecvRequ return out, nil } +func (c *walletServiceClient) RecvOnActiveChannel(ctx context.Context, in *RecvRequest, opts ...grpc.CallOption) (*RecvResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(RecvResponse) + err := c.cc.Invoke(ctx, WalletService_RecvOnActiveChannel_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *walletServiceClient) List(ctx context.Context, in *ListRequest, opts ...grpc.CallOption) (*ListResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(ListResponse) @@ -421,6 +435,9 @@ type WalletServiceServer interface { // also reads as NotFound, and a Recv retried under its ID may fail, so // start any new receive under a fresh request_id. LookupRecv(context.Context, *LookupRecvRequest) (*RecvResponse, error) + // RecvOnActiveChannel requires an existing Ark channel with inbound + // liquidity. Never creates a channel or falls back to a swap or credit. + RecvOnActiveChannel(context.Context, *RecvRequest) (*RecvResponse, error) // List returns the unified wallet view selected by ListRequest.view: // ACTIVITY (default) is the merged WalletEntry stream; VTXOS is the // live VTXO inventory; ONCHAIN is the boarding-plus-sweep on-chain @@ -514,6 +531,9 @@ func (UnimplementedWalletServiceServer) Recv(context.Context, *RecvRequest) (*Re func (UnimplementedWalletServiceServer) LookupRecv(context.Context, *LookupRecvRequest) (*RecvResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method LookupRecv not implemented") } +func (UnimplementedWalletServiceServer) RecvOnActiveChannel(context.Context, *RecvRequest) (*RecvResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method RecvOnActiveChannel not implemented") +} func (UnimplementedWalletServiceServer) List(context.Context, *ListRequest) (*ListResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method List not implemented") } @@ -685,6 +705,24 @@ func _WalletService_LookupRecv_Handler(srv interface{}, ctx context.Context, dec return interceptor(ctx, in, info, handler) } +func _WalletService_RecvOnActiveChannel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RecvRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WalletServiceServer).RecvOnActiveChannel(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WalletService_RecvOnActiveChannel_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WalletServiceServer).RecvOnActiveChannel(ctx, req.(*RecvRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _WalletService_List_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ListRequest) if err := dec(in); err != nil { @@ -961,6 +999,10 @@ var WalletService_ServiceDesc = grpc.ServiceDesc{ MethodName: "LookupRecv", Handler: _WalletService_LookupRecv_Handler, }, + { + MethodName: "RecvOnActiveChannel", + Handler: _WalletService_RecvOnActiveChannel_Handler, + }, { MethodName: "List", Handler: _WalletService_List_Handler, diff --git a/rpc/wavewalletrpc/wallet_mailboxrpc.pb.go b/rpc/wavewalletrpc/wallet_mailboxrpc.pb.go index f1347d177..d69e16725 100644 --- a/rpc/wavewalletrpc/wallet_mailboxrpc.pb.go +++ b/rpc/wavewalletrpc/wallet_mailboxrpc.pb.go @@ -36,6 +36,8 @@ type WalletServiceMailboxServer interface { Recv(ctx context.Context, req *RecvRequest) (*RecvResponse, error) // LookupRecv handles LookupRecv. LookupRecv(ctx context.Context, req *LookupRecvRequest) (*RecvResponse, error) + // RecvOnActiveChannel handles RecvOnActiveChannel. + RecvOnActiveChannel(ctx context.Context, req *RecvRequest) (*RecvResponse, error) // List handles List. List(ctx context.Context, req *ListRequest) (*ListResponse, error) // Deposit handles Deposit. @@ -128,6 +130,16 @@ func RegisterWalletServiceMailboxServer(r rpc.Router, impl WalletServiceMailboxS return impl.LookupRecv(ctx, req) }) + r.Handle("wavewalletrpc.WalletService", "RecvOnActiveChannel", func() proto.Message { + return &RecvRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*RecvRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.RecvOnActiveChannel(ctx, req) + }) r.Handle("wavewalletrpc.WalletService", "List", func() proto.Message { return &ListRequest{} }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { @@ -408,6 +420,29 @@ func (c *WalletServiceMailboxClient) LookupRecv(ctx context.Context, req *Lookup return resp, nil } +// RecvOnActiveChannel calls the RecvOnActiveChannel RPC. +func (c *WalletServiceMailboxClient) RecvOnActiveChannel(ctx context.Context, req *RecvRequest, opts ...rpc.RPCOptions) (*RecvResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "wavewalletrpc.WalletService", + Method: "RecvOnActiveChannel", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(RecvResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + // List calls the List RPC. func (c *WalletServiceMailboxClient) List(ctx context.Context, req *ListRequest, opts ...rpc.RPCOptions) (*ListResponse, error) { var opt rpc.RPCOptions diff --git a/sdk/swaps/sqlc/models.go b/sdk/swaps/sqlc/models.go index 5ba47891f..e7c51f149 100644 --- a/sdk/swaps/sqlc/models.go +++ b/sdk/swaps/sqlc/models.go @@ -84,4 +84,7 @@ type ReceiveSwap struct { DustLimitSat int64 RequestID sql.NullString Memo string + ReservedScid []byte + ChannelReceiveEnabled bool + ChannelID []byte } diff --git a/sdk/swaps/sqlc/swaps.sql.go b/sdk/swaps/sqlc/swaps.sql.go index b90c5c8ca..57a3a31e6 100644 --- a/sdk/swaps/sqlc/swaps.sql.go +++ b/sdk/swaps/sqlc/swaps.sql.go @@ -101,7 +101,7 @@ func (q *Queries) GetPaySwap(ctx context.Context, paymentHash []byte) (PaySwap, } const GetReceiveSwap = `-- name: GetReceiveSwap :one -SELECT payment_hash, amount_sat, payer_fee_msat, state, invoice, preimage, deadline_unix, client_pubkey, payment_addr, operator_pubkey, swap_server_pubkey, refund_locktime, unilateral_claim_delay, unilateral_refund_delay, unilateral_refund_without_receiver_delay, vhtlc_pkscript, vhtlc_policy_template, vhtlc_outpoint, vhtlc_amount, pending_htlc_ack_cursor, claim_receive_pubkey, claim_receive_pkscript, claim_session_id, claim_recovery_id, intervention_reason, created_at_unix, updated_at_unix, settlement_type, requested_amount_sat, available_credit_sat, attached_credit_sat, dust_limit_sat, request_id, memo FROM receive_swaps +SELECT payment_hash, amount_sat, payer_fee_msat, state, invoice, preimage, deadline_unix, client_pubkey, payment_addr, operator_pubkey, swap_server_pubkey, refund_locktime, unilateral_claim_delay, unilateral_refund_delay, unilateral_refund_without_receiver_delay, vhtlc_pkscript, vhtlc_policy_template, vhtlc_outpoint, vhtlc_amount, pending_htlc_ack_cursor, claim_receive_pubkey, claim_receive_pkscript, claim_session_id, claim_recovery_id, intervention_reason, created_at_unix, updated_at_unix, settlement_type, requested_amount_sat, available_credit_sat, attached_credit_sat, dust_limit_sat, request_id, memo, reserved_scid, channel_receive_enabled, channel_id FROM receive_swaps WHERE payment_hash = $1 LIMIT 1 ` @@ -144,12 +144,15 @@ func (q *Queries) GetReceiveSwap(ctx context.Context, paymentHash []byte) (Recei &i.DustLimitSat, &i.RequestID, &i.Memo, + &i.ReservedScid, + &i.ChannelReceiveEnabled, + &i.ChannelID, ) return i, err } const GetReceiveSwapByRequestID = `-- name: GetReceiveSwapByRequestID :one -SELECT payment_hash, amount_sat, payer_fee_msat, state, invoice, preimage, deadline_unix, client_pubkey, payment_addr, operator_pubkey, swap_server_pubkey, refund_locktime, unilateral_claim_delay, unilateral_refund_delay, unilateral_refund_without_receiver_delay, vhtlc_pkscript, vhtlc_policy_template, vhtlc_outpoint, vhtlc_amount, pending_htlc_ack_cursor, claim_receive_pubkey, claim_receive_pkscript, claim_session_id, claim_recovery_id, intervention_reason, created_at_unix, updated_at_unix, settlement_type, requested_amount_sat, available_credit_sat, attached_credit_sat, dust_limit_sat, request_id, memo FROM receive_swaps +SELECT payment_hash, amount_sat, payer_fee_msat, state, invoice, preimage, deadline_unix, client_pubkey, payment_addr, operator_pubkey, swap_server_pubkey, refund_locktime, unilateral_claim_delay, unilateral_refund_delay, unilateral_refund_without_receiver_delay, vhtlc_pkscript, vhtlc_policy_template, vhtlc_outpoint, vhtlc_amount, pending_htlc_ack_cursor, claim_receive_pubkey, claim_receive_pkscript, claim_session_id, claim_recovery_id, intervention_reason, created_at_unix, updated_at_unix, settlement_type, requested_amount_sat, available_credit_sat, attached_credit_sat, dust_limit_sat, request_id, memo, reserved_scid, channel_receive_enabled, channel_id FROM receive_swaps WHERE request_id = $1 LIMIT 1 ` @@ -194,6 +197,9 @@ func (q *Queries) GetReceiveSwapByRequestID(ctx context.Context, requestID sql.N &i.DustLimitSat, &i.RequestID, &i.Memo, + &i.ReservedScid, + &i.ChannelReceiveEnabled, + &i.ChannelID, ) return i, err } @@ -297,11 +303,12 @@ INSERT INTO receive_swaps ( pending_htlc_ack_cursor, claim_receive_pubkey, claim_receive_pkscript, claim_session_id, claim_recovery_id, intervention_reason, requested_amount_sat, available_credit_sat, attached_credit_sat, - dust_limit_sat, created_at_unix, updated_at_unix, request_id, memo + dust_limit_sat, reserved_scid, channel_receive_enabled, channel_id, + created_at_unix, updated_at_unix, request_id, memo ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, - $29, $30, $31, $32, $33, $34 + $29, $30, $31, $32, $33, $34, $35, $36, $37 ) ON CONFLICT (payment_hash) DO NOTHING ` @@ -337,6 +344,9 @@ type InsertReceiveSwapParams struct { AvailableCreditSat int64 AttachedCreditSat int64 DustLimitSat int64 + ReservedScid []byte + ChannelReceiveEnabled bool + ChannelID []byte CreatedAtUnix int64 UpdatedAtUnix int64 RequestID sql.NullString @@ -376,6 +386,9 @@ func (q *Queries) InsertReceiveSwap(ctx context.Context, arg InsertReceiveSwapPa arg.AvailableCreditSat, arg.AttachedCreditSat, arg.DustLimitSat, + arg.ReservedScid, + arg.ChannelReceiveEnabled, + arg.ChannelID, arg.CreatedAtUnix, arg.UpdatedAtUnix, arg.RequestID, @@ -507,7 +520,7 @@ func (q *Queries) ListPendingPaySwaps(ctx context.Context) ([]PaySwap, error) { } const ListPendingReceiveSwaps = `-- name: ListPendingReceiveSwaps :many -SELECT payment_hash, amount_sat, payer_fee_msat, state, invoice, preimage, deadline_unix, client_pubkey, payment_addr, operator_pubkey, swap_server_pubkey, refund_locktime, unilateral_claim_delay, unilateral_refund_delay, unilateral_refund_without_receiver_delay, vhtlc_pkscript, vhtlc_policy_template, vhtlc_outpoint, vhtlc_amount, pending_htlc_ack_cursor, claim_receive_pubkey, claim_receive_pkscript, claim_session_id, claim_recovery_id, intervention_reason, created_at_unix, updated_at_unix, settlement_type, requested_amount_sat, available_credit_sat, attached_credit_sat, dust_limit_sat, request_id, memo FROM receive_swaps +SELECT payment_hash, amount_sat, payer_fee_msat, state, invoice, preimage, deadline_unix, client_pubkey, payment_addr, operator_pubkey, swap_server_pubkey, refund_locktime, unilateral_claim_delay, unilateral_refund_delay, unilateral_refund_without_receiver_delay, vhtlc_pkscript, vhtlc_policy_template, vhtlc_outpoint, vhtlc_amount, pending_htlc_ack_cursor, claim_receive_pubkey, claim_receive_pkscript, claim_session_id, claim_recovery_id, intervention_reason, created_at_unix, updated_at_unix, settlement_type, requested_amount_sat, available_credit_sat, attached_credit_sat, dust_limit_sat, request_id, memo, reserved_scid, channel_receive_enabled, channel_id FROM receive_swaps WHERE state NOT IN ('Completed', 'Expired', 'NeedsIntervention', 'Failed') ORDER BY created_at_unix ASC ` @@ -556,6 +569,9 @@ func (q *Queries) ListPendingReceiveSwaps(ctx context.Context) ([]ReceiveSwap, e &i.DustLimitSat, &i.RequestID, &i.Memo, + &i.ReservedScid, + &i.ChannelReceiveEnabled, + &i.ChannelID, ); err != nil { return nil, err } @@ -571,7 +587,7 @@ func (q *Queries) ListPendingReceiveSwaps(ctx context.Context) ([]ReceiveSwap, e } const ListReceiveSwaps = `-- name: ListReceiveSwaps :many -SELECT payment_hash, amount_sat, payer_fee_msat, state, invoice, preimage, deadline_unix, client_pubkey, payment_addr, operator_pubkey, swap_server_pubkey, refund_locktime, unilateral_claim_delay, unilateral_refund_delay, unilateral_refund_without_receiver_delay, vhtlc_pkscript, vhtlc_policy_template, vhtlc_outpoint, vhtlc_amount, pending_htlc_ack_cursor, claim_receive_pubkey, claim_receive_pkscript, claim_session_id, claim_recovery_id, intervention_reason, created_at_unix, updated_at_unix, settlement_type, requested_amount_sat, available_credit_sat, attached_credit_sat, dust_limit_sat, request_id, memo FROM receive_swaps +SELECT payment_hash, amount_sat, payer_fee_msat, state, invoice, preimage, deadline_unix, client_pubkey, payment_addr, operator_pubkey, swap_server_pubkey, refund_locktime, unilateral_claim_delay, unilateral_refund_delay, unilateral_refund_without_receiver_delay, vhtlc_pkscript, vhtlc_policy_template, vhtlc_outpoint, vhtlc_amount, pending_htlc_ack_cursor, claim_receive_pubkey, claim_receive_pkscript, claim_session_id, claim_recovery_id, intervention_reason, created_at_unix, updated_at_unix, settlement_type, requested_amount_sat, available_credit_sat, attached_credit_sat, dust_limit_sat, request_id, memo, reserved_scid, channel_receive_enabled, channel_id FROM receive_swaps ORDER BY created_at_unix ASC ` @@ -619,6 +635,9 @@ func (q *Queries) ListReceiveSwaps(ctx context.Context) ([]ReceiveSwap, error) { &i.DustLimitSat, &i.RequestID, &i.Memo, + &i.ReservedScid, + &i.ChannelReceiveEnabled, + &i.ChannelID, ); err != nil { return nil, err } @@ -798,6 +817,9 @@ INSERT INTO receive_swaps ( available_credit_sat, attached_credit_sat, dust_limit_sat, + reserved_scid, + channel_receive_enabled, + channel_id, created_at_unix, updated_at_unix, request_id, @@ -805,7 +827,7 @@ INSERT INTO receive_swaps ( ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, - $29, $30, $31, $32, $33, $34 + $29, $30, $31, $32, $33, $34, $35, $36, $37 ) ON CONFLICT (payment_hash) DO UPDATE SET amount_sat = EXCLUDED.amount_sat, @@ -838,6 +860,9 @@ ON CONFLICT (payment_hash) DO UPDATE SET available_credit_sat = EXCLUDED.available_credit_sat, attached_credit_sat = EXCLUDED.attached_credit_sat, dust_limit_sat = EXCLUDED.dust_limit_sat, + reserved_scid = EXCLUDED.reserved_scid, + channel_receive_enabled = EXCLUDED.channel_receive_enabled, + channel_id = EXCLUDED.channel_id, updated_at_unix = EXCLUDED.updated_at_unix ` @@ -872,6 +897,9 @@ type UpsertReceiveSwapParams struct { AvailableCreditSat int64 AttachedCreditSat int64 DustLimitSat int64 + ReservedScid []byte + ChannelReceiveEnabled bool + ChannelID []byte CreatedAtUnix int64 UpdatedAtUnix int64 RequestID sql.NullString @@ -910,6 +938,9 @@ func (q *Queries) UpsertReceiveSwap(ctx context.Context, arg UpsertReceiveSwapPa arg.AvailableCreditSat, arg.AttachedCreditSat, arg.DustLimitSat, + arg.ReservedScid, + arg.ChannelReceiveEnabled, + arg.ChannelID, arg.CreatedAtUnix, arg.UpdatedAtUnix, arg.RequestID, diff --git a/swaprpc/swap.pb.go b/swaprpc/swap.pb.go index 4ba1a2b24..d119554ce 100644 --- a/swaprpc/swap.pb.go +++ b/swaprpc/swap.pb.go @@ -3774,7 +3774,7 @@ const file_swap_proto_rawDesc = "" + "\x16client_identity_pubkey\x18\x01 \x01(\fR\x14clientIdentityPubkey\x12%\n" + "\x0etimestamp_unix\x18\x02 \x01(\x03R\rtimestampUnix\x12\x14\n" + "\x05nonce\x18\x03 \x01(\fR\x05nonce\x12\x1c\n" + - "\tsignature\x18\x04 \x01(\fR\tsignature\"\xe5\x03\n" + + "\tsignature\x18\x04 \x01(\fR\tsignature\"\xfe\x03\n" + "\x17RequestChannelIdRequest\x12%\n" + "\x0eexpiry_seconds\x18\x01 \x01(\rR\rexpirySeconds\x12.\n" + "\x13client_vhtlc_pubkey\x18\x02 \x01(\fR\x11clientVhtlcPubkey\x12!\n" + @@ -3786,7 +3786,7 @@ const file_swap_proto_rawDesc = "" + "\vowner_proof\x18\a \x01(\v2\x17.swaprpc.SwapOwnerProofR\n" + "ownerProof\x128\n" + "\x18preimage_recovery_params\x18\b \x01(\fR\x16preimageRecoveryParams\x12.\n" + - "\x13invoice_routing_key\x18\t \x01(\fR\x11invoiceRoutingKey\"\xf5\x03\n" + + "\x13invoice_routing_key\x18\t \x01(\fR\x11invoiceRoutingKeyR\x17channel_backing_fee_sat\"\x8e\x04\n" + "\x18RequestChannelIdResponse\x12$\n" + "\x0epayer_fee_msat\x18\x02 \x01(\x04R\fpayerFeeMsat\x120\n" + "\x14requested_amount_sat\x18\x03 \x01(\x04R\x12requestedAmountSat\x120\n" + @@ -3797,7 +3797,7 @@ const file_swap_proto_rawDesc = "" + "\x0fsettlement_type\x18\b \x01(\x0e2\x17.swaprpc.SettlementTypeR\x0esettlementType\x12@\n" + "\x10route_hint_paths\x18\t \x03(\v2\x16.swaprpc.RouteHintPathR\x0erouteHintPaths\x124\n" + "\x16invoice_routing_pubkey\x18\n" + - " \x01(\fR\x14invoiceRoutingPubkeyJ\x04\b\x01\x10\x02R\x0froute_hint_path\"\xaf\x01\n" + + " \x01(\fR\x14invoiceRoutingPubkeyJ\x04\b\x01\x10\x02R\x0froute_hint_pathR\x17channel_backing_fee_sat\"\xaf\x01\n" + "\x1dAcknowledgeOutSwapHtlcRequest\x12!\n" + "\fpayment_hash\x18\x01 \x01(\fR\vpaymentHash\x12.\n" + "\x13client_vhtlc_pubkey\x18\x02 \x01(\fR\x11clientVhtlcPubkey\x12;\n" + diff --git a/waved/rpc_auth.go b/waved/rpc_auth.go index ddaad4bdf..11909dd58 100644 --- a/waved/rpc_auth.go +++ b/waved/rpc_auth.go @@ -209,8 +209,9 @@ func newWavedRPCPermissions() map[string][]bakery.Op { grant(wavewalletdk, entityActivity, "read", "List", ) - grant(wavewalletdk, entityAddress, "write", - "Recv", + grant( + wavewalletdk, entityAddress, "write", "Recv", + "RecvOnActiveChannel", ) grant(wavewalletdk, entityAddress, "read", "LookupRecv", diff --git a/waved/rpc_auth_test.go b/waved/rpc_auth_test.go index 6edd3f2cc..287ec21a8 100644 --- a/waved/rpc_auth_test.go +++ b/waved/rpc_auth_test.go @@ -62,6 +62,7 @@ func TestWavedRPCPermissionsMapsMutatingMethods(t *testing.T) { waverpc.DaemonService_RefreshVTXOs_FullMethodName, waverpc.DaemonService_SignReceiveAuthMessage_FullMethodName, waverpc.DaemonService_SignOutSwapHtlcAck_FullMethodName, + wavewalletrpc.WalletService_RecvOnActiveChannel_FullMethodName, fullArkChannelMethod("PromoteVTXO"), fullArkChannelMethod("PayLightningInvoice"), fullArkChannelMethod("MaterializeAndForceClose"), From 27ad6f022088c0917f9e52097dc0717187743050 Mon Sep 17 00:00:00 2001 From: sputn1ck Date: Tue, 24 Nov 2026 17:45:18 +0100 Subject: [PATCH 3/5] sdk/swaps: Gate channel invoices and recover existing settlements Persist the channel chosen for a receive so recovery cannot switch rails after restart. Separate permission for new invoices from the bridge that must finish an existing payment. --- sdk/swaps/AGENTS.md | 47 ++- sdk/swaps/CLAUDE.md | 47 ++- sdk/swaps/client.go | 64 +++- sdk/swaps/in_swap_quote.go | 12 + sdk/swaps/in_swap_test.go | 36 ++ sdk/swaps/out_swap.go | 564 +++++++++++++++++++++++++----- sdk/swaps/out_swap_fsm.go | 22 ++ sdk/swaps/out_swap_test.go | 408 ++++++++++++++++++++- sdk/swaps/store_admission_test.go | 46 +++ sdk/swaps/store_sessions.go | 93 +++-- sdk/swaps/store_test.go | 78 +++++ 11 files changed, 1276 insertions(+), 141 deletions(-) diff --git a/sdk/swaps/AGENTS.md b/sdk/swaps/AGENTS.md index 23a2b5b12..ea3ad1139 100644 --- a/sdk/swaps/AGENTS.md +++ b/sdk/swaps/AGENTS.md @@ -8,6 +8,8 @@ FSM-driven flows using the Loop FSM engine, coordinating with a remote swap server and the local Ark daemon to fund, claim, or refund on-chain vHTLCs. With `NewSwapClientWithStore`, persists every state transition in an isolated SQLite database; `NewSwapClient` retains state in memory. +`StartReceiveViaArkChannel` issues a separate invoice for settlement on an +existing active channel. `StartReceiveViaLightning` uses ordinary swap settlement. Also handles same-Ark (in-Ark) vHTLC settlement where sender and receiver settle a vHTLC inside the same Ark instance without bridging through Lightning. @@ -19,7 +21,9 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap - `SwapClient` — top-level entry point. Constructed via `NewSwapClient` (no persistence) or `NewSwapClientWithStore` (SQLite-backed). Holds an `OutSwapEventReceiver` overridable via - `SetOutSwapEventReceiver`. + `SetOutSwapEventReceiver` and an optional daemon-owned + `ArkChannelPaymentBridge` installed via + `SetArkChannelPaymentBridge`. - `PaySession` — Ark-to-Lightning pay FSM: `Created → SwapCreated → FundingInitiated → VHTLCFunded → WaitingForClaim → Completed` (or `Expired` / `RefundInitiated → @@ -30,6 +34,9 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap `Failed`). `HTLCEventAccepted` becomes authoritative after the configured persistence step succeeds. With a store it is a crash-durable checkpoint, so funding detection resumes without re-driving mailbox delivery. + A channel-enabled receive may + instead move directly from `InvoiceCreated` to `Completed` after an active + channel is recorded and its private hold invoice is settled. - `MailboxOutSwapEventReceiver` — mailbox-backed receiver. Pulls out-swap HTLC events from a `mailbox/pb` edge keyed by a per-session mailbox ID derived from the client identity key and payment hash. @@ -56,9 +63,15 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap - `IncomingVHTLCEventReceiver` — interface for receivers that handle both Lightning-backed and same-Ark vHTLC events; implemented by `MailboxOutSwapEventReceiver`. -- `SettlementType` — `SettlementTypeLightning`, `SettlementTypeInArk` - (returned in `InSwapConfig` identifying how the server bridges - payment). +- `SettlementType` — Identifies the selected rail: + `SettlementTypeLightning`, `SettlementTypeInArk`, + `SettlementTypeCredit`, `SettlementTypeMixed`, and + `SettlementTypeArkChannel`. The Ark-channel value is a receive outcome; pay + quote validation rejects it. +- `ArkChannelPaymentBridge` — Narrow daemon-owned boundary with prepare, + register, wait, settle, and cancel operations for an incoming payment. The + SDK owns receive orchestration and persistence, while the daemon and lnd own + the native invoice and preimage release on the registered channel. - `Store` — isolated SQLite persistence. Runs its own migration table (`swap_client_schema_migrations`) separate from the main daemon DB. - `SwapServerConn` / `GRPCSwapServerConn` — remote swap-server gRPC @@ -84,7 +97,12 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap - `PayState` / `ReceiveState` — typed FSM enums with `IsTerminal()` / `String()`. `ReceiveState` includes `ReceiveStateHTLCEventAccepted`. - `VHTLCConfig`, `InSwapConfig`, `RouteHint` — server-negotiation - DTOs. `SwapSummary` — flat list view for persisted sessions. + DTOs. `SwapSummary` — flat list view for persisted sessions; receive rows + include `ChannelID` for the existing channel and `ReservedSCID` for the + virtual SCID advertised in the invoice. +- `ReceiveResult` — Successful receive result. Channel settlements return a + nonzero `ChannelID` and `SettlementTypeArkChannel`; vHTLC settlements return + their claimed `VTXOOutpoint` instead. - `RecoveryPolicy` / `DefaultRecoveryPolicy` — governs auto-escalation from cooperative vHTLC retry to daemon-owned on-chain recovery (arm/escalate/cancel via `DaemonConn`'s VHTLC recovery RPCs). Also @@ -119,6 +137,7 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap - **Depends on**: `lib/arkscript` (vHTLC policy + claim/refund tapscript paths, plus the shared `VHTLCTiming` admission model), + `arkchannel` (channel identifiers returned by the payment bridge), `sdk/ark` (type aliases), `swaprpc` (gRPC stubs), `vtxo` (forfeit sign-request conversion), `mailbox/pb` (edge pull/ack), `serverconn` + `serverconn/mailboxpull` (`CompoundMailboxID`, @@ -143,6 +162,11 @@ same-Ark vHTLC event: if `outEvents` implements otherwise the flow falls back to `WaitOutSwapHtlc` and converts the result into an `IncomingVHTLCNotification`. +Explicit channel receive installs a private hold invoice and registers its hash, +amount, and virtual SCID with the hub before it publishes the invoice. The hub +must return an active channel ID. The SDK waits for acceptance on that exact +channel; it never starts a vHTLC listener for the same invoice. + ## Invariants - `mutateAndPersist` is the only way to change session state — it @@ -215,6 +239,19 @@ result into an `IncomingVHTLCNotification`. store. - `ReceiveAuthKey` signing/ECDH is always delegated to the daemon; the SDK never holds the raw private key for receive-auth. +- Keep the payment bridge installed to recover existing invoices. Only + explicit channel receives need admission; ordinary receives never use it. + Channel registration must succeed before the caller receives the invoice. + Expiry or cancellation releases the registration and the private hold invoice. +- The channel ID is persisted at registration. After lnd accepts the HTLC + on that channel, the SDK records `SettlementTypeArkChannel` before + releasing the preimage. A restart retries that settlement decision. +- Receive rows encode `reserved_scid` as 8-byte big-endian data and + `channel_id` as 32 bytes; empty values mean unset. Row restoration rejects + any other width. Migration 5 also stores + `channel_receive_enabled` so ownership survives restart. +- `SettlementTypeArkChannel` is receive-only. `validateInSwapPreview` and + `validateInSwapQuote` reject it for Ark-to-Lightning pay quotes. - Error sentinels (`ErrSwapExpired`, `ErrSwapRefunded`, `ErrSwapSummaryNotFound`) are exported; callers use `errors.Is`. - The credit ledger is server-authoritative; local state only records diff --git a/sdk/swaps/CLAUDE.md b/sdk/swaps/CLAUDE.md index 23a2b5b12..ea3ad1139 100644 --- a/sdk/swaps/CLAUDE.md +++ b/sdk/swaps/CLAUDE.md @@ -8,6 +8,8 @@ FSM-driven flows using the Loop FSM engine, coordinating with a remote swap server and the local Ark daemon to fund, claim, or refund on-chain vHTLCs. With `NewSwapClientWithStore`, persists every state transition in an isolated SQLite database; `NewSwapClient` retains state in memory. +`StartReceiveViaArkChannel` issues a separate invoice for settlement on an +existing active channel. `StartReceiveViaLightning` uses ordinary swap settlement. Also handles same-Ark (in-Ark) vHTLC settlement where sender and receiver settle a vHTLC inside the same Ark instance without bridging through Lightning. @@ -19,7 +21,9 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap - `SwapClient` — top-level entry point. Constructed via `NewSwapClient` (no persistence) or `NewSwapClientWithStore` (SQLite-backed). Holds an `OutSwapEventReceiver` overridable via - `SetOutSwapEventReceiver`. + `SetOutSwapEventReceiver` and an optional daemon-owned + `ArkChannelPaymentBridge` installed via + `SetArkChannelPaymentBridge`. - `PaySession` — Ark-to-Lightning pay FSM: `Created → SwapCreated → FundingInitiated → VHTLCFunded → WaitingForClaim → Completed` (or `Expired` / `RefundInitiated → @@ -30,6 +34,9 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap `Failed`). `HTLCEventAccepted` becomes authoritative after the configured persistence step succeeds. With a store it is a crash-durable checkpoint, so funding detection resumes without re-driving mailbox delivery. + A channel-enabled receive may + instead move directly from `InvoiceCreated` to `Completed` after an active + channel is recorded and its private hold invoice is settled. - `MailboxOutSwapEventReceiver` — mailbox-backed receiver. Pulls out-swap HTLC events from a `mailbox/pb` edge keyed by a per-session mailbox ID derived from the client identity key and payment hash. @@ -56,9 +63,15 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap - `IncomingVHTLCEventReceiver` — interface for receivers that handle both Lightning-backed and same-Ark vHTLC events; implemented by `MailboxOutSwapEventReceiver`. -- `SettlementType` — `SettlementTypeLightning`, `SettlementTypeInArk` - (returned in `InSwapConfig` identifying how the server bridges - payment). +- `SettlementType` — Identifies the selected rail: + `SettlementTypeLightning`, `SettlementTypeInArk`, + `SettlementTypeCredit`, `SettlementTypeMixed`, and + `SettlementTypeArkChannel`. The Ark-channel value is a receive outcome; pay + quote validation rejects it. +- `ArkChannelPaymentBridge` — Narrow daemon-owned boundary with prepare, + register, wait, settle, and cancel operations for an incoming payment. The + SDK owns receive orchestration and persistence, while the daemon and lnd own + the native invoice and preimage release on the registered channel. - `Store` — isolated SQLite persistence. Runs its own migration table (`swap_client_schema_migrations`) separate from the main daemon DB. - `SwapServerConn` / `GRPCSwapServerConn` — remote swap-server gRPC @@ -84,7 +97,12 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap - `PayState` / `ReceiveState` — typed FSM enums with `IsTerminal()` / `String()`. `ReceiveState` includes `ReceiveStateHTLCEventAccepted`. - `VHTLCConfig`, `InSwapConfig`, `RouteHint` — server-negotiation - DTOs. `SwapSummary` — flat list view for persisted sessions. + DTOs. `SwapSummary` — flat list view for persisted sessions; receive rows + include `ChannelID` for the existing channel and `ReservedSCID` for the + virtual SCID advertised in the invoice. +- `ReceiveResult` — Successful receive result. Channel settlements return a + nonzero `ChannelID` and `SettlementTypeArkChannel`; vHTLC settlements return + their claimed `VTXOOutpoint` instead. - `RecoveryPolicy` / `DefaultRecoveryPolicy` — governs auto-escalation from cooperative vHTLC retry to daemon-owned on-chain recovery (arm/escalate/cancel via `DaemonConn`'s VHTLC recovery RPCs). Also @@ -119,6 +137,7 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/sdk/swap - **Depends on**: `lib/arkscript` (vHTLC policy + claim/refund tapscript paths, plus the shared `VHTLCTiming` admission model), + `arkchannel` (channel identifiers returned by the payment bridge), `sdk/ark` (type aliases), `swaprpc` (gRPC stubs), `vtxo` (forfeit sign-request conversion), `mailbox/pb` (edge pull/ack), `serverconn` + `serverconn/mailboxpull` (`CompoundMailboxID`, @@ -143,6 +162,11 @@ same-Ark vHTLC event: if `outEvents` implements otherwise the flow falls back to `WaitOutSwapHtlc` and converts the result into an `IncomingVHTLCNotification`. +Explicit channel receive installs a private hold invoice and registers its hash, +amount, and virtual SCID with the hub before it publishes the invoice. The hub +must return an active channel ID. The SDK waits for acceptance on that exact +channel; it never starts a vHTLC listener for the same invoice. + ## Invariants - `mutateAndPersist` is the only way to change session state — it @@ -215,6 +239,19 @@ result into an `IncomingVHTLCNotification`. store. - `ReceiveAuthKey` signing/ECDH is always delegated to the daemon; the SDK never holds the raw private key for receive-auth. +- Keep the payment bridge installed to recover existing invoices. Only + explicit channel receives need admission; ordinary receives never use it. + Channel registration must succeed before the caller receives the invoice. + Expiry or cancellation releases the registration and the private hold invoice. +- The channel ID is persisted at registration. After lnd accepts the HTLC + on that channel, the SDK records `SettlementTypeArkChannel` before + releasing the preimage. A restart retries that settlement decision. +- Receive rows encode `reserved_scid` as 8-byte big-endian data and + `channel_id` as 32 bytes; empty values mean unset. Row restoration rejects + any other width. Migration 5 also stores + `channel_receive_enabled` so ownership survives restart. +- `SettlementTypeArkChannel` is receive-only. `validateInSwapPreview` and + `validateInSwapQuote` reject it for Ark-to-Lightning pay quotes. - Error sentinels (`ErrSwapExpired`, `ErrSwapRefunded`, `ErrSwapSummaryNotFound`) are exported; callers use `errors.Is`. - The credit ledger is server-authoritative; local state only records diff --git a/sdk/swaps/client.go b/sdk/swaps/client.go index 97daba6dd..7a38a759d 100644 --- a/sdk/swaps/client.go +++ b/sdk/swaps/client.go @@ -10,6 +10,7 @@ import ( "github.com/btcsuite/btcd/btcutil/v2" "github.com/btcsuite/btcd/chaincfg/v2" "github.com/btcsuite/btclog/v2" + "github.com/lightninglabs/wavelength/arkchannel" sdkark "github.com/lightninglabs/wavelength/sdk/ark" "github.com/lightninglabs/wavelength/swaprpc" "github.com/lightninglabs/wavelength/waverpc" @@ -52,6 +53,10 @@ const ( // SettlementTypeMixed means the invoice is funded by both a vHTLC and // a reserved credit balance. SettlementTypeMixed SettlementType = "mixed" + + // SettlementTypeArkChannel means the receive settled directly into an + // active Ark-backed native Lightning channel. + SettlementTypeArkChannel SettlementType = "ark_channel" ) // CreditQuote describes how a pay quote uses wallet credits. @@ -224,6 +229,12 @@ type SwapSummary struct { // or as a same-Ark payment when that detail is durably known. SettlementType SettlementType + // ChannelID identifies the existing channel reserved for this invoice. + ChannelID [32]byte + + // ReservedSCID is the virtual route advertised by the receive invoice. + ReservedSCID uint64 + // CreditQuote records the credit component of a pay quote when the // server selected a credit or mixed rail. CreditQuote *CreditQuote @@ -286,8 +297,15 @@ type ReceiveResult struct { // "txid:vout" format. VTXOOutpoint string - // AmountSat is the value of the claimed VTXO in satoshis. + // AmountSat is the amount received into the wallet or active channel. AmountSat int64 + + // ChannelID identifies the existing channel used for direct settlement. + ChannelID [32]byte + + // SettlementType reports whether the result used a channel or ordinary + // vHTLC claim. + SettlementType SettlementType } // ReceiveVHTLCInfo holds the script details for one prepared @@ -765,6 +783,27 @@ type OORSessionWaiter interface { wait time.Duration) (*waverpc.OORSessionInfo, bool, error) } +// ArkChannelPaymentBridge is the narrow daemon-owned channel boundary used by +// the swap SDK. lnd remains authoritative for invoices and payments. +type ArkChannelPaymentBridge interface { + PrepareIncomingPayment(context.Context, lntypes.Preimage, + btcutil.Amount) error + + // RegisterIncomingPayment reserves an active channel and returns its ID + // and the minimum CLTV delta for the public invoice's final hop. + RegisterIncomingPayment(context.Context, lntypes.Hash, btcutil.Amount, + uint64) (arkchannel.ID, uint32, error) + + // WaitIncomingPayment identifies the native channel that accepted the + // HTLC. + WaitIncomingPayment(context.Context, + lntypes.Hash) (arkchannel.ID, error) + + SettleIncomingPayment(context.Context, lntypes.Preimage) error + + CancelIncomingPayment(context.Context, lntypes.Hash, string) error +} + // DaemonConn abstracts the connection to the client's own daemon for wallet // operations such as OOR sends and indexed VTXO lookups. // @@ -945,12 +984,14 @@ type SwapClient struct { // their own cancellation deadlines rather than wait on a mutex. restoreGate chan struct{} - server SwapServerConn - daemon DaemonConn - invoiceGen InvoiceCreator - outEvents OutSwapEventReceiver - store *Store - log btclog.Logger + server SwapServerConn + daemon DaemonConn + invoiceGen InvoiceCreator + outEvents OutSwapEventReceiver + store *Store + log btclog.Logger + channelBridge ArkChannelPaymentBridge + channelAdmission bool waitPollInterval time.Duration overdueReceivePollWindow time.Duration @@ -966,6 +1007,15 @@ type SwapClient struct { now func() time.Time } +// SetArkChannelPaymentBridge wires recovery independently of whether this +// process may admit new channel invoices. +func (c *SwapClient) SetArkChannelPaymentBridge(bridge ArkChannelPaymentBridge, + admit bool) { + + c.channelBridge = bridge + c.channelAdmission = admit +} + // SetOutSwapEventReceiver sets the mailbox event receiver used by // ReceiveViaLightning. Callers should configure this before starting receives. func (c *SwapClient) SetOutSwapEventReceiver(receiver OutSwapEventReceiver) { diff --git a/sdk/swaps/in_swap_quote.go b/sdk/swaps/in_swap_quote.go index 50256096b..d06b670de 100644 --- a/sdk/swaps/in_swap_quote.go +++ b/sdk/swaps/in_swap_quote.go @@ -202,6 +202,10 @@ func validateInSwapPreview(invoice string, quote *InSwapQuote, } switch quote.SettlementType { case "", SettlementTypeLightning, SettlementTypeInArk: + case SettlementTypeArkChannel: + return fmt.Errorf("ark channel settlement is not valid for " + + "pay quotes") + case SettlementTypeCredit: expectedAmountSat = 0 @@ -277,6 +281,10 @@ func validateInSwapQuote(invoice string, maxFeeSat, maxCreditSat uint64, } switch cfg.SettlementType { case "", SettlementTypeLightning, SettlementTypeInArk: + case SettlementTypeArkChannel: + return fmt.Errorf("ark channel settlement is not valid for " + + "pay quotes") + case SettlementTypeCredit: if cfg.Preimage == nil { return fmt.Errorf("credit in-swap config missing " + @@ -341,6 +349,10 @@ func validatePayCredit(settlement SettlementType, quote *CreditQuote, } required := applied + shortfall switch settlement { + case SettlementTypeArkChannel: + return fmt.Errorf("ark channel settlement is not valid for " + + "pay quotes") + case SettlementTypeCredit: if maxCreditSat == 0 || required < totalSat || (!completed && required != totalSat) || diff --git a/sdk/swaps/in_swap_test.go b/sdk/swaps/in_swap_test.go index fc1debd69..94e414538 100644 --- a/sdk/swaps/in_swap_test.go +++ b/sdk/swaps/in_swap_test.go @@ -386,6 +386,42 @@ func TestValidateInSwapPreviewAllowsCreditOnlyZeroAmount(t *testing.T) { require.NoError(t, err) } +// TestInSwapValidationRejectsArkChannelSettlement verifies the receive-only +// settlement result cannot be supplied as a pay-side quote. +func TestInSwapValidationRejectsArkChannelSettlement(t *testing.T) { + t.Parallel() + + serverPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + preimage, err := NewPreimage() + require.NoError(t, err) + invoice := testValidPayInvoice(t, preimage) + + quote := &InSwapQuote{ + PaymentHash: preimage.Hash(), + InvoiceAmountSat: testInSwapInvoiceSat, + AmountSat: testInSwapAmountSat, + FeeSat: testInSwapFeeSat, + Expiry: time.Now().Add(time.Minute), + SettlementType: SettlementTypeArkChannel, + } + err = validateInSwapPreview( + invoice, quote, 0, &chaincfg.RegressionNetParams, + ) + require.ErrorContains(t, err, "unknown in-swap settlement type") + + cfg := testInSwapConfig( + serverPriv.PubKey(), preimage, time.Now().Add(time.Minute), + ) + cfg.SettlementType = SettlementTypeArkChannel + err = validateInSwapQuote( + invoice, testInSwapFeeSat, 0, cfg, + &chaincfg.RegressionNetParams, + ) + require.ErrorContains(t, err, "unknown in-swap settlement type") +} + // TestValidateInSwapQuoteRejectsServerMismatches verifies the client treats // the swap server response as a quote that must match the caller's invoice. func TestValidateInSwapQuoteRejectsServerMismatches(t *testing.T) { diff --git a/sdk/swaps/out_swap.go b/sdk/swaps/out_swap.go index d652c6829..6d25bbdfa 100644 --- a/sdk/swaps/out_swap.go +++ b/sdk/swaps/out_swap.go @@ -15,6 +15,7 @@ import ( "github.com/btcsuite/btcd/txscript/v2" "github.com/btcsuite/btclog/v2" loopfsm "github.com/lightninglabs/loop/fsm" + "github.com/lightninglabs/wavelength/arkchannel" "github.com/lightninglabs/wavelength/lib/arkscript" "github.com/lightninglabs/wavelength/swaprpc" "github.com/lightninglabs/wavelength/waverpc" @@ -66,6 +67,18 @@ const ( // negotiated refund locktime so the client does not start or continue a // swap when the refund path is already imminent. defaultRefundLocktimeBuffer = uint32(1) + + // defaultArkChannelReceiveSetupTimeout bounds active-channel + // registration. + defaultArkChannelReceiveSetupTimeout = 5 * time.Second + + // defaultArkChannelReceiveResolutionTimeout bounds detached settlement + // or cancellation after the caller's request context has ended. + defaultArkChannelReceiveResolutionTimeout = 30 * time.Second + + arkChannelReceiveSetupFailureReason = "Ark channel receive setup failed" + arkChannelReceiveExpiryReason = "receive invoice expired" + arkChannelReceiveTerminalReason = "receive swap terminated" ) type outSwapOnionDecoder func(ReceiveAuthKey, lntypes.Hash, @@ -218,6 +231,7 @@ var receiveTransitions = map[ReceiveState]map[receiveEvent]ReceiveState{ }, ReceiveStateInvoiceCreated: { receiveEventHTLCEventAccepted: ReceiveStateHTLCEventAccepted, + receiveEventCompleted: ReceiveStateCompleted, receiveEventExpired: ReceiveStateExpired, receiveEventNeedsIntervention: ReceiveStateNeedsIntervention, receiveEventFailed: ReceiveStateFailed, @@ -257,22 +271,26 @@ type ReceiveSession struct { // PaymentHash is the Lightning payment hash for this receive flow. PaymentHash lntypes.Hash - client *SwapClient - amountSat btcutil.Amount - memo string - requestID string - payerFeeMsat uint64 - requestedAmountSat uint64 - availableCreditSat uint64 - attachedCreditSat uint64 - expectedVHTLCSat uint64 - dustLimitSat uint64 - state ReceiveState - deadline time.Time - createdAt time.Time - updatedAt time.Time - clientPubKey *btcec.PublicKey - operatorPubKey *btcec.PublicKey + client *SwapClient + amountSat btcutil.Amount + memo string + requestID string + payerFeeMsat uint64 + requestedAmountSat uint64 + availableCreditSat uint64 + attachedCreditSat uint64 + expectedVHTLCSat uint64 + dustLimitSat uint64 + reservedSCID uint64 + requestActiveChannel bool // Only used before durable admission. + channelReceiveEnabled bool + channelID [32]byte + state ReceiveState + deadline time.Time + createdAt time.Time + updatedAt time.Time + clientPubKey *btcec.PublicKey + operatorPubKey *btcec.PublicKey // swapServerPubKey is the remote sender in the accepted vHTLC policy. // For Lightning-backed receives this is the swap server key; for // direct same-Ark receives this is the paying client's sender key. @@ -359,6 +377,11 @@ func (s *ReceiveSession) failTerminal(ctx context.Context, reason string, if s == nil { return newFailureError(reason, cause) } + if err := s.cancelPendingArkChannelReceive( + ctx, arkChannelReceiveTerminalReason, + ); err != nil { + return newRetryableActionError(errors.Join(cause, err)) + } s.client.log.WarnS(ctx, "Receive swap failed", cause, @@ -373,6 +396,7 @@ func (s *ReceiveSession) failTerminal(ctx context.Context, reason string, mutate() } + s.channelReceiveEnabled = false s.interventionReason = reason if s.state == ReceiveStateFailed { return nil @@ -421,6 +445,27 @@ func (c *SwapClient) StartReceiveWithRequestID(ctx context.Context, requestID string, amountSat btcutil.Amount, memo string) ( *ReceiveSession, error) { + return c.startReceive(ctx, amountSat, false, memo, requestID) +} + +// StartReceiveViaArkChannel creates an invoice payable only through an already +// active channel. Failure does not publish an invoice for another rail. +func (c *SwapClient) StartReceiveViaArkChannel(ctx context.Context, + amountSat btcutil.Amount, memo ...string) (*ReceiveSession, error) { + + if !c.channelAdmission || c.channelBridge == nil { + return nil, fmt.Errorf("active-channel receive is not enabled") + } + + return c.startReceive( + ctx, amountSat, true, receiveInvoiceMemo(memo), "", + ) +} + +// startReceive fixes the rail before allocating the invoice hash. +func (c *SwapClient) startReceive(ctx context.Context, amountSat btcutil.Amount, + activeChannel bool, memo, requestID string) (*ReceiveSession, error) { + if err := validateSatoshiAmount( amountSat, "receive amount", ); err != nil { @@ -428,18 +473,29 @@ func (c *SwapClient) StartReceiveWithRequestID(ctx context.Context, } session := &ReceiveSession{ - client: c, - amountSat: amountSat, - memo: memo, - requestID: requestID, - state: ReceiveStateCreated, - forfeitBindingGate: newReceiveForfeitBindingGate(), + client: c, + amountSat: amountSat, + memo: memo, + requestID: requestID, + requestActiveChannel: activeChannel, + state: ReceiveStateCreated, + forfeitBindingGate: newReceiveForfeitBindingGate(), } if err := session.runUntil( ctx, ReceiveStateInvoiceCreated, ); err != nil { - return c.resumeReceiveAdmission(ctx, err) + + existing, err := c.resumeReceiveAdmission(ctx, err) + if err != nil { + return nil, err + } + if activeChannel != existing.usesArkChannel() { + return nil, fmt.Errorf("existing receive uses a " + + "different rail") + } + + return existing, nil } return session, nil @@ -454,8 +510,12 @@ func receiveInvoiceMemo(memo []string) string { return memo[0] } -// Wait blocks until the swap server funds the expected vHTLC, then claims it -// into the client's wallet. +// usesArkChannel reports whether admission selected the channel rail. +func (s *ReceiveSession) usesArkChannel() bool { + return s.channelReceiveEnabled || s.channelID != (arkchannel.ID{}) +} + +// Wait blocks until the receive settles on the rail selected at admission. func (s *ReceiveSession) Wait(ctx context.Context) (*ReceiveResult, error) { if s == nil || s.client == nil { return nil, fmt.Errorf("receive session must be provided") @@ -465,12 +525,19 @@ func (s *ReceiveSession) Wait(ctx context.Context) (*ReceiveResult, error) { return nil, err } + amount := s.vhtlcAmount + if s.settlementType == SettlementTypeArkChannel { + amount = int64(s.amountSat) + } + return &ReceiveResult{ - Invoice: s.Invoice, - Preimage: s.Preimage, - PaymentHash: s.PaymentHash, - VTXOOutpoint: s.vhtlcOutpoint, - AmountSat: s.vhtlcAmount, + Invoice: s.Invoice, + Preimage: s.Preimage, + PaymentHash: s.PaymentHash, + VTXOOutpoint: s.vhtlcOutpoint, + AmountSat: amount, + ChannelID: s.channelID, + SettlementType: s.settlementType, }, nil } @@ -483,6 +550,10 @@ func (s *ReceiveSession) WaitForFunding(ctx context.Context) (string, int64, return "", 0, fmt.Errorf("receive session must be provided") } + if s.usesArkChannel() { + return "", 0, fmt.Errorf("channel invoice has no vHTLC funding") + } + if err := s.runUntil(ctx, ReceiveStateVHTLCFunded); err != nil { return "", 0, err } @@ -499,6 +570,10 @@ func (s *ReceiveSession) Claim(ctx context.Context, outpoint string, return nil, fmt.Errorf("receive session must be provided") } + if s.usesArkChannel() { + return nil, fmt.Errorf("channel invoice cannot be claimed as " + + "a vHTLC") + } if s.state == ReceiveStateInvoiceCreated { return nil, fmt.Errorf("cannot claim receive session before " + "out-swap HTLC event is accepted") @@ -556,11 +631,13 @@ func (s *ReceiveSession) Claim(ctx context.Context, outpoint string, } return &ReceiveResult{ - Invoice: s.Invoice, - Preimage: s.Preimage, - PaymentHash: s.PaymentHash, - VTXOOutpoint: s.vhtlcOutpoint, - AmountSat: s.vhtlcAmount, + Invoice: s.Invoice, + Preimage: s.Preimage, + PaymentHash: s.PaymentHash, + VTXOOutpoint: s.vhtlcOutpoint, + AmountSat: s.vhtlcAmount, + ChannelID: s.channelID, + SettlementType: s.settlementType, }, nil } @@ -596,7 +673,9 @@ func (s *ReceiveSession) runUntil(ctx context.Context, responderCtx, stopResponder := context.WithCancel(ctx) defer stopResponder() - if s.client != nil && receiveTargetNeedsForfeitResponder(target) { + if s.client != nil && !s.usesArkChannel() && + receiveTargetNeedsForfeitResponder(target) { + receiver, _ := s.client.outEvents.(OutSwapForfeitSignatureReceiver) paymentHash := s.PaymentHash @@ -647,6 +726,53 @@ func (s *ReceiveSession) transition(event receiveEvent) error { return nil } +// prepareClaimScript allocates a wallet claim script only for a vHTLC. +func (s *ReceiveSession) prepareClaimScript(ctx context.Context) (*ReceiveInfo, + error) { + + if s.requestActiveChannel { + return nil, nil + } + + info, err := s.client.daemon.AllocateReceiveScript(ctx, "") + if err != nil { + return nil, fmt.Errorf("allocate claim receive script: %w", err) + } + if err := validateClaimReceiveInfo(info); err != nil { + return nil, err + } + + return info, nil +} + +// receiveRouteChannel checks that every route reaches the same registered +// virtual channel, regardless of which backend the sender enters through. +func receiveRouteChannel(paths [][]*RouteHint) (uint64, error) { + if len(paths) == 0 { + return 0, fmt.Errorf("route quote must be provided") + } + var channelID uint64 + for i, path := range paths { + if len(path) == 0 { + return 0, fmt.Errorf("route hint path %d is empty", i) + } + hop := path[len(path)-1] + if hop == nil { + return 0, fmt.Errorf("route hint path %d has no "+ + "final hop", i) + } + if i == 0 { + channelID = hop.ChannelID + } else if hop.ChannelID != channelID { + return 0, fmt.Errorf("route hint path %d terminates "+ + "at channel %d, want %d", i, hop.ChannelID, + channelID) + } + } + + return channelID, nil +} + // prepareInvoice requests route metadata from the swap server and constructs // the invoice plus expected vHTLC policy. func (s *ReceiveSession) prepareInvoice(ctx context.Context) error { @@ -682,18 +808,9 @@ func (s *ReceiveSession) prepareInvoice(ctx context.Context) error { return fmt.Errorf("get receive auth key: %w", err) } - claimReceiveInfo, err := s.client.daemon.AllocateReceiveScript(ctx, "") + claimReceiveInfo, err := s.prepareClaimScript(ctx) if err != nil { - return fmt.Errorf("allocate claim receive script: %w", err) - } - if claimReceiveInfo == nil { - return fmt.Errorf("claim receive script is required") - } - if len(claimReceiveInfo.PubKeyXOnly) == 0 { - return fmt.Errorf("claim receive pubkey is required") - } - if len(claimReceiveInfo.PkScript) == 0 { - return fmt.Errorf("claim receive script is required") + return err } // Receive setup is the one session edge that prepares external @@ -727,13 +844,14 @@ func (s *ReceiveSession) prepareInvoice(ctx context.Context) error { return fmt.Errorf("create owner proof: %w", err) } quote, routingKey, err := s.requestReceiveRoute( - ctx, clientKey, paymentHash, supportsInArkCredit, ownerProof, + ctx, clientKey, paymentHash, + supportsInArkCredit && !s.requestActiveChannel, ownerProof, preimageRecoveryParams, ) if err != nil { return fmt.Errorf("request channel ID: %w", err) } - if quote == nil || len(quote.RouteHintPaths) == 0 { + if quote == nil { return fmt.Errorf("route quote must be provided") } if routingKey != nil { @@ -741,26 +859,9 @@ func (s *ReceiveSession) prepareInvoice(ctx context.Context) error { } hintPaths := quote.RouteHintPaths - // Every alternative path must terminate at the same virtual channel: - // the sender can enter through any backend, but all of them intercept - // into the one vSCID this receive is registered under. A divergent - // final hop would let a malformed quote split the receive across two - // different registrations. - var finalHop *RouteHint - for i, hintPath := range hintPaths { - if len(hintPath) == 0 { - return fmt.Errorf("route hint path %d is empty", i) - } - lastHop := hintPath[len(hintPath)-1] - if finalHop == nil { - finalHop = lastHop - continue - } - if lastHop.ChannelID != finalHop.ChannelID { - return fmt.Errorf("route hint path %d terminates at "+ - "channel %d, want %d", i, lastHop.ChannelID, - finalHop.ChannelID) - } + routeChannel, err := receiveRouteChannel(hintPaths) + if err != nil { + return err } requestedAmountSat := quote.RequestedAmountSat @@ -780,16 +881,33 @@ func (s *ReceiveSession) prepareInvoice(ctx context.Context) error { return fmt.Errorf("route quote attached credit overflows " + "vHTLC amount") } - if quote.AttachedCreditSat > 0 && - expectedVHTLCSat != requestedAmountSat+quote.AttachedCreditSat { + expectedQuoteVHTLC := requestedAmountSat + quote.AttachedCreditSat + if expectedVHTLCSat != expectedQuoteVHTLC { return fmt.Errorf("route quote vHTLC amount %d does not equal "+ "requested amount %d plus attached credit %d", expectedVHTLCSat, requestedAmountSat, quote.AttachedCreditSat) } + var channelID arkchannel.ID + if quote.SettlementType == SettlementTypeArkChannel { + return fmt.Errorf("swap quote cannot authorize channel " + + "settlement") + } + if s.requestActiveChannel { + if quote.AttachedCreditSat != 0 { + return fmt.Errorf("active-channel receive cannot " + + "settle attached credit") + } + channelID, err = s.prepareArkChannelReceive( + ctx, preimage, paymentHash, routeChannel, hintPaths, + ) + if err != nil { + return err + } + } s.client.log.InfoS(ctx, "Received route hint from swap server", - slog.Uint64("channel_id", finalHop.ChannelID), + slog.Uint64("channel_id", routeChannel), slog.Int("path_count", len(hintPaths)), slog.Int("path_hops", len(hintPaths[0])), slog.Uint64("payer_fee_msat", quote.PayerFeeMsat), @@ -803,10 +921,16 @@ func (s *ReceiveSession) prepareInvoice(ctx context.Context) error { &preimage, ) if err != nil { - return fmt.Errorf("create invoice: %w", err) + return s.abortPreparedArkChannelReceive( + ctx, paymentHash, s.requestActiveChannel, + fmt.Errorf("create invoice: %w", err), + ) } if hash != paymentHash { - return fmt.Errorf("invoice hash does not match route hash") + return s.abortPreparedArkChannelReceive( + ctx, paymentHash, s.requestActiveChannel, + fmt.Errorf("invoice hash does not match route hash"), + ) } s.client.log.InfoS(ctx, "Invoice created for out-swap", @@ -818,7 +942,7 @@ func (s *ReceiveSession) prepareInvoice(ctx context.Context) error { ), ) - return s.mutateAndPersist(ctx, func() error { + err = s.mutateAndPersist(ctx, func() error { s.Invoice = string(inv.PaymentRequest) s.Preimage = preimage s.PaymentHash = hash @@ -828,6 +952,9 @@ func (s *ReceiveSession) prepareInvoice(ctx context.Context) error { s.attachedCreditSat = quote.AttachedCreditSat s.expectedVHTLCSat = expectedVHTLCSat s.dustLimitSat = quote.DustLimitSat + s.reservedSCID = routeChannel + s.channelReceiveEnabled = s.requestActiveChannel + s.channelID = channelID s.settlementType = quote.SettlementType s.deadline = s.client.currentTime().Add(expiry) if s.createdAt.IsZero() { @@ -836,15 +963,134 @@ func (s *ReceiveSession) prepareInvoice(ctx context.Context) error { s.clientPubKey = clientKey s.operatorPubKey = operatorKey s.paymentAddr = inv.Terms.PaymentAddr - s.claimReceivePubKey = append( - []byte(nil), claimReceiveInfo.PubKeyXOnly..., - ) - s.claimReceiveScript = append( - []byte(nil), claimReceiveInfo.PkScript..., - ) + if claimReceiveInfo != nil { + s.claimReceivePubKey = append( + []byte(nil), claimReceiveInfo.PubKeyXOnly..., + ) + s.claimReceiveScript = append( + []byte(nil), claimReceiveInfo.PkScript..., + ) + } return s.transition(receiveEventInvoiceCreated) }) + if err != nil { + // A concurrent admission owns any idempotent registration for + // this hash; do not cancel its published invoice. + var conflict *swapAdmissionConflict + if errors.As(err, &conflict) { + return err + } + + return s.abortPreparedArkChannelReceive( + ctx, paymentHash, s.requestActiveChannel, err, + ) + } + + return nil +} + +// prepareArkChannelReceive binds this invoice to an existing channel. +func (s *ReceiveSession) prepareArkChannelReceive(ctx context.Context, + preimage lntypes.Preimage, hash lntypes.Hash, reservedSCID uint64, + hintPaths [][]*RouteHint) (arkchannel.ID, error) { + + bridge := s.client.channelBridge + var id arkchannel.ID + setupCtx, cancel := context.WithTimeout( + ctx, defaultArkChannelReceiveSetupTimeout, + ) + err := bridge.PrepareIncomingPayment(setupCtx, preimage, s.amountSat) + if err == nil { + var minimumCLTVDelta uint32 + id, minimumCLTVDelta, err = bridge.RegisterIncomingPayment( + setupCtx, hash, s.amountSat, reservedSCID, + ) + if err == nil && id == (arkchannel.ID{}) { + err = fmt.Errorf("no active channel registered for " + + "receive") + } + if err == nil { + err = raiseFinalRouteHintCLTV( + hintPaths, minimumCLTVDelta, + ) + } + } + cancel() + if err == nil { + return id, nil + } + + return arkchannel.ID{}, s.abortPreparedArkChannelReceive( + ctx, hash, true, err, + ) +} + +// raiseFinalRouteHintCLTV makes every alternative route reserve enough public +// lifetime for the private Ark-channel HTLC. Validate all paths before changing +// any. Only the final virtual hop changes; ingress prefixes retain their +// policy. +func raiseFinalRouteHintCLTV(hintPaths [][]*RouteHint, + minimumDelta uint32) error { + + if minimumDelta == 0 { + return fmt.Errorf("private payment CLTV delta is required") + } + if minimumDelta > uint32(^uint16(0)) { + return fmt.Errorf("private payment CLTV delta %d "+ + "exceeds BOLT 11", minimumDelta) + } + for i, hintPath := range hintPaths { + if len(hintPath) == 0 { + return fmt.Errorf("route hint path %d is empty", i) + } + finalHop := hintPath[len(hintPath)-1] + if finalHop == nil { + return fmt.Errorf("route hint path %d has no final hop", + i) + } + } + + for _, hintPath := range hintPaths { + finalHop := hintPath[len(hintPath)-1] + if finalHop.CltvExpiryDelta < minimumDelta { + finalHop.CltvExpiryDelta = minimumDelta + } + } + + return nil +} + +// abortPreparedArkChannelReceive cancels external channel state when invoice +// construction cannot durably publish the prepared receive session. +func (s *ReceiveSession) abortPreparedArkChannelReceive(ctx context.Context, + hash lntypes.Hash, enabled bool, cause error) error { + + if !enabled { + return cause + } + err := s.cancelIncomingChannelPayment( + ctx, hash, arkChannelReceiveSetupFailureReason, + defaultArkChannelReceiveSetupTimeout, + ) + if err != nil { + return errors.Join(cause, err) + } + + return cause +} + +// validateClaimReceiveInfo checks that the allocated vHTLC claim destination +// has both the signing identity and exact output script needed for recovery. +func validateClaimReceiveInfo(info *ReceiveInfo) error { + if info == nil || len(info.PkScript) == 0 { + return fmt.Errorf("claim receive script is required") + } + if len(info.PubKeyXOnly) == 0 { + return fmt.Errorf("claim receive pubkey is required") + } + + return nil } // requestReceiveRoute negotiates routing-key delegation with capable services. @@ -901,6 +1147,9 @@ func (s *ReceiveSession) requestReceiveRoute(ctx context.Context, // waitForHTLCEvent waits until the swap server delivers the HTLC event, // validates it, then persists the accepted event before acking the mailbox. func (s *ReceiveSession) waitForHTLCEvent(ctx context.Context) error { + if s.usesArkChannel() { + return s.waitForArkChannel(ctx) + } if s.client.outEvents == nil { return fmt.Errorf("out-swap event receiver is not configured") } @@ -913,9 +1162,7 @@ func (s *ReceiveSession) waitForHTLCEvent(ctx context.Context) error { waitCtx, cancel := s.invoiceDeadlineContext(ctx) defer cancel() - notification, err := s.waitIncomingVHTLCNotification( - waitCtx, ctx, authKey, - ) + notification, err := s.receiveIncomingVHTLCNotification(waitCtx) if err != nil { if invoiceDeadlineExceeded(ctx, waitCtx, err) { return fmt.Errorf("receive invoice deadline "+ @@ -924,6 +1171,14 @@ func (s *ReceiveSession) waitForHTLCEvent(ctx context.Context) error { return err } + // Once delivered, the event represents locked funds. Invoice expiry + // bounds only delivery; durable acceptance belongs to the caller. + notification, err = s.acceptIncomingVHTLCNotification( + ctx, notification, authKey, + ) + if err != nil { + return err + } if notification == nil { return fmt.Errorf("incoming vHTLC notification must be " + "provided") @@ -935,6 +1190,112 @@ func (s *ReceiveSession) waitForHTLCEvent(ctx context.Context) error { return s.ackAcceptedHTLCEvent(ctx, notification.Ack) } +// waitForArkChannel accepts only the HTLC delivered on the registered channel. +// The settlement decision is durable before the hold invoice releases funds. +func (s *ReceiveSession) waitForArkChannel(ctx context.Context) error { + if s.client.channelBridge == nil { + return newRetryableActionError( + fmt.Errorf("Ark channel payment bridge is unavailable"), + ) + } + if s.channelID == (arkchannel.ID{}) { + return newInterventionError( + "channel receive has no registered channel", nil, + ) + } + if s.settlementType != SettlementTypeArkChannel { + waitCtx, cancel := s.invoiceDeadlineContext(ctx) + defer cancel() + id, err := s.client.channelBridge.WaitIncomingPayment( + waitCtx, s.PaymentHash, + ) + if err != nil { + if invoiceDeadlineExceeded(ctx, waitCtx, err) { + return errSwapExpired + } + + return err + } + if id != s.channelID { + return newInterventionError( + "invoice arrived on a different channel", nil, + ) + } + } + resolutionCtx, cancel := context.WithTimeout( + context.WithoutCancel(ctx), + defaultArkChannelReceiveResolutionTimeout, + ) + defer cancel() + if s.settlementType != SettlementTypeArkChannel { + err := s.mutateAndPersist(resolutionCtx, func() error { + s.settlementType = SettlementTypeArkChannel + + return nil + }) + if err != nil { + return newRetryableActionError(err) + } + } + if err := s.client.channelBridge.SettleIncomingPayment( + resolutionCtx, s.Preimage, + ); err != nil { + return newRetryableActionError( + fmt.Errorf("settle incoming Ark channel payment: %w", + err), + ) + } + + err := s.mutateAndPersist(resolutionCtx, func() error { + s.channelReceiveEnabled = false + + return s.transition(receiveEventCompleted) + }) + if err != nil { + return newRetryableActionError(err) + } + + return nil +} + +// cancelPendingArkChannelReceive cancels a pending channel-only invoice before +// expiry or failure. +func (s *ReceiveSession) cancelPendingArkChannelReceive(ctx context.Context, + reason string) error { + + if !s.channelReceiveEnabled { + return nil + } + + return s.cancelIncomingChannelPayment( + ctx, s.PaymentHash, reason, + defaultArkChannelReceiveResolutionTimeout, + ) +} + +// cancelIncomingChannelPayment uses a detached bounded context so an RPC +// cancellation cannot strand the hold invoice or its route registration. +func (s *ReceiveSession) cancelIncomingChannelPayment(ctx context.Context, + hash lntypes.Hash, reason string, timeout time.Duration) error { + + if s.client == nil || s.client.channelBridge == nil { + return fmt.Errorf("Ark channel payment bridge is unavailable") + } + resolutionCtx, cancel := context.WithTimeout( + context.WithoutCancel(ctx), timeout, + ) + defer cancel() + + if err := s.client.channelBridge.CancelIncomingPayment( + resolutionCtx, hash, reason, + ); err != nil { + return fmt.Errorf("cancel incoming Ark channel payment: %w", + err) + } + + return nil +} + // invoiceDeadlineContext bounds only the unpaid-invoice mailbox wait. When a // daemon resumes after the invoice deadline, it still gives mailbox delivery a // short grace window to surface an already-delivered HTLC event before the @@ -968,6 +1329,11 @@ func invoiceDeadlineExceeded(parent, waitCtx context.Context, err error) bool { // waitForFunding waits until the expected accepted vHTLC is indexed as live. func (s *ReceiveSession) waitForFunding(ctx context.Context) error { + if s.usesArkChannel() { + return newInterventionError( + "channel invoice cannot fund a vHTLC", nil, + ) + } if err := s.ackAcceptedHTLCEvent(ctx, nil); err != nil { return err } @@ -1010,11 +1376,9 @@ func (s *ReceiveSession) waitForFunding(ctx context.Context) error { return s.ensureReceiveClaimRecoveryArmed(ctx) } -// waitIncomingVHTLCNotification waits for and validates the server notification -// that tells this receiver which vHTLC script should be funded. Acceptance uses -// the parent context so the delivery deadline cannot interrupt persistence. -func (s *ReceiveSession) waitIncomingVHTLCNotification( - ctx, acceptCtx context.Context, authKey ReceiveAuthKey) ( +// receiveIncomingVHTLCNotification waits for a mailbox event without mutating +// the session so channel and vHTLC arbitration stays single-threaded. +func (s *ReceiveSession) receiveIncomingVHTLCNotification(ctx context.Context) ( *IncomingVHTLCNotification, error) { if receiver, ok := s.client.outEvents.(IncomingVHTLCEventReceiver); ok { @@ -1029,9 +1393,7 @@ func (s *ReceiveSession) waitIncomingVHTLCNotification( return nil, err } - return s.acceptIncomingVHTLCNotification( - acceptCtx, notification, authKey, - ) + return notification, nil } notification, err := s.client.outEvents.WaitOutSwapHtlc( @@ -1054,7 +1416,7 @@ func (s *ReceiveSession) waitIncomingVHTLCNotification( return nil, err } - return s.acceptIncomingVHTLCNotification(acceptCtx, incoming, authKey) + return incoming, nil } // validateIncomingVHTLCAck checks mailbox ack metadata before the notification @@ -1697,6 +2059,21 @@ func (s *ReceiveSession) validateReceiveFunding(ctx context.Context, }) } + height, err := s.client.daemon.BlockHeight(ctx) + if err != nil { + return fmt.Errorf("get block height: %w", err) + } + if height+s.client.refundLocktimeBuffer >= + s.vhtlcConfig.RefundLocktime { + return s.failTerminal(ctx, fmt.Sprintf("funded "+ + "vHTLC observed too close to refund "+ + "locktime %d at height %d", + s.vhtlcConfig.RefundLocktime, height), nil, func() { + s.vhtlcOutpoint = funding.Outpoint + s.vhtlcAmount = funding.AmountSat + }) + } + return nil } @@ -1763,7 +2140,6 @@ func (s *ReceiveSession) claimFundedVHTLC(ctx context.Context) error { // OOR's durable status instead of submitting another claim. return s.resolveClaimSession(ctx) } - if s.state == ReceiveStateClaimInitiated && !s.claimIntentRecordedInProcess { diff --git a/sdk/swaps/out_swap_fsm.go b/sdk/swaps/out_swap_fsm.go index 27f18c6aa..db49e696a 100644 --- a/sdk/swaps/out_swap_fsm.go +++ b/sdk/swaps/out_swap_fsm.go @@ -235,12 +235,27 @@ func (m *receiveLoopFSM) fail( m.session.state == ReceiveStateExpired, m.session.state == ReceiveStateNeedsIntervention, func(ctx context.Context) error { + if err := m.session.cancelPendingArkChannelReceive( + ctx, arkChannelReceiveExpiryReason, + ); err != nil { + return err + } + return m.session.mutateAndPersist(ctx, func() error { + m.session.channelReceiveEnabled = false + return m.session.transition(receiveEventExpired) }) }, receiveEventExpired, func(ctx context.Context, reason string) error { + if err := m.session.cancelPendingArkChannelReceive( + ctx, arkChannelReceiveTerminalReason, + ); err != nil { + return err + } + return m.session.mutateAndPersist(ctx, func() error { + m.session.channelReceiveEnabled = false m.session.interventionReason = reason return m.session.transition( @@ -249,7 +264,14 @@ func (m *receiveLoopFSM) fail( }) }, receiveEventNeedsIntervention, func(ctx context.Context, reason string) error { + if err := m.session.cancelPendingArkChannelReceive( + ctx, arkChannelReceiveTerminalReason, + ); err != nil { + return err + } + return m.session.mutateAndPersist(ctx, func() error { + m.session.channelReceiveEnabled = false m.session.interventionReason = reason if m.session.state == ReceiveStateFailed { return nil diff --git a/sdk/swaps/out_swap_test.go b/sdk/swaps/out_swap_test.go index a4ebd0adf..78aa2ce5b 100644 --- a/sdk/swaps/out_swap_test.go +++ b/sdk/swaps/out_swap_test.go @@ -20,6 +20,7 @@ import ( "github.com/btcsuite/btcd/txscript/v2" "github.com/btcsuite/btcd/wire/v2" "github.com/btcsuite/btclog/v2" + "github.com/lightninglabs/wavelength/arkchannel" "github.com/lightninglabs/wavelength/lib/arkscript" "github.com/lightninglabs/wavelength/lib/swaprecovery" "github.com/lightninglabs/wavelength/swaprpc" @@ -37,6 +38,7 @@ import ( type testInvoiceCreator struct { invoice *invoices.Invoice paymentHash lntypes.Hash + createErr error lastAuthKey keychain.SingleKeyMessageSigner lastMemo string authKeys []keychain.SingleKeyMessageSigner @@ -55,7 +57,7 @@ func (c *testInvoiceCreator) CreateInvoice(_ context.Context, _ btcutil.Amount, ) } - return c.invoice, c.paymentHash, nil + return c.invoice, c.paymentHash, c.createErr } // CreateInvoiceWithKey returns the preconfigured invoice and payment hash. @@ -211,6 +213,309 @@ func TestStartReceiveDerivesReceiveAuthKeyPerPaymentHash(t *testing.T) { ) } +// TestArkChannelReceiveSettlesDirectly proves invoice creation installs and +// registers the private destination before publication, and raises the final +// route-hint delta so the hub's incoming HTLC can nest private delivery. +func TestArkChannelReceiveSettlesDirectly(t *testing.T) { + t.Parallel() + + clientPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + operatorPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + serverPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + creator := &testInvoiceCreator{invoice: &invoices.Invoice{ + PaymentRequest: []byte("lnrtest1channel"), + }} + serverConn := &testSwapServerConn{hint: &RouteHint{ + NodeID: serverPriv.PubKey().SerializeCompressed(), + ChannelID: 99, CltvExpiryDelta: 40, + }} + channelID := arkchannel.ID{1, 2, 3} + bridge := &testArkChannelPaymentBridge{ + waitChannelID: channelID, + } + client := NewSwapClient( + serverConn, &testDaemonConn{ + identityKey: clientPriv.PubKey(), + operatorKey: operatorPriv.PubKey(), + receiveAllocErr: errors.New( + "channel receive must not allocate a " + + "vHTLC claim", + ), + }, nil, creator, + ) + client.SetArkChannelPaymentBridge(bridge, true) + client.SetOutSwapEventReceiver(nil) + + session, err := client.StartReceiveViaArkChannel( + t.Context(), btcutil.Amount(42_000), + ) + require.NoError(t, err) + require.Equal(t, session.Preimage, bridge.preparePreimage) + require.Equal(t, btcutil.Amount(42_000), bridge.prepareAmount) + require.Equal(t, session.PaymentHash, bridge.registerHash) + require.Equal(t, uint64(99), bridge.registerSCID) + require.True(t, session.channelReceiveEnabled) + require.Len(t, creator.lastHintPaths, 1) + require.Equal( + t, uint32(616), creator.lastHintPaths[0][0].CltvExpiryDelta, + ) + + result, err := session.Wait(t.Context()) + require.NoError(t, err) + require.Equal(t, SettlementTypeArkChannel, result.SettlementType) + require.Equal(t, [32]byte(channelID), result.ChannelID) + require.EqualValues(t, 42_000, result.AmountSat) + require.Equal(t, ReceiveStateCompleted, session.State()) + require.False(t, session.channelReceiveEnabled) + require.Equal(t, 1, bridge.settleCalls) + require.Equal(t, session.Preimage, bridge.settlePreimage) + require.Zero(t, bridge.cancelCalls) +} + +// TestArkChannelReceiveRejectsDifferentChannel proves a valid HTLC on another +// native channel cannot authorize releasing this invoice's preimage. +func TestArkChannelReceiveRejectsDifferentChannel(t *testing.T) { + bridge := &testArkChannelPaymentBridge{waitChannelID: arkchannel.ID{2}} + session := &ReceiveSession{ + client: &SwapClient{ + channelBridge: bridge, + }, + state: ReceiveStateInvoiceCreated, + channelReceiveEnabled: true, channelID: arkchannel.ID{ + 1, + }, + } + err := session.waitForHTLCEvent(t.Context()) + require.ErrorContains(t, err, "different channel") + require.Zero(t, bridge.settleCalls) +} + +// TestArkChannelReceiveInvoiceFailureCancelsRegistration proves a successful +// channel registration cannot survive failure before invoice publication. +func TestArkChannelReceiveInvoiceFailureCancelsRegistration(t *testing.T) { + t.Parallel() + + clientPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + operatorPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + serverPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + createErr := errors.New("invoice publication failed") + creator := &testInvoiceCreator{createErr: createErr} + serverConn := &testSwapServerConn{hint: &RouteHint{ + NodeID: serverPriv.PubKey().SerializeCompressed(), + ChannelID: 99, CltvExpiryDelta: 40, + }} + bridge := &testArkChannelPaymentBridge{} + client := NewSwapClient( + serverConn, &testDaemonConn{ + identityKey: clientPriv.PubKey(), + operatorKey: operatorPriv.PubKey(), + }, nil, creator, + ) + client.SetArkChannelPaymentBridge(bridge, true) + + _, err = client.StartReceiveViaArkChannel( + t.Context(), btcutil.Amount(42_000), + ) + require.ErrorIs(t, err, createErr) + require.NotZero(t, bridge.registerSCID) + require.Equal(t, 1, bridge.cancelCalls) + require.Equal(t, bridge.registerHash, bridge.cancelHash) + require.Equal( + t, arkChannelReceiveSetupFailureReason, bridge.cancelReason, + ) +} + +// TestRaiseFinalRouteHintCLTV proves channel receive raises only final virtual +// hops, retains an already safer delta, and rejects values BOLT 11 cannot +// encode. +func TestRaiseFinalRouteHintCLTV(t *testing.T) { + t.Parallel() + + paths := [][]*RouteHint{ + { + { + ChannelID: 1, + CltvExpiryDelta: 20, + }, + { + ChannelID: 99, + CltvExpiryDelta: 40, + }, + }, + { + { + ChannelID: 99, + CltvExpiryDelta: 700, + }, + }, + } + require.NoError(t, raiseFinalRouteHintCLTV(paths, 616)) + require.Equal(t, uint32(20), paths[0][0].CltvExpiryDelta) + require.Equal(t, uint32(616), paths[0][1].CltvExpiryDelta) + require.Equal(t, uint32(700), paths[1][0].CltvExpiryDelta) + + require.Error(t, raiseFinalRouteHintCLTV(paths, 0)) + require.Error(t, raiseFinalRouteHintCLTV(paths, 1<<16)) + + invalid := [][]*RouteHint{ + { + { + CltvExpiryDelta: 40, + }, + }, + {}, + } + require.Error(t, raiseFinalRouteHintCLTV(invalid, 616)) + require.Equal(t, uint32(40), invalid[0][0].CltvExpiryDelta) +} + +// TestArkChannelReceiveSetupFailsClosed verifies registration failure cannot +// return a usable vHTLC invoice. +func TestArkChannelReceiveSetupFailsClosed(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + prepareErr error + registerErr error + wantRegister bool + }{ + { + name: "prepare unavailable", + prepareErr: errors.New("daemon unavailable"), + }, + { + name: "register unavailable", + registerErr: errors.New("hub unavailable"), + wantRegister: true, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + clientPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + operatorPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + serverPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + creator := &testInvoiceCreator{ + invoice: &invoices.Invoice{ + PaymentRequest: []byte( + "lnrtest1unpublished", + ), + }, + } + serverConn := &testSwapServerConn{hint: &RouteHint{ + NodeID: serverPriv. + PubKey(). + SerializeCompressed(), + ChannelID: 99, CltvExpiryDelta: 40, + }} + bridge := &testArkChannelPaymentBridge{ + prepareErr: test.prepareErr, + registerErr: test.registerErr, + } + client := NewSwapClient( + serverConn, &testDaemonConn{ + identityKey: clientPriv.PubKey(), + operatorKey: operatorPriv.PubKey(), + }, nil, creator, + ) + client.SetArkChannelPaymentBridge(bridge, true) + + session, err := client.StartReceiveViaArkChannel( + t.Context(), btcutil.Amount(42_000), + ) + require.Error(t, err) + require.Nil(t, session) + require.Empty(t, creator.lastHintPaths) + require.Equal( + t, test.wantRegister, bridge.registerSCID != 0, + ) + require.Equal(t, 1, bridge.cancelCalls) + require.Equal( + t, arkChannelReceiveSetupFailureReason, + bridge.cancelReason, + ) + + // The same client can request a separate ordinary + // invoice. + session, err = client.StartReceiveViaLightning( + t.Context(), 42_000, + ) + require.NoError(t, err) + require.NotEmpty(t, session.Invoice) + require.False(t, session.channelReceiveEnabled) + require.NotEqual( + t, session.PaymentHash, bridge.cancelHash, + ) + require.Equal(t, 1, bridge.cancelCalls) + }) + } +} + +// TestArkChannelReceiveTerminalFailureCancelsPrivateRail verifies a terminal +// non-channel result cannot leave its hold invoice eligible for later payment. +func TestArkChannelReceiveTerminalFailureCancelsPrivateRail(t *testing.T) { + t.Parallel() + + bridge := &testArkChannelPaymentBridge{} + client := NewSwapClient(nil, nil, nil, nil) + client.SetArkChannelPaymentBridge(bridge, true) + session := &ReceiveSession{ + client: client, + PaymentHash: lntypes.Hash{ + 10, + 11, + 12, + }, + state: ReceiveStateInvoiceCreated, + channelReceiveEnabled: true, + } + cause := errors.New("invalid channel payment") + + err := session.failTerminal( + t.Context(), cause.Error(), cause, nil, + ) + require.ErrorIs(t, err, cause) + require.Equal(t, ReceiveStateFailed, session.State()) + require.False(t, session.channelReceiveEnabled) + require.Equal(t, 1, bridge.cancelCalls) + require.Equal( + t, arkChannelReceiveTerminalReason, bridge.cancelReason, + ) +} + +// TestArkChannelReceiveExpiryCancelsRegistration verifies an unpaid channel +// invoice expires without touching the vHTLC event receiver. +func TestArkChannelReceiveExpiryCancelsRegistration(t *testing.T) { + bridge := &testArkChannelPaymentBridge{wait: make(chan struct{})} + client := NewSwapClient(nil, nil, nil, nil) + client.SetArkChannelPaymentBridge(bridge, true) + client.overdueReceivePollWindow = time.Millisecond + session := &ReceiveSession{ + client: client, channelID: arkchannel.ID{ + 1, + }, + channelReceiveEnabled: true, state: ReceiveStateInvoiceCreated, + deadline: time.Now().Add(-time.Second), + } + _, err := session.Wait(t.Context()) + require.ErrorIs(t, err, errSwapExpired) + require.Equal(t, ReceiveStateExpired, session.State()) + require.Equal(t, 1, bridge.cancelCalls) + require.Zero(t, bridge.settleCalls) +} + // TestStartReceiveEmbedsAllRouteHintPaths verifies every alternative // route-hint path from the quote flows through to invoice creation when all // paths terminate at the same virtual channel. @@ -1519,6 +1824,95 @@ type testSwapServerConn struct { lastRecoverableProof *swaprpc.SwapOwnerProof } +type testArkChannelPaymentBridge struct { + preparePreimage lntypes.Preimage + prepareAmount btcutil.Amount + prepareErr error + registerHash lntypes.Hash + registerAmount btcutil.Amount + registerSCID uint64 + registerCLTV uint32 + registerErr error + waitChannelID arkchannel.ID + waitErr error + wait <-chan struct{} + settlePreimage lntypes.Preimage + settleCalls int + settleErr error + cancelHash lntypes.Hash + cancelReason string + cancelCalls int + cancelErr error + cancelContextErr error +} + +func (b *testArkChannelPaymentBridge) PrepareIncomingPayment(_ context.Context, + preimage lntypes.Preimage, amount btcutil.Amount) error { + + b.preparePreimage = preimage + b.prepareAmount = amount + + return b.prepareErr +} + +func (b *testArkChannelPaymentBridge) RegisterIncomingPayment(_ context.Context, + hash lntypes.Hash, amount btcutil.Amount, scid uint64) (arkchannel.ID, + uint32, error) { + + b.registerHash = hash + b.registerAmount = amount + b.registerSCID = scid + + delta := b.registerCLTV + if delta == 0 { + delta = 616 + } + + id := b.waitChannelID + if id == (arkchannel.ID{}) { + id = arkchannel.ID{1} + } + + return id, delta, b.registerErr +} + +func (b *testArkChannelPaymentBridge) WaitIncomingPayment(ctx context.Context, + _ lntypes.Hash) (arkchannel.ID, error) { + + if b.wait != nil { + select { + case <-ctx.Done(): + return arkchannel.ID{}, ctx.Err() + + case <-b.wait: + } + } + + return b.waitChannelID, b.waitErr +} + +// SettleIncomingPayment records the selected channel result in tests. +func (b *testArkChannelPaymentBridge) SettleIncomingPayment(_ context.Context, + preimage lntypes.Preimage) error { + + b.settleCalls++ + b.settlePreimage = preimage + + return b.settleErr +} + +// CancelIncomingPayment records release of the unused channel rail in tests. +func (b *testArkChannelPaymentBridge) CancelIncomingPayment(ctx context.Context, + hash lntypes.Hash, reason string) error { + + b.cancelCalls++ + b.cancelHash = hash + b.cancelReason = reason + b.cancelContextErr = ctx.Err() + + return b.cancelErr +} + type testIncomingEventReceiver struct { notification *IncomingVHTLCNotification } @@ -2308,9 +2702,9 @@ func acceptTestOutSwapHtlcEvent(t *testing.T, client *SwapClient, require.Equal(t, ReceiveStateHTLCEventAccepted, session.State()) } -// TestWaitIncomingVHTLCNotificationRejectsMissingAckCursor verifies ack +// TestReceiveIncomingVHTLCNotificationRejectsMissingAckCursor verifies ack // metadata is checked before the event is durably accepted. -func TestWaitIncomingVHTLCNotificationRejectsMissingAckCursor(t *testing.T) { +func TestReceiveIncomingVHTLCNotificationRejectsMissingAckCursor(t *testing.T) { t.Parallel() clientPriv, err := btcec.NewPrivateKey() @@ -2332,9 +2726,7 @@ func TestWaitIncomingVHTLCNotificationRejectsMissingAckCursor(t *testing.T) { clientPubKey: clientPriv.PubKey(), } - _, err = session.waitIncomingVHTLCNotification( - t.Context(), t.Context(), nil, - ) + _, err = session.receiveIncomingVHTLCNotification(t.Context()) require.ErrorContains(t, err, "incoming vHTLC ack cursor") require.Equal(t, ReceiveStateInvoiceCreated, session.State()) require.Zero(t, session.pendingHTLCAckCursor) @@ -4286,8 +4678,8 @@ func TestReceiveSessionOverdueInvoiceAcceptsDeliveredEvent(t *testing.T) { client := NewSwapClientWithStore( serverConn, daemonConn, nil, creator, store, ) - // The cached event is already delivered, so acceptance must persist - // under the parent context even after the polling window closes. + // Expire the polling context synchronously. The cached event is + // already delivered, so acceptance must use the caller's context. client.overdueReceivePollWindow = 0 useTestOnionDecoder(client, 42_000) diff --git a/sdk/swaps/store_admission_test.go b/sdk/swaps/store_admission_test.go index b45136bd0..632090bc8 100644 --- a/sdk/swaps/store_admission_test.go +++ b/sdk/swaps/store_admission_test.go @@ -106,6 +106,52 @@ func admissionReceiveSession(t *testing.T, client *SwapClient, return session } +// TestChannelReceiveAdmissionPreservesIdentity verifies both insert-only +// admission paths persist the same channel identity as subsequent updates. +func TestChannelReceiveAdmissionPreservesIdentity(t *testing.T) { + t.Parallel() + for _, restored := range []bool{false, true} { + name := "normal" + if restored { + name = "restored" + } + t.Run(name, func(t *testing.T) { + t.Parallel() + ctx := t.Context() + store := newTestSwapStore(t) + client := NewSwapClientWithStore( + nil, nil, nil, nil, store, + ) + session := admissionReceiveSession(t, client, restored) + session.channelReceiveEnabled = true + session.reservedSCID = 1<<63 | 99 + session.channelID = [32]byte{1, 2, 3} + if restored { + require.NoError(t, session.persistRestored(ctx)) + } else { + require.NoError(t, session.persist(ctx)) + } + for range 2 { + resumed, err := + client.ResumeReceiveViaLightning( + ctx, session.PaymentHash, + ) + require.NoError(t, err) + require.True(t, resumed.channelReceiveEnabled) + require.Equal( + t, session.reservedSCID, + resumed.reservedSCID, + ) + require.Equal( + t, session.channelID, resumed.channelID, + ) + resumed.Invoice = "updated-invoice" + require.NoError(t, resumed.persist(ctx)) + } + }) + } +} + // TestRestoredAdmissionPreservesWinner covers stale restore admission after a // normal worker has persisted accepted protocol work or a terminal outcome. func TestRestoredAdmissionPreservesWinner(t *testing.T) { diff --git a/sdk/swaps/store_sessions.go b/sdk/swaps/store_sessions.go index c25afa2dd..16072a2b9 100644 --- a/sdk/swaps/store_sessions.go +++ b/sdk/swaps/store_sessions.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "database/sql" + "encoding/binary" "encoding/json" "errors" "fmt" @@ -427,6 +428,13 @@ func receiveSummaryFromRow(row swapsqlc.ReceiveSwap) (SwapSummary, error) { if err != nil { return SwapSummary{}, err } + if len(row.ReservedScid) != 0 && len(row.ReservedScid) != 8 { + return SwapSummary{}, fmt.Errorf("invalid reserved channel " + + "SCID") + } + if len(row.ChannelID) != 0 && len(row.ChannelID) != 32 { + return SwapSummary{}, fmt.Errorf("invalid receive channel ID") + } paymentHash, err := hashFromBytes(row.PaymentHash) if err != nil { @@ -457,6 +465,8 @@ func receiveSummaryFromRow(row swapsqlc.ReceiveSwap) (SwapSummary, error) { VHTLCAmountSat: row.VhtlcAmount, ClaimSessionID: row.ClaimSessionID, SettlementType: SettlementType(row.SettlementType), + ChannelID: receiveChannelID(row.ChannelID), + ReservedSCID: decodeReceiveSCID(row.ReservedScid), RequestedAmountSat: requestedAmountSat, Memo: row.Memo, AvailableCreditSat: uint64(row.AvailableCreditSat), @@ -618,17 +628,20 @@ func (s *ReceiveSession) persistSnapshot(ctx context.Context, PendingHtlcAckCursor: int64( s.pendingHTLCAckCursor, ), - ClaimReceivePubkey: cloneBytesOrEmpty(s.claimReceivePubKey), - ClaimReceivePkscript: cloneBytesOrEmpty(s.claimReceiveScript), - ClaimSessionID: s.claimSessionID, - ClaimRecoveryID: s.claimRecoveryID, - InterventionReason: s.interventionReason, - RequestedAmountSat: int64(s.requestedAmountSat), - AvailableCreditSat: int64(s.availableCreditSat), - AttachedCreditSat: int64(s.attachedCreditSat), - DustLimitSat: int64(s.dustLimitSat), - CreatedAtUnix: s.createdAt.Unix(), - UpdatedAtUnix: now, + ClaimReceivePubkey: cloneBytesOrEmpty(s.claimReceivePubKey), + ClaimReceivePkscript: cloneBytesOrEmpty(s.claimReceiveScript), + ClaimSessionID: s.claimSessionID, + ClaimRecoveryID: s.claimRecoveryID, + InterventionReason: s.interventionReason, + RequestedAmountSat: int64(s.requestedAmountSat), + AvailableCreditSat: int64(s.availableCreditSat), + AttachedCreditSat: int64(s.attachedCreditSat), + DustLimitSat: int64(s.dustLimitSat), + ReservedScid: encodeReceiveSCID(s.reservedSCID), + ChannelReceiveEnabled: s.channelReceiveEnabled, + ChannelID: append([]byte(nil), s.channelID[:]...), + CreatedAtUnix: s.createdAt.Unix(), + UpdatedAtUnix: now, RequestID: sql.NullString{ String: s.requestID, Valid: s.requestID != "", @@ -891,6 +904,12 @@ func receiveSessionFromRow(c *SwapClient, if err != nil { return nil, err } + if len(row.ReservedScid) != 0 && len(row.ReservedScid) != 8 { + return nil, fmt.Errorf("invalid reserved channel SCID") + } + if len(row.ChannelID) != 0 && len(row.ChannelID) != 32 { + return nil, fmt.Errorf("invalid receive channel ID") + } clientKey, err := btcec.ParsePubKey(row.ClientPubkey) if err != nil { @@ -995,17 +1014,20 @@ func receiveSessionFromRow(c *SwapClient, claimReceiveScript: append( []byte(nil), row.ClaimReceivePkscript..., ), - claimSessionID: row.ClaimSessionID, - claimRecoveryID: row.ClaimRecoveryID, - interventionReason: row.InterventionReason, - clientPubKey: clientKey, - operatorPubKey: operatorKey, - swapServerPubKey: swapServerKey, - settlementType: SettlementType(row.SettlementType), - paymentAddr: paymentAddr, - createdAt: time.Unix(row.CreatedAtUnix, 0), - updatedAt: time.Unix(row.UpdatedAtUnix, 0), - forfeitBindingGate: newReceiveForfeitBindingGate(), + claimSessionID: row.ClaimSessionID, + claimRecoveryID: row.ClaimRecoveryID, + interventionReason: row.InterventionReason, + clientPubKey: clientKey, + operatorPubKey: operatorKey, + swapServerPubKey: swapServerKey, + settlementType: SettlementType(row.SettlementType), + reservedSCID: decodeReceiveSCID(row.ReservedScid), + channelReceiveEnabled: row.ChannelReceiveEnabled, + channelID: receiveChannelID(row.ChannelID), + paymentAddr: paymentAddr, + createdAt: time.Unix(row.CreatedAtUnix, 0), + updatedAt: time.Unix(row.UpdatedAtUnix, 0), + forfeitBindingGate: newReceiveForfeitBindingGate(), } // A restored session was reconstructed from a durable row, so a @@ -1025,6 +1047,33 @@ func receiveExpectedVHTLCSat(row swapsqlc.ReceiveSwap) uint64 { return requestedAmountSat + uint64(row.AttachedCreditSat) } +func encodeReceiveSCID(scid uint64) []byte { + if scid == 0 { + return []byte{} + } + encoded := make([]byte, 8) + binary.BigEndian.PutUint64(encoded, scid) + + return encoded +} + +func decodeReceiveSCID(encoded []byte) uint64 { + if len(encoded) != 8 { + return 0 + } + + return binary.BigEndian.Uint64(encoded) +} + +func receiveChannelID(encoded []byte) [32]byte { + var id [32]byte + if len(encoded) == len(id) { + copy(id[:], encoded) + } + + return id +} + // paySessionFromRow reconstructs one pay session from its persisted SQL row. func paySessionFromRow(ctx context.Context, c *SwapClient, row swapsqlc.PaySwap) (*PaySession, error) { diff --git a/sdk/swaps/store_test.go b/sdk/swaps/store_test.go index 7b577b423..c593e07c0 100644 --- a/sdk/swaps/store_test.go +++ b/sdk/swaps/store_test.go @@ -10,6 +10,7 @@ import ( "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btclog/v2" + "github.com/lightninglabs/wavelength/arkchannel" swapsqlc "github.com/lightninglabs/wavelength/sdk/swaps/sqlc" "github.com/lightningnetwork/lnd/lntypes" "github.com/stretchr/testify/require" @@ -169,6 +170,83 @@ func TestPaySessionPersistAllowsCreditOnlyWithoutVHTLC(t *testing.T) { require.Empty(t, resumed.vhtlcPolicyTemplate) } +// TestReceiveChannelRailOwnershipPersists verifies restart recovery remembers +// whether this receive still owns the private hold invoice on its reserved +// channel. +func TestReceiveChannelRailOwnershipPersists(t *testing.T) { + t.Parallel() + + ctx := context.Background() + store := newTestSwapStore(t) + client := NewSwapClientWithStore(nil, nil, nil, nil, store) + + key, err := btcec.NewPrivateKey() + require.NoError(t, err) + preimage, err := NewPreimage() + require.NoError(t, err) + + now := time.Now() + session := &ReceiveSession{ + Invoice: "ln-channel-receive", + Preimage: preimage, + PaymentHash: preimage.Hash(), + client: client, + amountSat: 21_000, + requestedAmountSat: 21_000, + channelID: arkchannel.ID{ + 1, + 2, + 3, + }, + reservedSCID: 99, + channelReceiveEnabled: true, + state: ReceiveStateInvoiceCreated, + deadline: now.Add(time.Hour), + clientPubKey: key.PubKey(), + operatorPubKey: key.PubKey(), + settlementType: SettlementTypeLightning, + createdAt: now, + } + require.NoError(t, session.persist(ctx)) + + resumed, err := client.ResumeReceiveViaLightning( + ctx, session.PaymentHash, + ) + require.NoError(t, err) + require.True(t, resumed.channelReceiveEnabled) + require.Equal(t, uint64(99), resumed.reservedSCID) + require.Equal(t, session.channelID, resumed.channelID) + + channelID := arkchannel.ID{1, 2, 3} + lostResponseErr := errors.New("settlement response lost") + bridge := &testArkChannelPaymentBridge{ + waitChannelID: channelID, + settleErr: lostResponseErr, + } + client.SetArkChannelPaymentBridge(bridge, true) + err = resumed.waitForHTLCEvent(ctx) + require.ErrorIs(t, err, lostResponseErr) + require.Equal(t, 1, bridge.settleCalls) + require.Equal(t, ReceiveStateInvoiceCreated, resumed.State()) + require.True(t, resumed.channelReceiveEnabled) + require.Equal(t, [32]byte(channelID), resumed.channelID) + + reconciled, err := client.ResumeReceiveViaLightning( + ctx, session.PaymentHash, + ) + require.NoError(t, err) + bridge = &testArkChannelPaymentBridge{} + client.SetArkChannelPaymentBridge(bridge, false) + _, err = client.StartReceiveViaArkChannel(ctx, 1_000) + require.ErrorContains(t, err, "not enabled") + client.SetOutSwapEventReceiver(nil) + require.NoError(t, reconciled.waitForHTLCEvent(ctx)) + require.Equal(t, ReceiveStateCompleted, reconciled.State()) + require.False(t, reconciled.channelReceiveEnabled) + require.Equal(t, [32]byte(channelID), reconciled.channelID) + require.Equal(t, 1, bridge.settleCalls) +} + // TestReceiveAuthKeyDerivesAcrossRestart verifies receive-auth keys come from // the wallet-backed daemon derivation and are not stored in the swap DB. func TestReceiveAuthKeyDerivesAcrossRestart(t *testing.T) { From 6e06195aafe88e6e28e62dfcdb1863df65e25e81 Mon Sep 17 00:00:00 2001 From: sputn1ck Date: Tue, 24 Nov 2026 17:46:59 +0100 Subject: [PATCH 4/5] swapwallet: Route explicit receives to an existing active channel Bind the invoice to an admitted channel with inbound liquidity. Ordinary receives retain their original rail and do not open a channel. Resume pending settlement independently of permission for a new invoice. --- cmd/wavecli/waveclicommands/AGENTS.md | 1 + cmd/wavecli/waveclicommands/CLAUDE.md | 1 + cmd/wavecli/waveclicommands/cmd_channel.go | 51 +++++++++- .../waveclicommands/cmd_channel_test.go | 10 +- docs/daemon_cli_guide.md | 15 ++- swapclientserver/AGENTS.md | 26 +++++ swapclientserver/CLAUDE.md | 26 +++++ swapclientserver/ark_channel_bridge.go | 58 +++++++++++ swapclientserver/service.go | 75 ++++++++++++--- swapclientserver/service_test.go | 95 +++++++++++++++++-- swapwallet/inspection.go | 2 + swapwallet/inspection_test.go | 5 + swapwallet/recv.go | 36 ++++++- swapwallet/recv_test.go | 47 +++++++++ swapwallet/service.go | 11 +++ 15 files changed, 424 insertions(+), 35 deletions(-) create mode 100644 swapclientserver/ark_channel_bridge.go diff --git a/cmd/wavecli/waveclicommands/AGENTS.md b/cmd/wavecli/waveclicommands/AGENTS.md index 60193df5c..1ca35ed50 100644 --- a/cmd/wavecli/waveclicommands/AGENTS.md +++ b/cmd/wavecli/waveclicommands/AGENTS.md @@ -87,6 +87,7 @@ Every command prints the raw protobuf JSON response. | `channel create ` | `PromoteVTXO` | Promote wallet value into a channel; the daemon derives the protocol terms from capacity | | `channel get ` | `GetChannel` | Show one durable channel snapshot and live balances when available | | `channel list` | `ListChannels` | List channels that still need recovery, observation, or operator action | +| `channel receive ` | `StartReceive` | Issue an invoice on an existing active channel; requires `--swap.arkchannelsenabled` | | `channel pay ` | `PayLightningInvoice` | Hold the private channel leg while the hub pays a public Lightning invoice; `--max-fee-sat` defaults to 1,000 | | `channel close ` | `RequestCooperativeClose` | Start or resume the client-owned cooperative close | | `channel force-close ` | `MaterializeAndForceClose` | Publish the Ark ancestry, signed backing, and latest commitment | diff --git a/cmd/wavecli/waveclicommands/CLAUDE.md b/cmd/wavecli/waveclicommands/CLAUDE.md index 60193df5c..1ca35ed50 100644 --- a/cmd/wavecli/waveclicommands/CLAUDE.md +++ b/cmd/wavecli/waveclicommands/CLAUDE.md @@ -87,6 +87,7 @@ Every command prints the raw protobuf JSON response. | `channel create ` | `PromoteVTXO` | Promote wallet value into a channel; the daemon derives the protocol terms from capacity | | `channel get ` | `GetChannel` | Show one durable channel snapshot and live balances when available | | `channel list` | `ListChannels` | List channels that still need recovery, observation, or operator action | +| `channel receive ` | `StartReceive` | Issue an invoice on an existing active channel; requires `--swap.arkchannelsenabled` | | `channel pay ` | `PayLightningInvoice` | Hold the private channel leg while the hub pays a public Lightning invoice; `--max-fee-sat` defaults to 1,000 | | `channel close ` | `RequestCooperativeClose` | Start or resume the client-owned cooperative close | | `channel force-close ` | `MaterializeAndForceClose` | Publish the Ark ancestry, signed backing, and latest commitment | diff --git a/cmd/wavecli/waveclicommands/cmd_channel.go b/cmd/wavecli/waveclicommands/cmd_channel.go index 5e68dcd43..31bf8cbcf 100644 --- a/cmd/wavecli/waveclicommands/cmd_channel.go +++ b/cmd/wavecli/waveclicommands/cmd_channel.go @@ -10,6 +10,7 @@ import ( "time" "github.com/lightninglabs/wavelength/rpc/arkchannelrpc" + "github.com/lightninglabs/wavelength/rpc/swapclientrpc" "github.com/spf13/cobra" "google.golang.org/grpc" "google.golang.org/grpc/codes" @@ -44,8 +45,8 @@ func newChannelCmd() *cobra.Command { } cmd.AddCommand( newChannelCreateCmd(), newChannelGetCmd(), newChannelListCmd(), - newChannelPayCmd(), newChannelRefreshCmd(), - newChannelForceCloseCmd(), + newChannelPayCmd(), newChannelReceiveCmd(), + newChannelRefreshCmd(), newChannelForceCloseCmd(), ) return cmd @@ -269,6 +270,52 @@ func newChannelPayCmd() *cobra.Command { return cmd } +// newChannelReceiveCmd obtains an invoice bound to an existing active channel. +func newChannelReceiveCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "receive ", + Short: "Receive Lightning over an active channel", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + amount, err := parsePositiveChannelAmount(args[0]) + if err != nil { + return err + } + conn, err := getDaemonConn(cmd) + if err != nil { + return err + } + defer conn.Close() + ctx, cancel := rpcContext(cmd) + defer cancel() + memo, _ := cmd.Flags().GetString("memo") + client := swapclientrpc.NewSwapClientServiceClient(conn) + resp, err := client.StartReceive( + ctx, &swapclientrpc.StartReceiveRequest{ + AmountSat: amount, + Memo: memo, + ActiveChannelOnly: true, + }, + ) + if err != nil { + return err + } + // Older daemons ignore the request flag. Do not publish + // a swap invoice if the daemon did not reserve a + // channel. + if len(resp.GetSwap().GetChannelId()) != 32 { + return fmt.Errorf("daemon did not reserve an " + + "active channel") + } + + return printJSON(resp) + }, + } + cmd.Flags().String("memo", "", "invoice description") + + return cmd +} + // newChannelRefreshCmd settles one clean channel into replacement VTXOs. func newChannelRefreshCmd() *cobra.Command { return channelIDCommand( diff --git a/cmd/wavecli/waveclicommands/cmd_channel_test.go b/cmd/wavecli/waveclicommands/cmd_channel_test.go index bb05bb2fd..07eae3ce7 100644 --- a/cmd/wavecli/waveclicommands/cmd_channel_test.go +++ b/cmd/wavecli/waveclicommands/cmd_channel_test.go @@ -161,10 +161,12 @@ func TestChannelCommandRecoveryFlags(t *testing.T) { _, _, err = root.Find([]string{"close"}) require.ErrorContains(t, err, "unknown command") - for _, method := range []string{"send", "receive"} { - _, _, err := root.Find([]string{method}) - require.ErrorContains(t, err, "unknown command") - } + receive, _, err := root.Find([]string{"receive"}) + require.NoError(t, err) + require.Equal(t, "receive", receive.Name()) + require.NotNil(t, receive.Flags().Lookup("memo")) + _, _, err = root.Find([]string{"send"}) + require.ErrorContains(t, err, "unknown command") pay := newChannelPayCmd() maxFee, err := pay.Flags().GetUint64("max-fee-sat") diff --git a/docs/daemon_cli_guide.md b/docs/daemon_cli_guide.md index 1376b3e1a..1c1bc5fd6 100644 --- a/docs/daemon_cli_guide.md +++ b/docs/daemon_cli_guide.md @@ -153,7 +153,7 @@ waved \ | `--swap.serveraddress` | network default | Swap server address override for swapruntime builds | | `--swap.servertransport` | `grpc` | Swap server transport: `grpc` or `rest` | | `--maxpaymentcltv` | `480` in swap-enabled builds | Largest total Lightning payment CLTV reserved by automatic VTXO refresh; `0` disables the payment reserve | -| `--swap.arkchannelsenabled` | `false` | Permit explicit channel open and pay; ordinary send and receive are unchanged | +| `--swap.arkchannelsenabled` | `false` | Permit explicit channel open, pay and receive; ordinary send and receive are unchanged | | `--swap.disablearkchannelruntime` | `false` | Disable protection only if the local recovery inventory is readable and empty | Empty Ark and swap addresses resolve from the selected network and transport. @@ -532,13 +532,20 @@ hex. wavecli channel create 100000 wavecli channel get wavecli channel pay --max-fee-sat 1000 +wavecli channel receive 25000 wavecli channel refresh wavecli channel force-close ``` -Opening a channel and paying through it require `--swap.arkchannelsenabled`. -An ordinary `recv --offchain --amt ` settles into the wallet and -does not open a channel. To fund one, use `wavecli channel create `. +With `--swap.arkchannelsenabled`, `channel receive ` +returns an invoice bound to an existing active channel. If no channel has +enough inbound liquidity, the command fails without issuing an invoice. +`activity inspect --format json` shows the selected +`channel_id` and the invoice's virtual SCID. + +To receive into the wallet instead, use `recv --offchain --amt ` +to create a separate invoice. To fund a channel from wallet VTXOs, use +`wavecli channel create `. ### `ark board` / `dev daemon Board` diff --git a/swapclientserver/AGENTS.md b/swapclientserver/AGENTS.md index 7458e7622..2a5cd90a9 100644 --- a/swapclientserver/AGENTS.md +++ b/swapclientserver/AGENTS.md @@ -32,6 +32,10 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`. - `receiveSessionAdapter` — Adds method accessors over `sdk/swaps.ReceiveSession` so both production code and tests share the same interface without exposing struct fields. +- `arkChannelPaymentBridge` — Adapts the SDK's channel-payment boundary to the + daemon-owned native lnd controller through direct `waved.RPCServer` calls. + It prepares, registers, waits, settles, and cancels incoming channel + payments without an in-process gRPC loop. - `creditServerBridge` / `creditDaemonBridge` — Adapt the subserver and the in-process Ark/daemon facade to the `credit` package's `CreditServer` / `CreditDaemon` interfaces, so the credit durable-actor subsystem reuses this @@ -46,6 +50,10 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`. `MailboxOutSwapEventReceiver` (empty mailbox ID — receiver derives the per-swap mailbox from client identity + payment hash) on the `SwapClient` so out-swap HTLC events flow over the mailbox transport, + installs the channel bridge for durable settlement but admits new channel + invoices only when `SwapConfig.ArkChannelsEnabled` is true, and publishes the + authenticated swap-server mailbox as `cfg.Swap.ArkChannelMailbox` for the + daemon-owned channel process. Cleanup clears that mailbox handle, publishes `cfg.Swap.Backend`/`CreditServer`/`CreditDaemon` bridges, registers the gRPC subserver, calls `resumePending` (unless `cfg.Swap.SuppressResume`), and returns a cleanup function. @@ -69,6 +77,8 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`. - **Depends on**: `sdk/swaps` (swap FSM, `SwapClient`, `Store`, session, credit types), `sdk/ark` (`WrapDaemonServer`, in-process Ark facade), + `arkchannel` (channel IDs returned by the payment bridge), `mailbox/pb` + (method identities used by reconnect admission), `waved` (`RPCServer`, `Config`, `SwapConfig`, `SwapSubsystem`), `credit` (`CreditServer`/`CreditDaemon` interfaces bridged for the credit actor subsystem), `rpc/swapclientrpc` (generated gRPC stubs + proto types). @@ -88,6 +98,13 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`. - Worker ownership is process-local and mutex-guarded: at most one goroutine drives a given payment hash at any time. `markActive` is the admission gate; `markInactive` releases it on goroutine exit. +- A process-local resume or `Wait` error is not itself terminal. The worker + reads the durable summary and retries while the FSM remains pending; it + releases ownership only after terminal state, successful completion, missing + durable state, or daemon shutdown. `runSwapWorker` is the shared retry loop + for both directions; `workerRetryDelay` defaults to one second and remains a + service field so tests can shorten it without moving retry policy into the + swap FSM. - The daemon uses `rootCtx` (not the individual RPC contexts) for all `ResumePayViaLightning` / `ResumeReceiveViaLightning` calls. A CLI disconnect does not cancel an admitted swap. @@ -139,6 +156,15 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`. "no filesystem here". It mirrors `waved.ensureDataDir`; keep the two in step, since a Node host given an unwritable path should fail there rather than at the first database open. +- `swapServerOperationWaitsForReady` enables gRPC reconnect waiting only for + methods that create or advance durable protocol state. Mailbox `Send` is + included because a receive acknowledgement must survive a reconnect; + mailbox `Pull`, quote RPCs, and credit snapshots remain fail-fast. New + state-changing RPCs must be classified explicitly. +- `StartReceive(active_channel_only=true)` requires the opt-in daemon bridge. + It must reserve an existing active channel or fail without an invoice. + An ordinary `StartReceive` never calls the channel bridge, even when the + daemon flag is enabled. - `SetOutSwapEventReceiver` must run before any receive worker is started: `SwapClient` captures the receiver into the per-swap worker at start time, so a late install would leave already-running workers using whatever diff --git a/swapclientserver/CLAUDE.md b/swapclientserver/CLAUDE.md index 7458e7622..2a5cd90a9 100644 --- a/swapclientserver/CLAUDE.md +++ b/swapclientserver/CLAUDE.md @@ -32,6 +32,10 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`. - `receiveSessionAdapter` — Adds method accessors over `sdk/swaps.ReceiveSession` so both production code and tests share the same interface without exposing struct fields. +- `arkChannelPaymentBridge` — Adapts the SDK's channel-payment boundary to the + daemon-owned native lnd controller through direct `waved.RPCServer` calls. + It prepares, registers, waits, settles, and cancels incoming channel + payments without an in-process gRPC loop. - `creditServerBridge` / `creditDaemonBridge` — Adapt the subserver and the in-process Ark/daemon facade to the `credit` package's `CreditServer` / `CreditDaemon` interfaces, so the credit durable-actor subsystem reuses this @@ -46,6 +50,10 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`. `MailboxOutSwapEventReceiver` (empty mailbox ID — receiver derives the per-swap mailbox from client identity + payment hash) on the `SwapClient` so out-swap HTLC events flow over the mailbox transport, + installs the channel bridge for durable settlement but admits new channel + invoices only when `SwapConfig.ArkChannelsEnabled` is true, and publishes the + authenticated swap-server mailbox as `cfg.Swap.ArkChannelMailbox` for the + daemon-owned channel process. Cleanup clears that mailbox handle, publishes `cfg.Swap.Backend`/`CreditServer`/`CreditDaemon` bridges, registers the gRPC subserver, calls `resumePending` (unless `cfg.Swap.SuppressResume`), and returns a cleanup function. @@ -69,6 +77,8 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`. - **Depends on**: `sdk/swaps` (swap FSM, `SwapClient`, `Store`, session, credit types), `sdk/ark` (`WrapDaemonServer`, in-process Ark facade), + `arkchannel` (channel IDs returned by the payment bridge), `mailbox/pb` + (method identities used by reconnect admission), `waved` (`RPCServer`, `Config`, `SwapConfig`, `SwapSubsystem`), `credit` (`CreditServer`/`CreditDaemon` interfaces bridged for the credit actor subsystem), `rpc/swapclientrpc` (generated gRPC stubs + proto types). @@ -88,6 +98,13 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`. - Worker ownership is process-local and mutex-guarded: at most one goroutine drives a given payment hash at any time. `markActive` is the admission gate; `markInactive` releases it on goroutine exit. +- A process-local resume or `Wait` error is not itself terminal. The worker + reads the durable summary and retries while the FSM remains pending; it + releases ownership only after terminal state, successful completion, missing + durable state, or daemon shutdown. `runSwapWorker` is the shared retry loop + for both directions; `workerRetryDelay` defaults to one second and remains a + service field so tests can shorten it without moving retry policy into the + swap FSM. - The daemon uses `rootCtx` (not the individual RPC contexts) for all `ResumePayViaLightning` / `ResumeReceiveViaLightning` calls. A CLI disconnect does not cancel an admitted swap. @@ -139,6 +156,15 @@ protocol behavior remain entirely inside `sdk/swaps` and `swapdk-server`. "no filesystem here". It mirrors `waved.ensureDataDir`; keep the two in step, since a Node host given an unwritable path should fail there rather than at the first database open. +- `swapServerOperationWaitsForReady` enables gRPC reconnect waiting only for + methods that create or advance durable protocol state. Mailbox `Send` is + included because a receive acknowledgement must survive a reconnect; + mailbox `Pull`, quote RPCs, and credit snapshots remain fail-fast. New + state-changing RPCs must be classified explicitly. +- `StartReceive(active_channel_only=true)` requires the opt-in daemon bridge. + It must reserve an existing active channel or fail without an invoice. + An ordinary `StartReceive` never calls the channel bridge, even when the + daemon flag is enabled. - `SetOutSwapEventReceiver` must run before any receive worker is started: `SwapClient` captures the receiver into the per-swap worker at start time, so a late install would leave already-running workers using whatever diff --git a/swapclientserver/ark_channel_bridge.go b/swapclientserver/ark_channel_bridge.go new file mode 100644 index 000000000..b68f5a211 --- /dev/null +++ b/swapclientserver/ark_channel_bridge.go @@ -0,0 +1,58 @@ +package swapclientserver + +import ( + "context" + + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/sdk/swaps" + "github.com/lightninglabs/wavelength/waved" + "github.com/lightningnetwork/lnd/lntypes" +) + +// arkChannelPaymentBridge adapts the swap SDK to waved's process-owned native +// lnd channel controller without introducing an in-process gRPC loop. +type arkChannelPaymentBridge struct { + rpc *waved.RPCServer +} + +// PrepareIncomingPayment installs the known-preimage native invoice. +func (b *arkChannelPaymentBridge) PrepareIncomingPayment(ctx context.Context, + preimage lntypes.Preimage, amount btcutil.Amount) error { + + return b.rpc.PrepareArkChannelIncomingPayment(ctx, preimage, amount) +} + +// RegisterIncomingPayment binds the public future SCID at the hub and returns +// the minimum CLTV delta in blocks required by its private channel payment. +func (b *arkChannelPaymentBridge) RegisterIncomingPayment(ctx context.Context, + hash lntypes.Hash, amount btcutil.Amount, reservedSCID uint64) ( + arkchannel.ID, uint32, error) { + + return b.rpc.RegisterArkChannelIncomingPayment( + ctx, hash, amount, reservedSCID, + ) +} + +// WaitIncomingPayment waits for private lnd acceptance and channel activation. +func (b *arkChannelPaymentBridge) WaitIncomingPayment(ctx context.Context, + hash lntypes.Hash) (arkchannel.ID, error) { + + return b.rpc.WaitArkChannelIncomingPayment(ctx, hash) +} + +// SettleIncomingPayment releases the selected private hold invoice. +func (b *arkChannelPaymentBridge) SettleIncomingPayment(ctx context.Context, + preimage lntypes.Preimage) error { + + return b.rpc.SettleArkChannelIncomingPayment(ctx, preimage) +} + +// CancelIncomingPayment releases the registration and private hold invoice. +func (b *arkChannelPaymentBridge) CancelIncomingPayment(ctx context.Context, + hash lntypes.Hash, reason string) error { + + return b.rpc.CancelArkChannelIncomingPayment(ctx, hash, reason) +} + +var _ swaps.ArkChannelPaymentBridge = (*arkChannelPaymentBridge)(nil) diff --git a/swapclientserver/service.go b/swapclientserver/service.go index 2e488817f..1927fe2fb 100644 --- a/swapclientserver/service.go +++ b/swapclientserver/service.go @@ -299,7 +299,8 @@ type swapRuntimeClient interface { // invoice that callers hand to the remote payer. A non-empty request // ID is stored with the receive and may own only one receive. StartReceiveViaLightning(ctx context.Context, requestID string, - amount btcutil.Amount, memo string) (receiveSwapSession, error) + amount btcutil.Amount, memo string, + activeChannelOnly bool) (receiveSwapSession, error) // ReceiveSummaryByRequestID reads the receive created under a request // ID, or returns swaps.ErrSwapSummaryNotFound. @@ -549,7 +550,7 @@ func RegisterGateway(ctx context.Context, mux *runtime.ServeMux, // must be called during daemon shutdown so the root worker context is canceled // before the Ark, swapdk-server, and store resources are closed. // -//nolint:contextcheck +//nolint:contextcheck,funlen // Startup owns reverse-order cleanup. func newSwapClientService(ctx context.Context, rpcServer *waved.RPCServer, daemonCfg *waved.Config) (*swapClientService, func(), error) { @@ -612,7 +613,6 @@ func newSwapClientService(ctx context.Context, rpcServer *waved.RPCServer, return nil, nil, err } - arkClient, err := sdkark.WrapDaemonServer(ctx, sdkark.InProcessConfig{ DaemonServer: rpcServer, }) @@ -653,6 +653,9 @@ func newSwapClientService(ctx context.Context, rpcServer *waved.RPCServer, swapClients.server, daemonConn, log, invoiceGen, store, ) swapClient.SetChainParams(chainParams) + configureArkChannelReceiveBridge( + swapClient, rpcServer, cfg, + ) recoveryCfg := cfg.VHTLCRecovery swapClient.SetRecoveryPolicy(swaps.RecoveryPolicy{ AutoEscalate: recoveryCfg.AutoEscalate, @@ -747,6 +750,22 @@ func newSwapClientService(ctx context.Context, rpcServer *waved.RPCServer, return service, cleanup, nil } +// arkChannelPaymentBridgeSetter is the narrow SDK wiring surface needed by the +// direct receive opt-in. +type arkChannelPaymentBridgeSetter interface { + SetArkChannelPaymentBridge(swaps.ArkChannelPaymentBridge, bool) +} + +// configureArkChannelReceiveBridge keeps the bridge available for recovery +// while new invoices require an explicit opt-in. +func configureArkChannelReceiveBridge(client arkChannelPaymentBridgeSetter, + rpcServer *waved.RPCServer, cfg *waved.SwapConfig) { + + client.SetArkChannelPaymentBridge(&arkChannelPaymentBridge{ + rpc: rpcServer, + }, cfg.ArkChannelsEnabled && !cfg.SuppressArkChannelRuntime) +} + // bindArkChannelMailbox publishes the authenticated swap-server transport for // the daemon-owned channel process and returns its matching release function. func bindArkChannelMailbox(cfg *waved.SwapConfig, @@ -982,12 +1001,20 @@ func (a *swapClientAdapter) ListCredits(ctx context.Context, limit uint32) ( // StartReceiveViaLightning starts a real sdk/swaps receive session and wraps // it with method accessors for the daemon RPC response path. func (a *swapClientAdapter) StartReceiveViaLightning(ctx context.Context, - requestID string, amountSat btcutil.Amount, memo string) ( - receiveSwapSession, error) { + requestID string, amountSat btcutil.Amount, memo string, + activeChannelOnly bool) (receiveSwapSession, error) { - session, err := a.client.StartReceiveWithRequestID( - ctx, requestID, amountSat, memo, - ) + var session *swaps.ReceiveSession + var err error + if activeChannelOnly { + session, err = a.client.StartReceiveViaArkChannel( + ctx, amountSat, memo, + ) + } else { + session, err = a.client.StartReceiveWithRequestID( + ctx, requestID, amountSat, memo, + ) + } if err != nil { return nil, err } @@ -1222,11 +1249,11 @@ func swapServerDialOptions(cfg *waved.SwapConfig, addr string, } } -// swapServerWaitForReadyInterceptor applies reconnect waiting only to swap -// operations that create or advance protocol state. User operations remain -// bounded by their request context, while background resume operations remain -// bounded by the daemon root context. Read-only quotes and credit snapshots -// retain gRPC's fail-fast behavior. +// swapServerWaitForReadyInterceptor applies reconnect waiting only to swap and +// mailbox operations that create or advance protocol state. User operations +// remain bounded by their request context, while background resume operations +// remain bounded by the daemon root context. Read-only quotes, mailbox pulls, +// and credit snapshots retain gRPC's fail-fast behavior. func swapServerWaitForReadyInterceptor(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { @@ -1243,7 +1270,8 @@ func swapServerWaitForReadyInterceptor(ctx context.Context, method string, req, // reconnects. func swapServerOperationWaitsForReady(method string) bool { switch method { - case swaprpc.SwapService_RequestChannelId_FullMethodName, + case mailboxpb.MailboxService_Send_FullMethodName, + swaprpc.SwapService_RequestChannelId_FullMethodName, swaprpc.SwapService_CreateInSwap_FullMethodName, swaprpc.SwapService_CreateCredit_FullMethodName, swaprpc.SwapService_RedeemCredit_FullMethodName, @@ -1813,6 +1841,12 @@ func (s *swapClientService) StartReceive(ctx context.Context, codes.InvalidArgument, "amount_sat must be positive", ) } + if req.GetActiveChannelOnly() && req.GetIdempotencyKey() != "" { + return nil, status.Error( + codes.Unimplemented, + "keyed active-channel receives are unsupported", + ) + } if !s.reserveReceiveWorker() { return nil, status.Errorf(codes.ResourceExhausted, "active "+ "receive swap limit of %d reached", s.maxActiveReceives) @@ -1830,6 +1864,7 @@ func (s *swapClientService) StartReceive(ctx context.Context, req.GetAmountSat(), ), req.GetMemo(), + req.GetActiveChannelOnly(), ) if err != nil { return nil, status.Errorf(codes.Internal, "start receive "+ @@ -1862,7 +1897,7 @@ func (s *swapClientService) StartReceive(ctx context.Context, } func receivePlanVHTLCAmount(summary *swapclientrpc.SwapSummary) uint64 { - if summary == nil { + if summary == nil || len(summary.GetChannelId()) != 0 { return 0 } if summary.GetVhtlcAmountSat() > 0 { @@ -2867,6 +2902,10 @@ func swapSummaryToProto(summary swaps.SwapSummary) *swapclientrpc.SwapSummary { if summary.Preimage != nil { preimage = hex.EncodeToString(summary.Preimage[:]) } + var channelID []byte + if summary.ChannelID != ([32]byte{}) { + channelID = append([]byte(nil), summary.ChannelID[:]...) + } return &swapclientrpc.SwapSummary{ Direction: swapDirectionToProto(summary.Direction), @@ -2898,6 +2937,8 @@ func swapSummaryToProto(summary swaps.SwapSummary) *swapclientrpc.SwapSummary { AttachedCreditSat: summary.AttachedCreditSat, DustLimitSat: summary.DustLimitSat, AvailableCreditSat: summary.AvailableCreditSat, + ChannelId: channelID, + ReservedScid: summary.ReservedSCID, } } @@ -3216,6 +3257,10 @@ func swapSettlementTypeToProto( case swaps.SettlementTypeMixed: return swapclientrpc.SwapSettlementType_SWAP_SETTLEMENT_TYPE_MIXED + case swaps.SettlementTypeArkChannel: + return swapclientrpc. + SwapSettlementType_SWAP_SETTLEMENT_TYPE_ARK_CHANNEL + default: return swapclientrpc. SwapSettlementType_SWAP_SETTLEMENT_TYPE_UNSPECIFIED diff --git a/swapclientserver/service_test.go b/swapclientserver/service_test.go index 8342dd9bb..d67effbe1 100644 --- a/swapclientserver/service_test.go +++ b/swapclientserver/service_test.go @@ -954,7 +954,7 @@ func TestStartReceiveReturnsInvoiceAndStartsWorker(t *testing.T) { resp, err := service.StartReceive( t.Context(), &swapclientrpc.StartReceiveRequest{ AmountSat: 50_000, - Memo: "coffee", + Memo: "coffee", ActiveChannelOnly: true, }, ) require.NoError(t, err) @@ -966,7 +966,18 @@ func TestStartReceiveReturnsInvoiceAndStartsWorker(t *testing.T) { fakeClient.awaitReceiveResume(t, receiveHash) require.Equal(t, 1, fakeClient.startReceiveCount()) require.Equal(t, "coffee", fakeClient.startReceiveMemo) + require.True(t, fakeClient.startActiveChannel) require.Equal(t, 1, fakeClient.receiveResumeCount(receiveHash)) + + _, err = service.StartReceive(t.Context(), + &swapclientrpc.StartReceiveRequest{ + AmountSat: 50_000, + ActiveChannelOnly: true, + IdempotencyKey: "ordinary-receive-key", + }, + ) + require.Equal(t, codes.Unimplemented, status.Code(err)) + require.Equal(t, 1, fakeClient.startReceiveCount()) } // TestStartReceiveReturnsCreditAssistedPlan verifies receive startup returns @@ -1287,7 +1298,9 @@ func TestSwapSummaryToProtoCopiesDurableFields(t *testing.T) { UpdatedAt: updatedAt, Deadline: deadline, RefundLocktime: 42, - SettlementType: swaps.SettlementTypeInArk, + SettlementType: swaps.SettlementTypeArkChannel, + ChannelID: [32]byte{7}, + ReservedSCID: 99, SenderPubkey: senderPubKey, }) @@ -1315,9 +1328,18 @@ func TestSwapSummaryToProtoCopiesDurableFields(t *testing.T) { require.Equal(t, deadline.Unix(), got.GetDeadlineUnix()) require.Equal(t, uint32(42), got.GetRefundLocktime()) require.Equal( - t, swapclientrpc.SwapSettlementType_SWAP_SETTLEMENT_TYPE_IN_ARK, + t, swapclientrpc. + SwapSettlementType_SWAP_SETTLEMENT_TYPE_ARK_CHANNEL, got.GetSettlementType(), ) + require.Equal( + t, + append( + []byte{7}, make([]byte, 31)..., + ), + got.GetChannelId(), + ) + require.Equal(t, uint64(99), got.GetReservedScid()) require.Equal(t, senderPubKeyHex, got.GetSenderPubkey()) } @@ -1362,6 +1384,58 @@ func TestBindArkChannelMailbox(t *testing.T) { require.Nil(t, cfg.ArkChannelMailbox) } +// recordingArkChannelBridgeSetter records whether daemon wiring exposes the +// optional direct receive bridge to the swap SDK. +type recordingArkChannelBridgeSetter struct { + bridge swaps.ArkChannelPaymentBridge + admit bool + calls int +} + +// SetArkChannelPaymentBridge records one bridge installation. +func (s *recordingArkChannelBridgeSetter) SetArkChannelPaymentBridge( + bridge swaps.ArkChannelPaymentBridge, admit bool) { + + s.bridge = bridge + s.admit = admit + s.calls++ +} + +// TestConfigureArkChannelReceiveBridgeRequiresOptIn keeps the recovery +// bridge available without admitting new invoices on a disabled runtime. +func TestConfigureArkChannelReceiveBridgeRequiresOptIn(t *testing.T) { + t.Parallel() + + rpcServer := waved.NewRPCServer(nil) + disabled := &recordingArkChannelBridgeSetter{} + configureArkChannelReceiveBridge( + disabled, rpcServer, &waved.SwapConfig{}, + ) + require.Equal(t, 1, disabled.calls) + require.NotNil(t, disabled.bridge) + require.False(t, disabled.admit) + + enabled := &recordingArkChannelBridgeSetter{} + configureArkChannelReceiveBridge(enabled, rpcServer, &waved.SwapConfig{ + ArkChannelsEnabled: true, + }) + require.Equal(t, 1, enabled.calls) + require.True(t, enabled.admit) + bridge, ok := enabled.bridge.(*arkChannelPaymentBridge) + require.True(t, ok) + require.Same(t, rpcServer, bridge.rpc) + + suppressed := &recordingArkChannelBridgeSetter{} + configureArkChannelReceiveBridge( + suppressed, rpcServer, &waved.SwapConfig{ + ArkChannelsEnabled: true, + SuppressArkChannelRuntime: true, + }, + ) + require.NotNil(t, suppressed.bridge) + require.False(t, suppressed.admit) +} + // TestDaemonWithLiveOperatorKeyUsesLiveFetcher verifies the daemon-hosted swap // runtime bypasses the Ark SDK facade's cached operator key. func TestDaemonWithLiveOperatorKeyUsesLiveFetcher(t *testing.T) { @@ -1765,8 +1839,13 @@ func TestSwapServerOperationWaitsForReady(t *testing.T) { method: swaprpc.SwapService_ListCredits_FullMethodName, }, { - name: "mailbox", - method: "/mailboxrpc.MailboxService/Pull", + name: "mailbox send", + method: mailboxpb.MailboxService_Send_FullMethodName, + wait: true, + }, + { + name: "mailbox pull", + method: mailboxpb.MailboxService_Pull_FullMethodName, }, { name: "future swap method", @@ -2001,6 +2080,7 @@ type fakeSwapRuntime struct { startReceiveRequestID string receiveByRequestID map[string]swaps.SwapSummary + startActiveChannel bool startReceiveHook func() createCreditCalls int createCreditReq swaps.CreateCreditRequest @@ -2068,8 +2148,8 @@ func (f *fakeSwapRuntime) StartPayViaLightning(_ context.Context, _ string, } func (f *fakeSwapRuntime) StartReceiveViaLightning(_ context.Context, - requestID string, _ btcutil.Amount, memo string) (receiveSwapSession, - error) { + requestID string, _ btcutil.Amount, memo string, activeChannel bool) ( + receiveSwapSession, error) { f.mu.Lock() defer f.mu.Unlock() @@ -2077,6 +2157,7 @@ func (f *fakeSwapRuntime) StartReceiveViaLightning(_ context.Context, f.startReceiveCalls++ f.startReceiveMemo = memo f.startReceiveRequestID = requestID + f.startActiveChannel = activeChannel if f.startReceiveHook != nil { f.startReceiveHook() } diff --git a/swapwallet/inspection.go b/swapwallet/inspection.go index d1468a053..01e4aca01 100644 --- a/swapwallet/inspection.go +++ b/swapwallet/inspection.go @@ -578,6 +578,8 @@ func swapTraceFromSummary( ), SenderPubkey: swap.GetSenderPubkey(), Preimage: swap.GetPreimage(), + ChannelId: swap.GetChannelId(), + ReservedScid: swap.GetReservedScid(), } } diff --git a/swapwallet/inspection_test.go b/swapwallet/inspection_test.go index 30f393ff8..c1e8334fc 100644 --- a/swapwallet/inspection_test.go +++ b/swapwallet/inspection_test.go @@ -42,6 +42,7 @@ func TestInspectActivityShowsPayFundingTrace(t *testing.T) { sessionID := testBytes(32, 0x21) sessionHex := testSessionString(t, sessionID) + channelID := testBytes(32, 0x31) swap.listSwapsResp = &swapclientrpc.ListSwapsResponse{ Swaps: []*swapclientrpc.SwapSummary{ @@ -59,6 +60,8 @@ func TestInspectActivityShowsPayFundingTrace(t *testing.T) { VhtlcAmountSat: 1_234, UpdatedAtUnix: 200, FundingSessionId: sessionHex, + ChannelId: channelID, + ReservedScid: 1234, }, }, } @@ -103,6 +106,8 @@ func TestInspectActivityShowsPayFundingTrace(t *testing.T) { ) require.Equal(t, "sender-pubkey", resp.GetSwap().GetSenderPubkey()) require.Equal(t, "deadbeef", resp.GetSwap().GetPreimage()) + require.Equal(t, channelID, resp.GetSwap().GetChannelId()) + require.Equal(t, uint64(1234), resp.GetSwap().GetReservedScid()) require.Len(t, resp.GetLedgerRows(), 2) require.Len(t, resp.GetVtxos(), 3) diff --git a/swapwallet/recv.go b/swapwallet/recv.go index 29d95f54e..ccc643d62 100644 --- a/swapwallet/recv.go +++ b/swapwallet/recv.go @@ -49,6 +49,13 @@ func newReceiver(deps *Deps, runtime *Runtime) *receiver { func (r *receiver) Recv(ctx context.Context, req *wavewalletrpc.RecvRequest) ( *wavewalletrpc.RecvResponse, error) { + return r.receive(ctx, req, false) +} + +// receive applies wallet amount validation before selecting the requested rail. +func (r *receiver) receive(ctx context.Context, req *wavewalletrpc.RecvRequest, + activeChannelOnly bool) (*wavewalletrpc.RecvResponse, error) { + if r == nil || r.deps == nil || r.deps.SwapService == nil { return nil, ErrSwapBackendUnavailable } @@ -64,6 +71,20 @@ func (r *receiver) Recv(ctx context.Context, req *wavewalletrpc.RecvRequest) ( ErrAmountInvalid) } + // A channel receive credits existing liquidity, not a new wallet VTXO. + // The channel backend enforces inbound capacity; never fall back to + // credit, even when the invoice is below the operator's VTXO floor. + if activeChannelOnly { + if req.GetRequestId() != "" { + return nil, status.Error( + codes.Unimplemented, + "keyed active-channel receives are unsupported", + ) + } + + return r.startReceive(ctx, req, true) + } + // A keyed receive first reads what the key already owns. Routing // depends on live credit balance and operator terms, so a retry could // otherwise land on the other backend and create a second invoice. @@ -147,11 +168,20 @@ func (r *receiver) Recv(ctx context.Context, req *wavewalletrpc.RecvRequest) ( } } + return r.startReceive(ctx, req, false) +} + +// startReceive projects the invoice returned by the requested backend. +func (r *receiver) startReceive(ctx context.Context, + req *wavewalletrpc.RecvRequest, activeChannelOnly bool) ( + *wavewalletrpc.RecvResponse, error) { + startResp, err := r.deps.SwapService.StartReceive( ctx, &swapclientrpc.StartReceiveRequest{ - AmountSat: int64(amt), - Memo: req.GetMemo(), - IdempotencyKey: requestID, + AmountSat: int64(req.GetAmtSat()), + Memo: req.GetMemo(), + ActiveChannelOnly: activeChannelOnly, + IdempotencyKey: req.GetRequestId(), }, ) if err != nil { diff --git a/swapwallet/recv_test.go b/swapwallet/recv_test.go index 6ffdba96d..ae9a7b463 100644 --- a/swapwallet/recv_test.go +++ b/swapwallet/recv_test.go @@ -58,6 +58,7 @@ func TestRecvDispatchesStartReceive(t *testing.T) { require.NoError(t, err) require.Equal(t, 1, swap.startReceiveCalls) require.Equal(t, "coffee", swap.startReceiveLast.GetMemo()) + require.False(t, swap.startReceiveLast.GetActiveChannelOnly()) require.Equal(t, "lnbc1invoice", resp.GetInvoice()) require.Equal(t, "abc123", resp.GetEntry().GetId()) require.Equal(t, "coffee", resp.GetEntry().GetNote()) @@ -81,6 +82,52 @@ func TestRecvDispatchesStartReceive(t *testing.T) { ) } +// TestRecvOnActiveChannelDispatch requires the channel rail even below the +// VTXO floor. A rejected request must not issue an invoice on another rail. +func TestRecvOnActiveChannelDispatch(t *testing.T) { + t.Parallel() + r, swap := newRecvFixture(t) + credit := &fakeCreditRegistry{} + r.deps.CreditRegistry = credit + r.deps.RPCServer = &fakeRPCServer{ + getInfoResp: &waverpc.GetInfoResponse{ + WalletState: waverpc.WalletState_WALLET_STATE_READY, + ServerInfo: &waverpc.ServerInfo{ + MinVtxoAmountSat: 10_000, + }, + }, + } + svc := newService(r.deps, r.runtime) + req := &wavewalletrpc.RecvRequest{AmtSat: 1000, Memo: "channel"} + swap.startReceiveResp = &swapclientrpc.StartReceiveResponse{ + Invoice: "channel-invoice", + Swap: &swapclientrpc.SwapSummary{ + PaymentHash: "aabb", + }, + } + result, err := svc.RecvOnActiveChannel(t.Context(), req) + require.NoError(t, err) + require.Equal(t, "channel-invoice", result.GetInvoice()) + require.Equal(t, "aabb", result.GetEntry().GetId()) + require.True(t, swap.startReceiveLast.GetActiveChannelOnly()) + require.Equal(t, int64(1000), swap.startReceiveLast.GetAmountSat()) + require.Equal(t, "channel", swap.startReceiveLast.GetMemo()) + + swap.startReceiveErr = status.Error( + codes.FailedPrecondition, "no inbound", + ) + result, err = svc.RecvOnActiveChannel(t.Context(), req) + require.Nil(t, result) + require.Equal(t, codes.FailedPrecondition, status.Code(err)) + req.RequestId = "ordinary-receive-key" + result, err = svc.RecvOnActiveChannel(t.Context(), req) + require.Nil(t, result) + require.Equal(t, codes.Unimplemented, status.Code(err)) + require.Equal(t, 2, swap.startReceiveCalls) + require.Zero(t, swap.listCreditsCalls) + require.Zero(t, credit.receiveCalls) +} + // TestRecvProjectsPendingEntry confirms a swap-backed RECV projects its // pending row on dispatch, keyed by payment hash, before Recv returns. func TestRecvProjectsPendingEntry(t *testing.T) { diff --git a/swapwallet/service.go b/swapwallet/service.go index 980249b77..5b4e264c2 100644 --- a/swapwallet/service.go +++ b/swapwallet/service.go @@ -202,6 +202,17 @@ func (s *Service) LookupRecv(ctx context.Context, return s.recv.LookupRecv(ctx, req) } +// RecvOnActiveChannel issues an invoice only against existing inbound capacity. +func (s *Service) RecvOnActiveChannel(ctx context.Context, + req *wavewalletrpc.RecvRequest) (*wavewalletrpc.RecvResponse, error) { + + if err := s.requireWalletReady(ctx); err != nil { + return nil, err + } + + return s.recv.receive(ctx, req, true) +} + // List returns the unified, normalized wallet history merged across the // swap subserver and the daemon's ledger/sweep stores. func (s *Service) List(ctx context.Context, req *wavewalletrpc.ListRequest) ( From 631755fef433ee48dd6d2ed07e92b28a12043076 Mon Sep 17 00:00:00 2001 From: sputn1ck Date: Tue, 24 Nov 2026 17:49:50 +0100 Subject: [PATCH 5/5] sdk: Expose explicit channel actions to wallet hosts Pass the same default-off admission option through embedded Go, mobile and WASM. A wallet that omits it still protects durable channel state; ordinary invoice and payment APIs do not change their rail. --- .github/workflows/mobile-bindings.yml | 16 ++ cmd/wavewalletdk-wasm/ark_channel_test.go | 137 ++++++++++ cmd/wavewalletdk-wasm/main.go | 19 +- docs/ark-channel-lifecycle.md | 66 +++++ docs/index.md | 1 + docs/wavewalletdk_integration.md | 40 +++ docs/wavewalletdk_mobile.md | 56 +++++ sdk/wavewalletdk/ark_channel.go | 122 +++++++++ sdk/wavewalletdk/ark_channel_config_test.go | 85 +++++++ sdk/wavewalletdk/client.go | 26 +- sdk/wavewalletdk/embedded.go | 6 +- sdk/wavewalletdk/embedded_config.go | 6 + sdk/wavewalletdk/invoice_test.go | 8 +- sdk/wavewalletdk/mobile/ark_channel.go | 43 ++++ sdk/wavewalletdk/mobile/ark_channel_test.go | 237 ++++++++++++++++++ sdk/wavewalletdk/mobile/config.go | 2 + .../mobile/external_seed_wallet_test.go | 14 ++ sdk/wavewalletdk/mobile/mobile_test.go | 23 ++ sdk/wavewalletdk/mobile/wallet.go | 17 +- sdk/wavewalletdk/options_test.go | 44 ++++ sdk/wavewalletdk/restclient_test.go | 66 +++++ sdk/wavewalletdk/swapruntime.go | 31 ++- sdk/wavewalletdk/swapruntime_stub.go | 6 +- sdk/wavewalletdk/wavewalletrpc_stub_test.go | 4 + swaprpc/AGENTS.md | 7 +- swaprpc/CLAUDE.md | 7 +- 26 files changed, 1072 insertions(+), 17 deletions(-) create mode 100644 cmd/wavewalletdk-wasm/ark_channel_test.go create mode 100644 docs/ark-channel-lifecycle.md create mode 100644 sdk/wavewalletdk/ark_channel.go create mode 100644 sdk/wavewalletdk/ark_channel_config_test.go create mode 100644 sdk/wavewalletdk/mobile/ark_channel.go create mode 100644 sdk/wavewalletdk/mobile/ark_channel_test.go diff --git a/.github/workflows/mobile-bindings.yml b/.github/workflows/mobile-bindings.yml index a755dbeb9..407bad96e 100644 --- a/.github/workflows/mobile-bindings.yml +++ b/.github/workflows/mobile-bindings.yml @@ -26,6 +26,12 @@ on: pull_request: paths: - "sdk/wavewalletdk/**" + - "cmd/wavewalletdk-wasm/**" + - "arkchannel/**" + - "lnruntime/**" + - "rpc/arkchannelrpc/**" + - "rpc/wavewalletrpc/**" + - "waved/*ark_channel*" - "sdk/swaps/**" - "db/**" - "lwwallet/**" @@ -125,6 +131,16 @@ jobs: -exec="$(go env GOROOT)/lib/wasm/go_js_wasm_exec" \ -run '^TestWASM.*OpenRetry$' ./db ./lwwallet + - name: Test channel bindings and persistent storage under WASM + if: matrix.sqlite == 'host' + run: | + go mod download github.com/lightninglabs/go-wasmsqlite + sqlite_dir=$(go list -m -f '{{.Dir}}' github.com/lightninglabs/go-wasmsqlite) + GOOS=js GOARCH=wasm go test -tags="${MOBILE_TAGS}" \ + -exec="node ${sqlite_dir}/scripts/node-wasm-test-exec.cjs" \ + -run '^Test(ChannelSQLReopen|WASMArkChannelDispatch|ArkChannelBindingDispatch)$' \ + ./db ./cmd/wavewalletdk-wasm ./sdk/wavewalletdk/mobile + - name: Test mobile facade and SQLite stores env: SQLITE_TAGS: ${{ matrix.tags }} diff --git a/cmd/wavewalletdk-wasm/ark_channel_test.go b/cmd/wavewalletdk-wasm/ark_channel_test.go new file mode 100644 index 000000000..bee869f49 --- /dev/null +++ b/cmd/wavewalletdk-wasm/ark_channel_test.go @@ -0,0 +1,137 @@ +//go:build js && wasm + +package main + +import ( + "errors" + "syscall/js" + "testing" + + "github.com/stretchr/testify/require" +) + +// callWalletJS invokes the registered function from JS and waits for its +// Promise, retaining both callbacks until the Promise settles. +func callWalletJS(method string, body map[string]any) (js.Value, error) { + type result struct { + value js.Value + err error + } + done := make(chan result, 1) + resolve := js.FuncOf(func(_ js.Value, args []js.Value) any { + done <- result{value: args[0]} + + return nil + }) + defer resolve.Release() + reject := js.FuncOf(func(_ js.Value, args []js.Value) any { + done <- result{err: errors.New(args[0].Get("message").String())} + + return nil + }) + defer reject.Release() + js.Global().Call("wavewalletdkCall", method, body).Call( + "then", resolve, reject, + ) + res := <-done + + return res.value, res.err +} + +// TestWASMArkChannelDispatch runs the JS -> mobile -> embedded RPC path on a +// fresh wallet. Specific handler rejections prove that valid request fields +// reached a registered RPC; unknown verbs or generic failures do not suffice. +func TestWASMArkChannelDispatch(t *testing.T) { + call := installWalletCall() + defer call.Release() + cfg := map[string]any{ + "data_dir": t.TempDir(), + "network": "regtest", + "wallet_type": "lwwallet", + "wallet_esplora_url": "http://127.0.0.1:1", + "server_address": "http://127.0.0.1:1", + "server_transport": "rest", + "server_insecure": true, + "swap_server_address": "http://127.0.0.1:1", + "swap_server_transport": "rest", + "swap_server_insecure": true, + } + _, err := callWalletJS("start", cfg) + require.NoError(t, err) + _, err = callWalletJS("promoteVTXO", map[string]any{ + "AmountSat": 5000, "IdempotencyKey": "not-admitted", + }) + require.ErrorContains(t, err, "operations are disabled") + _, err = callWalletJS("payOnActiveChannel", map[string]any{ + "Invoice": "ln-pay", + }) + require.ErrorContains(t, err, "operations are disabled") + _, err = callWalletJS("stop", nil) + require.NoError(t, err) + cfg["ark_channels_enabled"] = true + _, err = callWalletJS("start", cfg) + require.NoError(t, err) + defer func() { + _, err := callWalletJS("stop", nil) + require.NoError(t, err) + }() + + for _, tc := range []struct { + method string + req map[string]any + want string + }{ + { + "promoteVTXO", + map[string]any{ + "AmountSat": 5000, + }, + "idempotency key is required", + }, + { + "promoteVTXO", + map[string]any{ + "AmountSat": 5000, + "IdempotencyKey": "one", + }, + "runtime is not ready", + }, + { + "payOnActiveChannel", + map[string]any{}, + "payment request is required", + }, + { + "payOnActiveChannel", + map[string]any{ + "Invoice": "ln-pay", + "MaxFeeSat": 1, + }, + "runtime is not ready", + }, + { + "receiveOnActiveChannel", + map[string]any{ + "AmountSat": 5000, + }, + "create active-channel receive invoice:", + }, + { + "receive", + map[string]any{ + "AmountSat": 5000, + }, + "create receive invoice:", + }, + } { + t.Run(tc.method, func(t *testing.T) { + _, err := callWalletJS(tc.method, tc.req) + require.ErrorContains(t, err, tc.want) + if tc.method == "receive" || tc.method == "receiveOnActiveChannel" { + require.ErrorContains( + t, err, "wallet is not ready", + ) + } + }) + } +} diff --git a/cmd/wavewalletdk-wasm/main.go b/cmd/wavewalletdk-wasm/main.go index 2c959c38f..cbb5da54d 100644 --- a/cmd/wavewalletdk-wasm/main.go +++ b/cmd/wavewalletdk-wasm/main.go @@ -27,7 +27,7 @@ import ( // main installs the private browser transport entry point and then parks the Go // runtime so the exported callbacks stay live for the lifetime of the page. func main() { - js.Global().Set("wavewalletdkCall", js.FuncOf(walletCall)) + installWalletCall() js.Global().Call("dispatchEvent", js.Global().Get("CustomEvent").New( "wavewalletdk-ready", )) @@ -35,6 +35,14 @@ func main() { select {} } +// installWalletCall exposes the dispatch callback for the lifetime of the VM. +func installWalletCall() js.Func { + call := js.FuncOf(walletCall) + js.Global().Set("wavewalletdkCall", call) + + return call +} + // walletCall is the private JS transport dispatcher used by a typed host SDK. // It takes a method name and an optional request object and returns a Promise // that resolves with the verb's JSON response decoded into a JS value (or @@ -135,6 +143,15 @@ func walletCall(_ js.Value, args []js.Value) any { case "lookupReceive": return promise(jsonVerb(req, mobile.LookupReceive)) + case "promoteVTXO": + return promise(jsonVerb(req, mobile.PromoteVTXO)) + + case "receiveOnActiveChannel": + return promise(jsonVerb(req, mobile.ReceiveOnActiveChannel)) + + case "payOnActiveChannel": + return promise(jsonVerb(req, mobile.PayOnActiveChannel)) + case "prepareSend": return promise(jsonVerb(req, mobile.PrepareSend)) diff --git a/docs/ark-channel-lifecycle.md b/docs/ark-channel-lifecycle.md new file mode 100644 index 000000000..80e09a2ea --- /dev/null +++ b/docs/ark-channel-lifecycle.md @@ -0,0 +1,66 @@ +# Ark channels: open first, pay on an active channel + +Opening a channel and receiving a payment are separate operations. The client +can promote wallet VTXOs through the prepared out-of-round (OOR) transfer. +The funding wallet must not release that transfer until both lnd endpoints +have enforceable commitments and the signed VTXO-to-channel backing. Neither +the funding script nor its delays change. + +Only the client opens the channel. It uses the authenticated hub mailbox to +register the promotion, coordinate signatures, and install the finalized +source recovery package. The separate Lightning peer transport carries lnd's +opening messages, commitment updates, and reestablishment in both directions. +After installation, either endpoint can materialize and force close using its +own durable state without a request to the other. + +An invoice can use an existing channel with inbound capacity. Selecting that +channel does not reserve its balance until the payer arrives. If capacity +changes, the payment can fail; it cannot fund a new channel or switch to a +vHTLC under the same invoice. A wallet without a suitable channel can receive +through the ordinary vHTLC flow and later promote its wallet funds. + +## Cooperative settlement + +1. The client asks for the hub's payout destination and saves both destinations. + This first query does not stop either link. +2. The client quiesces its lnd link and proposes the payout from its clean + commitment. The hub checks its own clean lnd balances, commitment height, + source, and destination. It saves the exact signed authorization before + returning it. A lost signing reply is not permission to reopen the link. +3. The client saves the authorization and returns a digest of the two hub + signatures. The unsigned transaction ID would not prove receipt. Only + then may the client submit the 3-of-3 spend through the usual OOR flow. +4. The client records the completed OOR and reports its ID. A hub with a + payout checks the wallet's completed OOR session for its exact output, + not today's list of spendable VTXOs. A hub without a payout needs the + authenticated client report. Each endpoint archives its own lnd record. + No subsequent acknowledgment of local archival is needed. + +This close unrolls nothing. The wallets retain their replacement VTXOs and +ancestry watches. On a force close, Ark instead materializes the pre-agreed +funding outpoint. lnd's chain arbitrator and sweeper resolve the channel. + +## Two boundaries to keep + +**Transport.** Ark commands still need authenticated, durable delivery. A +retry of an exact close proposal, signature receipt, or OOR result goes to +the channel FSM, not a second execution journal. An unsigned abort is +different: a delayed duplicate must not abort a later attempt. + +A live connection for Lightning frames is a separate transport change. +The current sender promises durable admission; a WebSocket write cannot +satisfy that promise. A replacement could carry ordered binary frames over +an outbound authenticated connection, bind it to one peer, fence its old +connection on resume, and start with lnd's channel reestablishment. Only +then could it replace the per-frame mailbox and ingress receipts. It would +not replace durable Ark commands, lnd's circuit database, or chain watches +while a device sleeps. + +**Forwarding.** SwapDK's public lnd is reached through RPC; its private Ark +links share a different in-process lnd switch. The payment bridge therefore +still owns the relationship between two HTLCs, including their hash, nested +deadlines, and settlement after restart. To remove the bridge, the operator +would need to host its public and Ark links in the same switch and circuit +database, with consistent peer identities, channel aliases, fees, and +onion forwarding. That experiment belongs on the operator. It needs no +second switch, public graph, or pathfinder in the client. diff --git a/docs/index.md b/docs/index.md index e308b333c..d718fe5a0 100644 --- a/docs/index.md +++ b/docs/index.md @@ -22,6 +22,7 @@ into specific topics below. | [sdk_layered_architecture.md](sdk_layered_architecture.md) | SDK layering rationale: `sdk/ark` facade, remote vs. embedded modes, `sdk/swaps` future direction | | [swap_system.md](swap_system.md) | End-to-end swap walkthrough: vHTLC tree (collaborative vs. unilateral-exit leaves), receive (out-swap) and pay (in-swap) flows, the off-chain-first cancellation/timeout recovery ladder, same-Ark p2p detection, swap-server RPCs, and proof-gated indexer authorization, with mermaid diagrams | | [wavewalletdk_integration.md](wavewalletdk_integration.md) | Basic `wavewalletdk` integration flow, startup/config examples, swap accounting, and wrapper guidance | +| [ark-channel-lifecycle.md](ark-channel-lifecycle.md) | Client promotion, active-channel payments, cooperative settlement and force close | | [canonical_activity_log_design.md](canonical_activity_log_design.md) | Design (#774): a canonical store with stable cross-restart ids replacing the derive-on-read activity feed — a current-state `activity_entries` projection plus an append-only, sequence-numbered `activity_events` log (mailbox-style cursor) for resumable subscribe; foundation of the event-log epic (#776) | | [wavewalletrpc_build.md](wavewalletrpc_build.md) | How to build and install the daemon and CLI with the wallet RPC subserver enabled (`wavewalletrpc` + `swapruntime` tags) | | [exit_ancestry_export.md](exit_ancestry_export.md) | Signed ancestry bundle format and external CPFP executor contract | diff --git a/docs/wavewalletdk_integration.md b/docs/wavewalletdk_integration.md index 4eba2310f..2d87c2b1b 100644 --- a/docs/wavewalletdk_integration.md +++ b/docs/wavewalletdk_integration.md @@ -249,6 +249,46 @@ fmt.Println("entry:", send.Entry.ID, send.Entry.Status) fmt.Println("actual outflow:", send.ActualAmountSat) ``` +## Payments on an existing Ark channel + +Set `cfg.ArkChannelsEnabled = true` **before** `Start`. This mode needs +`lwwallet`, continuous mailbox ingress (not `HostDrivenIngress`), and a +channel-capable swap hub. For runtime builds, see the +[downstream dependency gate](wavewalletdk_mobile.md#ark-channel-operations). +Create or unlock the wallet and wait for +readiness. The daemon authenticates its operator and swap mailbox requests +with wallet-owned keys; the application does not supply a channel signer. + +1. **Fund outbound capacity.** Persist a distinct idempotency key for the + promotion, then call + `client.PromoteVTXO(ctx, wavewalletdk.PromoteVTXORequest{AmountSat: 50000, IdempotencyKey: key})`. + The wallet selects its VTXOs. The result identifies the channel by hex + `ChannelID`. After an uncertain result, use the **same** key and amount; + a fresh key asks for a second channel. +2. **Spend from the channel.** Call + `client.PayOnActiveChannel(ctx, wavewalletdk.PayOnActiveChannelRequest{Invoice: bolt11, MaxFeeSat: 10})`. + Success returns the payment hash, preimage, channel ID, private amount and + fee. Spending shifts balance to the hub side, creating inbound capacity. + Ordinary `PrepareSend` / `SendPrepared` do not spend this channel balance. +3. **Receive into the channel.** Call + `client.ReceiveOnActiveChannel(ctx, wavewalletdk.ReceiveRequest{AmountSat: 1000, Memo: "refund"})`. + Hand out the returned `Invoice` only on success. The hub needs an existing + active channel with sufficient inbound capacity; selection at invoice + creation does not reserve liquidity until payment. A rejection does not + create a channel, issue a vHTLC invoice, or start a credit receive. + +An ordinary `client.Receive` keeps the wallet's vHTLC and sub-floor credit +routing even with the channel runtime enabled. The distinct wallet RPC +`RecvOnActiveChannel` fails on an older daemon instead of silently creating +an ordinary invoice. Its HTTP route is `POST /v1/wallet/recv-on-active-channel`. +Promotion and channel pay use `ArkChannelService`, which is available over +embedded or remote gRPC, not remote HTTP. An embedded WASM wallet uses local +gRPC for these calls even though its operator and hub transports are REST. + +See [mobile binding requests](wavewalletdk_mobile.md#ark-channel-operations) +and the [channel lifecycle](ark-channel-lifecycle.md) for liquidity and +recovery semantics. + ## Native btcwallet RPC `BtcwalletRPC` exposes btcsuite btcwallet's native `walletrpc.WalletService` diff --git a/docs/wavewalletdk_mobile.md b/docs/wavewalletdk_mobile.md index cf97d5ae6..0ed9d4165 100644 --- a/docs/wavewalletdk_mobile.md +++ b/docs/wavewalletdk_mobile.md @@ -74,6 +74,55 @@ ABI. Its startup envelope is snake_case (`config`, `seed_entropy`, is the PascalCase `ExternalSeedWalletOpenResult`. Typed SDKs map their public request types onto this wire shape. +## Ark channel operations + +Set `"ark_channels_enabled": true` in the startup config (nested `config` +for `StartExternalSeedWallet`). Use `"wallet_type": "lwwallet"` and leave +`host_driven_ingress` off. In WASM set both `server_transport` and +`swap_server_transport` to `"rest"` and use browser-trusted HTTPS endpoints +in production; the browser cannot pin PEM files. Keep the wallet running +while serving invoices. + +The host sets this flag at wallet startup, not on an ordinary invoice. +Mobile and WASM both decode it into `wavewalletdk.Config.ArkChannelsEnabled`; +an embedded Go host may set that field directly. Omitted or false leaves +new channel operations disabled. Even with it set, only an explicit open +creates a channel. Existing obligations in the same data directory restore +without opting in again. + +**Downstream dependency gate.** A runtime flag cannot change the packages +compiled into a binary. For integration tests only, the main module building +a daemon, mobile binding, or WASM wallet must select both replacements: + +```go +replace github.com/lightningnetwork/lnd => github.com/sputn1ck/lnd v0.4.2-beta.0.20261124151740-0cc0299da78b +replace github.com/lightningnetwork/lnd/kvdb => github.com/sputn1ck/lnd/kvdb v0.0.0-20261124151740-0cc0299da78b +``` + +Go ignores replacements in dependencies. A client using an already-built RPC +service does not need either replacement. Neither does an application that +only imports the Wavelength policy parser. Do not ship either personal +replacement on a supported main branch. First land the required recovery +behavior upstream, select official versions of **both modules**, then build +native, mobile and WASM from an external module with no replacements and +`GOWORK=off`. Run both default mixed-version directions and the enabled +daemon suite on those versions. A fork-pinned pass or the original upstream +runtime proposal alone does not satisfy the release gate. + +| Go mobile binding | WASM worker method | Request JSON | +| --- | --- | --- | +| `PromoteVTXO` | `promoteVTXO` | `{"AmountSat":50000,"IdempotencyKey":"order-17-channel"}` | +| `PayOnActiveChannel` | `payOnActiveChannel` | `{"Invoice":"","MaxFeeSat":10}` | +| `ReceiveOnActiveChannel` | `receiveOnActiveChannel` | `{"AmountSat":1000,"Memo":"refund","TimeoutSeconds":30}` | + +The first result contains `ChannelID`, `Phase`, and `CapacitySat`. Channel pay +returns `PaymentHash`, `Preimage`, `ChannelID`, `PrivateAmountSat`, and +`FeeSat`. IDs and preimages are hex strings. Channel receive returns the same +invoice, entry and receipt reference as `Receive`, with the same deadline +and uncertainty contract. Never retry a timed-out payment on a different rail. +Neither receiving nor ordinary prepared sends will implicitly promote funds. +See the [ordered payment flow](wavewalletdk_integration.md#payments-on-an-existing-ark-channel). + ## Maximum send For an amountless BOLT-11 payment, `PrepareSend` accepts `MaxAmount: true` @@ -201,6 +250,13 @@ Empty `server_address` and `swap_server_address` values select the endpoint for the configured network and transport. They don't disable either service. Set the fields explicitly when a mobile host needs a custom or local endpoint. +The [Ark channel opt-in](#ark-channel-operations) maps to +`wavewalletdk.Config.ArkChannelsEnabled` in Go. Restart with it enabled, +on the same network and with the same `data_dir`, while channels are +outstanding. This lets the wallet reopen its channel state and resume peer +delivery. The default starts no embedded channel peer. Ordinary Lightning +receives use vHTLCs even with the peer enabled. + ```json { "data_dir": "/data/user/0//files/wavewalletdk", diff --git a/sdk/wavewalletdk/ark_channel.go b/sdk/wavewalletdk/ark_channel.go new file mode 100644 index 000000000..be731c6be --- /dev/null +++ b/sdk/wavewalletdk/ark_channel.go @@ -0,0 +1,122 @@ +package wavewalletdk + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/rpc/arkchannelrpc" +) + +// PromoteVTXORequest selects wallet liquidity to move into an Ark channel. +// Persist the idempotency key before dispatch and reuse it for the same intent. +type PromoteVTXORequest struct { + AmountSat int64 + IdempotencyKey string +} + +// PromoteVTXOResult identifies the channel and its durable lifecycle phase. +type PromoteVTXOResult struct { + ChannelID string + Phase string + CapacitySat int64 +} + +// PayOnActiveChannelRequest pays a BOLT-11 invoice from channel liquidity. +type PayOnActiveChannelRequest struct { + Invoice string + MaxFeeSat uint64 +} + +// PayOnActiveChannelResult reports the settled payment. IDs and the proof of +// payment are hex encoded. +type PayOnActiveChannelResult struct { + PaymentHash string + Preimage string + ChannelID string + PrivateAmountSat int64 + FeeSat int64 +} + +// channelRPC selects the authenticated daemon connection, including embedded +// bufconn. The daemon has no HTTP/JSON gateway for ArkChannelService. +func (c *Client) channelRPC() (arkchannelrpc.ArkChannelServiceClient, error) { + if c == nil || c.conn == nil { + return nil, errors.New("channel control requires embedded or " + + "gRPC transport") + } + + return arkchannelrpc.NewArkChannelServiceClient(c.conn), nil +} + +// PromoteVTXO moves existing wallet liquidity into an Ark-backed channel. +func (c *Client) PromoteVTXO(ctx context.Context, req PromoteVTXORequest) ( + *PromoteVTXOResult, error) { + + rpc, err := c.channelRPC() + if err != nil { + return nil, err + } + resp, err := rpc.PromoteVTXO(ctx, &arkchannelrpc.PromoteVTXORequest{ + AmountSat: req.AmountSat, + IdempotencyKey: req.IdempotencyKey, + }) + if err != nil { + return nil, fmt.Errorf("promote wallet VTXO: %w", err) + } + ch := resp.GetChannel() + if len(ch.GetChannelId()) != len(arkchannel.ID{}) { + return nil, errors.New("promotion returned an invalid " + + "channel ID") + } + + return &PromoteVTXOResult{ + ChannelID: hex.EncodeToString(ch.GetChannelId()), + Phase: ch.GetPhase(), + CapacitySat: ch.GetCapacitySat(), + }, nil +} + +// PayOnActiveChannel spends channel liquidity without changing the rail used +// by PrepareSend and SendPrepared. It never falls back to a wallet swap. +func (c *Client) PayOnActiveChannel(ctx context.Context, + req PayOnActiveChannelRequest) (*PayOnActiveChannelResult, error) { + + rpc, err := c.channelRPC() + if err != nil { + return nil, err + } + resp, err := rpc.PayLightningInvoice( + ctx, &arkchannelrpc.PayLightningInvoiceRequest{ + PaymentRequest: req.Invoice, + MaxFeeSat: req.MaxFeeSat, + }, + ) + if err != nil { + return nil, fmt.Errorf("pay on active channel: %w", err) + } + + if len(resp.GetChannelId()) != len(arkchannel.ID{}) { + return nil, errors.New("channel payment returned an invalid " + + "channel ID") + } + preimage := resp.GetPreimage() + hash := sha256.Sum256(preimage) + if len(preimage) != sha256.Size || + !bytes.Equal(hash[:], resp.GetPaymentHash()) { + return nil, errors.New("channel payment returned an invalid " + + "settlement proof") + } + + return &PayOnActiveChannelResult{ + PaymentHash: hex.EncodeToString(resp.GetPaymentHash()), + Preimage: hex.EncodeToString(resp.GetPreimage()), + ChannelID: hex.EncodeToString(resp.GetChannelId()), + PrivateAmountSat: resp.GetPrivateAmountSat(), + FeeSat: resp.GetFeeSat(), + }, nil +} diff --git a/sdk/wavewalletdk/ark_channel_config_test.go b/sdk/wavewalletdk/ark_channel_config_test.go new file mode 100644 index 000000000..a04166aed --- /dev/null +++ b/sdk/wavewalletdk/ark_channel_config_test.go @@ -0,0 +1,85 @@ +//go:build swapruntime && wavewalletrpc + +package wavewalletdk + +import ( + "runtime" + "testing" + + "github.com/lightninglabs/wavelength/waved" + "github.com/stretchr/testify/require" +) + +// TestEmbeddedArkChannelConfig exercises the production startup merge on +// native hosts and JS/WASM. The advanced config remains caller-owned. +func TestEmbeddedArkChannelConfig(t *testing.T) { + base := waved.DefaultConfig() + cfg := Config{DaemonConfig: base} + resolved, err := resolveDaemonConfig(cfg) + require.NoError(t, err) + require.False(t, resolved.Swap.SuppressArkChannelRuntime) + require.False(t, resolved.Swap.ArkChannelsEnabled) + + cfg.ArkChannelsEnabled = true + cfg.ServerTransport = TransportREST + cfg.SwapServerTransport = TransportREST + resolved, err = resolveDaemonConfig(cfg) + require.NoError(t, err) + require.False(t, resolved.Swap.SuppressArkChannelRuntime) + require.True(t, resolved.Swap.ArkChannelsEnabled) + require.False(t, base.Swap.ArkChannelsEnabled) + + base.Swap.ArkChannelsEnabled = true + cfg.ArkChannelsEnabled = false + resolved, err = resolveDaemonConfig(cfg) + require.NoError(t, err) + require.False(t, resolved.Swap.SuppressArkChannelRuntime) + + cfg.HostDrivenIngress = true + _, err = resolveDaemonConfig(cfg) + require.ErrorContains(t, err, "host_driven_ingress") + cfg.HostDrivenIngress = false + for _, wallet := range []string{ + waved.WalletTypeBtcwallet, waved.WalletTypeLnd, + } { + cfg.WalletType = wallet + _, err = resolveDaemonConfig(cfg) + require.ErrorContains(t, err, "requires lwwallet") + } + + cfg.WalletType = waved.WalletTypeLwwallet + for _, transports := range [][2]Transport{ + { + TransportGRPC, + TransportREST, + }, + { + TransportREST, + TransportGRPC, + }, + { + TransportGRPC, + TransportGRPC, + }, + } { + cfg.ServerTransport = transports[0] + cfg.SwapServerTransport = transports[1] + _, err = resolveDaemonConfig(cfg) + if runtime.GOOS == "js" { + require.ErrorContains(t, err, "REST") + } else { + require.NoError(t, err) + } + } + if runtime.GOOS == "js" { + cfg.ServerTransport = TransportREST + cfg.SwapServerTransport = TransportREST + cfg.ServerTLSCertPath = "operator.pem" + _, err = resolveDaemonConfig(cfg) + require.ErrorContains(t, err, "cannot pin") + cfg.ServerTLSCertPath = "" + cfg.SwapServerTLSCertPath = "swap.pem" + _, err = resolveDaemonConfig(cfg) + require.ErrorContains(t, err, "cannot pin") + } +} diff --git a/sdk/wavewalletdk/client.go b/sdk/wavewalletdk/client.go index 0a590eafb..e2475fa03 100644 --- a/sdk/wavewalletdk/client.go +++ b/sdk/wavewalletdk/client.go @@ -482,6 +482,21 @@ func (c *Client) Deposit(ctx context.Context, req DepositRequest) ( func (c *Client) Receive(ctx context.Context, req ReceiveRequest) ( *ReceiveResult, error) { + return c.receive(ctx, req, false) +} + +// ReceiveOnActiveChannel creates an invoice backed only by existing channel +// liquidity. Neither an old daemon nor an unavailable channel triggers a retry. +func (c *Client) ReceiveOnActiveChannel(ctx context.Context, + req ReceiveRequest) (*ReceiveResult, error) { + + return c.receive(ctx, req, true) +} + +// receive keeps result and receipt mapping identical for both invoice paths. +func (c *Client) receive(ctx context.Context, req ReceiveRequest, + activeChannelOnly bool) (*ReceiveResult, error) { + if err := c.requireWalletRPC(); err != nil { return nil, err } @@ -489,12 +504,21 @@ func (c *Client) Receive(ctx context.Context, req ReceiveRequest) ( return nil, fmt.Errorf("amount_sat must be positive") } - resp, err := c.wallet.Recv(ctx, &wavewalletrpc.RecvRequest{ + recv := c.wallet.Recv + if activeChannelOnly { + recv = c.wallet.RecvOnActiveChannel + } + resp, err := recv(ctx, &wavewalletrpc.RecvRequest{ AmtSat: req.AmountSat, Memo: req.Memo, RequestId: req.RequestID, }) if err != nil { + if activeChannelOnly { + return nil, fmt.Errorf("create active-channel receive "+ + "invoice: %w", err) + } + return nil, fmt.Errorf("create receive invoice: %w", err) } diff --git a/sdk/wavewalletdk/embedded.go b/sdk/wavewalletdk/embedded.go index 07492148b..71c18504b 100644 --- a/sdk/wavewalletdk/embedded.go +++ b/sdk/wavewalletdk/embedded.go @@ -40,6 +40,7 @@ func DefaultConfig() Config { WalletBtcwalletFilterHeadersSource: cfg.Wallet. BtcwFilterSource, SwapServerAddress: cfg.Swap.ServerAddress, + ArkChannelsEnabled: cfg.Swap.ArkChannelsEnabled, SwapNotificationIssuer: cfg.Swap.NotificationIssuer, SwapServerTransport: Transport(cfg.Swap.ServerTransport), SwapServerTLSCertPath: cfg.Swap.ServerTLSCertPath, @@ -110,7 +111,7 @@ func resolveDaemonConfig(cfg Config, opts ...Option) (*waved.Config, error) { return nil, err } - if err := configureSwapRuntime(daemonCfg, true); err != nil { + if err := configureSwapRuntime(daemonCfg); err != nil { return nil, err } configureWalletRPC(daemonCfg, true) @@ -382,6 +383,9 @@ func applyConfigOverrides(daemonCfg *waved.Config, cfg Config) { if daemonCfg.Swap == nil { daemonCfg.Swap = &waved.SwapConfig{} } + if cfg.ArkChannelsEnabled { + daemonCfg.Swap.ArkChannelsEnabled = true + } if cfg.SwapNotificationIssuer != "" { daemonCfg.Swap.NotificationIssuer = cfg.SwapNotificationIssuer } diff --git a/sdk/wavewalletdk/embedded_config.go b/sdk/wavewalletdk/embedded_config.go index 254138a88..3ad990390 100644 --- a/sdk/wavewalletdk/embedded_config.go +++ b/sdk/wavewalletdk/embedded_config.go @@ -99,6 +99,12 @@ type Config struct { // transport. Empty selects the daemon network+transport default. SwapServerAddress string + // ArkChannelsEnabled permits explicit channel open, pay and receive. + // Ordinary operations keep their existing rail, and an empty wallet + // does not start a peer on opt-in alone. Keep the same DataDir for + // recovery; existing channels remain protected without this opt-in. + ArkChannelsEnabled bool + // SwapNotificationIssuer pins the configured swap source's compressed // public identity. Empty leaves swap notifications unsupported. SwapNotificationIssuer string diff --git a/sdk/wavewalletdk/invoice_test.go b/sdk/wavewalletdk/invoice_test.go index ba3883e1b..3c53e79c4 100644 --- a/sdk/wavewalletdk/invoice_test.go +++ b/sdk/wavewalletdk/invoice_test.go @@ -126,7 +126,13 @@ func TestDecodeInvoice(t *testing.T) { "regtest", ) require.ErrorContains(t, err, "expired") - _, err = DecodeInvoice(amountless[:len(amountless)-1]+"q", "regtest") + // Keep the character in the Bech32 alphabet but always change it. + last := len(amountless) - 1 + replacement := "q" + if amountless[last] == 'q' { + replacement = "p" + } + _, err = DecodeInvoice(amountless[:last]+replacement, "regtest") require.Error(t, err) _, err = DecodeInvoice("lnbcrt1invalid", "regtest") require.Error(t, err) diff --git a/sdk/wavewalletdk/mobile/ark_channel.go b/sdk/wavewalletdk/mobile/ark_channel.go new file mode 100644 index 000000000..c41d58f13 --- /dev/null +++ b/sdk/wavewalletdk/mobile/ark_channel.go @@ -0,0 +1,43 @@ +//go:build mobile && wavewalletrpc && swapruntime + +package mobile + +import "github.com/lightninglabs/wavelength/sdk/wavewalletdk" + +// PromoteVTXO promotes wallet liquidity using a caller-owned idempotency key. +// The JSON types are wavewalletdk.PromoteVTXORequest and PromoteVTXOResult. +func PromoteVTXO(reqJSON []byte) ([]byte, error) { + client, ctx, err := activeClient() + if err != nil { + return nil, err + } + var req wavewalletdk.PromoteVTXORequest + if err := decode(reqJSON, &req); err != nil { + return nil, err + } + result, err := client.PromoteVTXO(ctx, req) + if err != nil { + return nil, err + } + + return marshal(result) +} + +// PayOnActiveChannel pays an invoice directly using outbound channel balance. +// JSON is wavewalletdk.PayOnActiveChannelRequest and PayOnActiveChannelResult. +func PayOnActiveChannel(reqJSON []byte) ([]byte, error) { + client, ctx, err := activeClient() + if err != nil { + return nil, err + } + var req wavewalletdk.PayOnActiveChannelRequest + if err := decode(reqJSON, &req); err != nil { + return nil, err + } + result, err := client.PayOnActiveChannel(ctx, req) + if err != nil { + return nil, err + } + + return marshal(result) +} diff --git a/sdk/wavewalletdk/mobile/ark_channel_test.go b/sdk/wavewalletdk/mobile/ark_channel_test.go new file mode 100644 index 000000000..c81c9209a --- /dev/null +++ b/sdk/wavewalletdk/mobile/ark_channel_test.go @@ -0,0 +1,237 @@ +//go:build mobile && wavewalletrpc && swapruntime + +package mobile + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "io" + "sync/atomic" + "testing" + + "github.com/lightninglabs/wavelength/rpc/arkchannelrpc" + "github.com/lightninglabs/wavelength/rpc/wavewalletrpc" + "github.com/lightninglabs/wavelength/sdk/wavewalletdk" + "github.com/lightninglabs/wavelength/waved" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +// TestArkChannelBindingDispatch exercises the JSON ABI against an embedded +// server, recording the decoded request and returning a controlled RPC reply. +// No peer, invoice signing, or payment settlement is simulated here. +func TestArkChannelBindingDispatch(t *testing.T) { + cfg := wavewalletdk.Config{ + DataDir: t.TempDir(), + Network: "regtest", + WalletType: waved.WalletTypeLwwallet, + WalletEsploraURL: "http://127.0.0.1:1", + ServerAddress: "http://127.0.0.1:1", + ServerTransport: wavewalletdk.TransportREST, + ServerInsecure: true, + SwapServerAddress: "http://127.0.0.1:1", + SwapServerTransport: wavewalletdk.TransportREST, + SwapServerInsecure: true, + ArkChannelsEnabled: true, + LogWriter: io.Discard, + DaemonConfig: waved.DefaultConfig(), + } + type observation struct { + method string + req proto.Message + } + observed := make(chan observation, 8) + var reject atomic.Bool + channelID := sha256.Sum256([]byte("channel")) + preimage := sha256.Sum256([]byte("preimage")) + hash := sha256.Sum256(preimage[:]) + cfg.DaemonConfig.UnaryServerInterceptors = []grpc.UnaryServerInterceptor{ + func(ctx context.Context, req any, info *grpc.UnaryServerInfo, + next grpc.UnaryHandler) (any, error) { + + var resp proto.Message + switch req := req.(type) { + case *arkchannelrpc.PromoteVTXORequest: + id := channelID[:] + if req.GetIdempotencyKey() == "short-id" { + id = id[:1] + } + resp = &arkchannelrpc.PromoteVTXOResponse{ + Channel: &arkchannelrpc.ArkChannel{ + ChannelId: id, + Phase: "Active", + CapacitySat: 12345, + }, + } + + case *arkchannelrpc.PayLightningInvoiceRequest: + pay := &arkchannelrpc.PayLightningInvoiceResponse{ + ChannelId: channelID[:], PaymentHash: hash[:], + Preimage: preimage[:], PrivateAmountSat: 101, FeeSat: 1, + } + switch req.GetPaymentRequest() { + case "short-id": + pay.ChannelId = pay.ChannelId[:1] + + case "short-preimage": + pay.Preimage = pay.Preimage[:1] + shortHash := sha256.Sum256(pay.Preimage) + pay.PaymentHash = shortHash[:] + + case "short-hash": + pay.PaymentHash = pay.PaymentHash[:1] + + case "wrong-hash": + pay.PaymentHash = channelID[:] + + case "empty-reply": + pay = &arkchannelrpc.PayLightningInvoiceResponse{} + } + resp = pay + + case *wavewalletrpc.RecvRequest: + resp = &wavewalletrpc.RecvResponse{ + Invoice: "ln-result", + } + + default: + return next(ctx, req) + } + observed <- observation{ + info.FullMethod, + req.(proto.Message), + } + if reject.Load() { + return nil, status.Error( + codes.FailedPrecondition, + "no liquidity", + ) + } + + return resp, nil + }, + } + err := startEmbedded( + func(start, _ context.Context) (*wavewalletdk.Client, error) { + return wavewalletdk.Start(start, cfg) + }, + ) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, Stop()) }) + + for _, tc := range []struct { + verb func([]byte) ([]byte, error) + method string + body string + req proto.Message + want map[string]any + }{ + {PromoteVTXO, arkchannelrpc.ArkChannelService_PromoteVTXO_FullMethodName, + `{"AmountSat":12345,"IdempotencyKey":"promotion-1"}`, + &arkchannelrpc.PromoteVTXORequest{ + AmountSat: 12345, + IdempotencyKey: "promotion-1", + }, + map[string]any{ + "ChannelID": hex.EncodeToString(channelID[:]), + "Phase": "Active", + "CapacitySat": 12345.0, + }}, + {PayOnActiveChannel, arkchannelrpc.ArkChannelService_PayLightningInvoice_FullMethodName, + `{"Invoice":"ln-pay","MaxFeeSat":4}`, + &arkchannelrpc.PayLightningInvoiceRequest{ + PaymentRequest: "ln-pay", + MaxFeeSat: 4, + }, + map[string]any{"ChannelID": hex.EncodeToString( + channelID[:], + ), + "PaymentHash": hex.EncodeToString(hash[:]), "Preimage": hex.EncodeToString( + preimage[:], + ), + "PrivateAmountSat": 101.0, "FeeSat": 1.0}}, + {ReceiveOnActiveChannel, wavewalletrpc.WalletService_RecvOnActiveChannel_FullMethodName, + `{"AmountSat":500,"Memo":"inbound","TimeoutSeconds":4}`, + &wavewalletrpc.RecvRequest{ + AmtSat: 500, + Memo: "inbound", + }, + map[string]any{ + "Invoice": "ln-result", + }}, + {Receive, wavewalletrpc.WalletService_Recv_FullMethodName, + `{"AmountSat":700,"Memo":"ordinary"}`, + &wavewalletrpc.RecvRequest{ + AmtSat: 700, + Memo: "ordinary", + }, + map[string]any{ + "Invoice": "ln-result", + }}, + } { + t.Run(tc.method, func(t *testing.T) { + for _, fail := range []bool{false, true} { + reject.Store(fail) + out, err := tc.verb([]byte(tc.body)) + if fail { + require.Nil(t, out) + require.Equal( + t, codes.FailedPrecondition, + status.Code(err), + ) + require.ErrorContains( + t, err, "no liquidity", + ) + } else { + require.NoError(t, err) + var got map[string]any + require.NoError( + t, json.Unmarshal(out, &got), + ) + require.Subset(t, got, tc.want) + } + require.Len( + t, observed, 1, "one RPC, no fallback", + ) + call := <-observed + require.Equal(t, tc.method, call.method) + require.True( + t, proto.Equal(tc.req, call.req), + "%v", call.req, + ) + } + }) + } + t.Run("malformed replies", func(t *testing.T) { + reject.Store(false) + out, err := PromoteVTXO( + []byte( + `{"AmountSat":12345,"IdempotencyKey":"short-id"}`, + ), + ) + require.Nil(t, out) + require.ErrorContains(t, err, "invalid channel ID") + for invoice, wantErr := range map[string]string{ + "empty-reply": "invalid channel ID", + "short-id": "invalid channel ID", + "short-preimage": "invalid settlement proof", + "short-hash": "invalid settlement proof", + "wrong-hash": "invalid settlement proof", + } { + req, err := json.Marshal( + wavewalletdk.PayOnActiveChannelRequest{ + Invoice: invoice, + }, + ) + require.NoError(t, err) + out, err := PayOnActiveChannel(req) + require.Nil(t, out) + require.ErrorContains(t, err, wantErr) + } + }) +} diff --git a/sdk/wavewalletdk/mobile/config.go b/sdk/wavewalletdk/mobile/config.go index 697e825c8..4f15547ed 100644 --- a/sdk/wavewalletdk/mobile/config.go +++ b/sdk/wavewalletdk/mobile/config.go @@ -51,6 +51,7 @@ type mobileConfig struct { AssetGroupKeys []string `json:"asset_group_keys"` // Swap server. + ArkChannelsEnabled bool `json:"ark_channels_enabled"` SwapServerAddress string `json:"swap_server_address"` SwapNotificationIssuer string `json:"swap_notification_issuer"` SwapServerTransport string `json:"swap_server_transport"` @@ -185,6 +186,7 @@ func (mc mobileConfig) validate() error { // build defaults. func applyMobileConfig(cfg *wavewalletdk.Config, mc mobileConfig) { cfg.HostDrivenIngress = mc.HostDrivenIngress + cfg.ArkChannelsEnabled = mc.ArkChannelsEnabled cfg.DurableRoundRuntime = mc.DurableRoundRuntime if mc.DataDir != "" { cfg.DataDir = mc.DataDir diff --git a/sdk/wavewalletdk/mobile/external_seed_wallet_test.go b/sdk/wavewalletdk/mobile/external_seed_wallet_test.go index 8c3b7fa46..f237d6fdf 100644 --- a/sdk/wavewalletdk/mobile/external_seed_wallet_test.go +++ b/sdk/wavewalletdk/mobile/external_seed_wallet_test.go @@ -48,6 +48,7 @@ func TestParseExternalSeedWalletStartRequest(t *testing.T) { require.Equal(t, "/tmp/wavelength-wallet", cfg.DataDir) require.Equal(t, "regtest", cfg.Network) require.Equal(t, "btcwallet", cfg.WalletType) + require.False(t, cfg.ArkChannelsEnabled) require.Equal(t, []byte{ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, @@ -57,6 +58,19 @@ func TestParseExternalSeedWalletStartRequest(t *testing.T) { require.Equal(t, uint32(144), req.RecoveryWindow) } +// TestExternalSeedChannelOptIn checks the nested config used by mobile and +// JS external-seed wallets, independent of the flat Start configuration. +func TestExternalSeedChannelOptIn(t *testing.T) { + cfg, req, err := parseExternalSeedWalletStartRequest([]byte(`{ + "config":{"data_dir":"/wallet","wallet_type":"lwwallet", + "ark_channels_enabled":true}, + "seed_entropy":"ABEiM0RVZneImaq7zN3u/w==" + }`)) + require.NoError(t, err) + defer clear(req.SeedEntropy) + require.True(t, cfg.ArkChannelsEnabled) +} + // TestParseExternalSeedWalletStartRequestRejectsInvalid tests its wire shape. func TestParseExternalSeedWalletStartRequestRejectsInvalid(t *testing.T) { tests := []struct{ name, request string }{ diff --git a/sdk/wavewalletdk/mobile/mobile_test.go b/sdk/wavewalletdk/mobile/mobile_test.go index ec55fcc76..c08306cb7 100644 --- a/sdk/wavewalletdk/mobile/mobile_test.go +++ b/sdk/wavewalletdk/mobile/mobile_test.go @@ -118,6 +118,29 @@ func TestReceiveErrorMarksLifecycleCancellation(t *testing.T) { } } +// TestParseArkChannelOptIn covers the JSON boundary used by mobile and WASM. +func TestParseArkChannelOptIn(t *testing.T) { + for _, raw := range []string{ + "", + "{}", + `{"ark_channels_enabled":false}`, + } { + cfg, err := parseConfig(raw) + if err != nil || cfg.ArkChannelsEnabled { + t.Fatalf("unexpected channel config for %q: %v", raw, + err) + } + } + cfg, err := parseConfig(`{"ark_channels_enabled":true, + "server_transport":"rest","swap_server_transport":"rest"}`) + if err != nil || !cfg.ArkChannelsEnabled || + cfg.ServerTransport != wavewalletdk.TransportREST || + cfg.SwapServerTransport != wavewalletdk.TransportREST { + + t.Fatalf("channel transport opt-in not preserved: %v", err) + } +} + // TestParseConfigEmptyUsesDefaults verifies that an empty config string yields // the wavewalletdk defaults rather than a zero config. func TestParseConfigEmptyUsesDefaults(t *testing.T) { diff --git a/sdk/wavewalletdk/mobile/wallet.go b/sdk/wavewalletdk/mobile/wallet.go index 813a23471..98ed8c7da 100644 --- a/sdk/wavewalletdk/mobile/wallet.go +++ b/sdk/wavewalletdk/mobile/wallet.go @@ -227,6 +227,17 @@ func Deposit(reqJSON []byte) ([]byte, error) { // wavewalletdk.ReceiveResult. When the deadline expires, the outcome may be // uncertain, so the host must reconcile Activity before retrying deliberately. func Receive(reqJSON []byte) ([]byte, error) { + return receive(reqJSON, false) +} + +// ReceiveOnActiveChannel creates an invoice only on existing inbound channel +// liquidity. Request, timeout and result use the same contract as Receive. +func ReceiveOnActiveChannel(reqJSON []byte) ([]byte, error) { + return receive(reqJSON, true) +} + +// receive shares deadline and uncertainty handling across both receive verbs. +func receive(reqJSON []byte, activeChannelOnly bool) ([]byte, error) { client, parentCtx, err := activeClient() if err != nil { return nil, err @@ -240,7 +251,11 @@ func Receive(reqJSON []byte) ([]byte, error) { ctx, cancel := context.WithTimeout(parentCtx, timeout) defer cancel() - res, err := client.Receive(ctx, req) + recv := client.Receive + if activeChannelOnly { + recv = client.ReceiveOnActiveChannel + } + res, err := recv(ctx, req) if err != nil { return nil, receiveError(ctx, err) } diff --git a/sdk/wavewalletdk/options_test.go b/sdk/wavewalletdk/options_test.go index 968c580d2..6d8410614 100644 --- a/sdk/wavewalletdk/options_test.go +++ b/sdk/wavewalletdk/options_test.go @@ -3,12 +3,56 @@ package wavewalletdk import ( + "context" + "io" "testing" + "time" "github.com/lightninglabs/wavelength/waved" "github.com/stretchr/testify/require" + "google.golang.org/grpc" ) +// TestEmbeddedArkChannelRegistrarLifecycle boots the real swap and wallet +// registrars on the same directory across opt-out, opt-in and restart. +func TestEmbeddedArkChannelRegistrarLifecycle(t *testing.T) { + base := waved.DefaultConfig() + base.LogWriter = io.Discard + registered := make(chan *waved.Config, 1) + base.RPCServiceRegistrars = []waved.RPCServiceRegistrar{ + func(_ context.Context, _ *grpc.Server, _ *waved.RPCServer, + cfg *waved.Config) (func(), error) { + + registered <- cfg + + return nil, nil + }, + } + cfg := Config{ + DaemonConfig: base, + DataDir: t.TempDir(), + Network: "regtest", + ServerTransport: TransportREST, + SwapServerTransport: TransportREST, + WalletEsploraURL: "http://127.0.0.1", + } + for _, enabled := range []bool{false, true, true} { + cfg.ArkChannelsEnabled = enabled + ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) + client, err := Start(ctx, cfg) + cancel() + require.NoError(t, err) + t.Cleanup(func() { _ = client.Stop() }) + running := <-registered + require.NotNil(t, running.Swap.Backend) + require.NotNil(t, running.Swap.ArkChannelMailbox) + require.Equal(t, enabled, running.Swap.ArkChannelsEnabled) + require.NoError(t, client.Stop()) + require.Nil(t, running.Swap.ArkChannelMailbox) + require.Nil(t, base.Swap.ArkChannelMailbox) + } +} + // TestResolveDaemonConfigEagerRoundJoin is a table-driven test that pins the // wavewalletdk-side override contract for waved.Config.EagerRoundJoin under the // wavewalletrpc build tag. The matrix covers the three production paths a host diff --git a/sdk/wavewalletdk/restclient_test.go b/sdk/wavewalletdk/restclient_test.go index 11623fc80..cf937747b 100644 --- a/sdk/wavewalletdk/restclient_test.go +++ b/sdk/wavewalletdk/restclient_test.go @@ -1,13 +1,79 @@ package wavewalletdk import ( + "io" "net/http" "net/http/httptest" + "strings" "testing" "github.com/stretchr/testify/require" ) +// walletRoundTrip lets transport tests inspect the HTTP request without +// binding a TCP listener (including in a JS VM). +type walletRoundTrip func(*http.Request) (*http.Response, error) + +// RoundTrip serves the request using the test gateway. +func (rt walletRoundTrip) RoundTrip(req *http.Request) (*http.Response, error) { + return rt(req) +} + +// TestArkChannelReceiveREST checks both dispatch and fail-closed behavior +// against an older gateway that has no channel receive method. +func TestArkChannelReceiveREST(t *testing.T) { + var paths []string + var reject bool + httpClient := &http.Client{Transport: walletRoundTrip( + func(req *http.Request) (*http.Response, error) { + paths = append(paths, req.URL.Path) + code, body := http.StatusOK, "{}" + switch req.URL.Path { + case "/v1/daemon/get-info": + case "/v1/wallet/recv-on-active-channel": + raw, err := io.ReadAll(req.Body) + require.NoError(t, err) + require.JSONEq( + t, `{"amt_sat":"42","memo":"m"}`, + string(raw), + ) + body = `{"invoice":"ln-channel"}` + if reject { + code = http.StatusNotFound + body = "not found" + } + + default: + t.Fatalf("unexpected fallback to %s", + req.URL.Path) + } + + return &http.Response{ + StatusCode: code, Body: io.NopCloser( + strings.NewReader(body), + ), + }, nil + }, + )} + client, err := Connect(t.Context(), ConnectConfig{ + Address: "https://wallet.invalid", Transport: TransportREST, + HTTPClient: httpClient, + }) + require.NoError(t, err) + defer func() { + require.NoError(t, client.Close()) + }() + req := ReceiveRequest{AmountSat: 42, Memo: "m"} + invoice, err := client.ReceiveOnActiveChannel(t.Context(), req) + require.NoError(t, err) + require.Equal(t, "ln-channel", invoice.Invoice) + reject = true + invoice, err = client.ReceiveOnActiveChannel(t.Context(), req) + require.Error(t, err) + require.Nil(t, invoice) + require.Len(t, paths, 3) +} + // TestConnectREST verifies wavewalletdk can use grpc-gateway clients without a // native gRPC connection. func TestConnectREST(t *testing.T) { diff --git a/sdk/wavewalletdk/swapruntime.go b/sdk/wavewalletdk/swapruntime.go index 1b05b975e..a5e84df87 100644 --- a/sdk/wavewalletdk/swapruntime.go +++ b/sdk/wavewalletdk/swapruntime.go @@ -3,6 +3,9 @@ package wavewalletdk import ( + "fmt" + "runtime" + "github.com/lightninglabs/wavelength/swapclientserver" "github.com/lightninglabs/wavelength/waved" ) @@ -16,9 +19,31 @@ import ( // swapruntime; the stub file in swapruntime_stub.go is the negative half of // the same contract and keeps the public Client method set identical across // both build flavors. -func configureSwapRuntime(cfg *waved.Config, enabled bool) error { - if !enabled { - return nil +func configureSwapRuntime(cfg *waved.Config) error { + if cfg.Swap.ArkChannelsEnabled { + if cfg.Wallet == nil || + cfg.Wallet.Type != waved.WalletTypeLwwallet { + return fmt.Errorf("ark_channels_enabled requires " + + "lwwallet") + } + if cfg.HostDrivenIngress { + return fmt.Errorf("ark_channels_enabled is " + + "incompatible with host_driven_ingress") + } + if runtime.GOOS == "js" { + if cfg.Server == nil || + cfg.Server.Transport != waved.RPCTransportREST || + cfg.Swap.ServerTransport != waved.RPCTransportREST { + return fmt.Errorf("ark_channels_enabled on " + + "WASM requires REST operator and " + + "swap transports") + } + if cfg.Server.TLSCertPath != "" || + cfg.Swap.ServerTLSCertPath != "" { + return fmt.Errorf("browser HTTP cannot pin " + + "operator or swap TLS certificates") + } + } } cfg.RPCServiceRegistrars = append( diff --git a/sdk/wavewalletdk/swapruntime_stub.go b/sdk/wavewalletdk/swapruntime_stub.go index 43dab1a26..e7cad7bba 100644 --- a/sdk/wavewalletdk/swapruntime_stub.go +++ b/sdk/wavewalletdk/swapruntime_stub.go @@ -5,7 +5,11 @@ package wavewalletdk import "github.com/lightninglabs/wavelength/waved" // configureSwapRuntime keeps default builds compiling. -func configureSwapRuntime(_ *waved.Config, enabled bool) error { +func configureSwapRuntime(cfg *waved.Config) error { + if cfg.Swap.ArkChannelsEnabled { + return ErrWalletRPCUnavailable + } + return nil } diff --git a/sdk/wavewalletdk/wavewalletrpc_stub_test.go b/sdk/wavewalletdk/wavewalletrpc_stub_test.go index 6dd592d03..3945fb5c4 100644 --- a/sdk/wavewalletdk/wavewalletrpc_stub_test.go +++ b/sdk/wavewalletdk/wavewalletrpc_stub_test.go @@ -34,4 +34,8 @@ func TestStartRequiresWalletRPC(t *testing.T) { client, err := Start(context.Background(), Config{}) require.Nil(t, client) require.ErrorIs(t, err, ErrWalletRPCUnavailable) + + client, err = Start(t.Context(), Config{ArkChannelsEnabled: true}) + require.Nil(t, client) + require.ErrorIs(t, err, ErrWalletRPCUnavailable) } diff --git a/swaprpc/AGENTS.md b/swaprpc/AGENTS.md index 62132793e..69ba11f23 100644 --- a/swaprpc/AGENTS.md +++ b/swaprpc/AGENTS.md @@ -92,10 +92,9 @@ because they are part of the wire contract, not of either side's logic. shared by the optional Ark-channel rail and the ordinary vHTLC rail. The server quote does not claim that the channel rail won; that outcome is reported later by the daemon's `swapclientrpc` settlement type. -- `RequestChannelIdRequest` field 7 and `RequestChannelIdResponse` field 10 - are reserved under the retired name `channel_backing_fee_sat`. Receives no - longer negotiate that legacy fee reserve on the wire. Never reuse reserved - field numbers or names. +- Both messages reserve the retired name `channel_backing_fee_sat`, not + its old numbers. Keep the ordinary `owner_proof` and + `invoice_routing_pubkey` fields on their existing numbers. - `SwapMailboxEvent` is a proto oneof: read the populated variant, don't assume `OutSwapHtlcEvent` is the only case as new event kinds are added. diff --git a/swaprpc/CLAUDE.md b/swaprpc/CLAUDE.md index 62132793e..69ba11f23 100644 --- a/swaprpc/CLAUDE.md +++ b/swaprpc/CLAUDE.md @@ -92,10 +92,9 @@ because they are part of the wire contract, not of either side's logic. shared by the optional Ark-channel rail and the ordinary vHTLC rail. The server quote does not claim that the channel rail won; that outcome is reported later by the daemon's `swapclientrpc` settlement type. -- `RequestChannelIdRequest` field 7 and `RequestChannelIdResponse` field 10 - are reserved under the retired name `channel_backing_fee_sat`. Receives no - longer negotiate that legacy fee reserve on the wire. Never reuse reserved - field numbers or names. +- Both messages reserve the retired name `channel_backing_fee_sat`, not + its old numbers. Keep the ordinary `owner_proof` and + `invoice_routing_pubkey` fields on their existing numbers. - `SwapMailboxEvent` is a proto oneof: read the populated variant, don't assume `OutSwapHtlcEvent` is the only case as new event kinds are added.