From 18dbb0e98db3deb34ff6e44430c85869131dd03c Mon Sep 17 00:00:00 2001 From: sputn1ck Date: Wed, 18 Nov 2026 18:43:35 +0100 Subject: [PATCH 1/7] arkchannel: Define durable channel storage and peer contracts Keep the first channel migration and the authenticated peer protocol limited to the states used by active-channel settlement. --- db/migrations.go | 2 +- db/sqlc/AGENTS.md | 6 +- db/sqlc/CLAUDE.md | 6 +- .../migrations/000032_ark_channels.down.sql | 1 + db/sqlc/migrations/000032_ark_channels.up.sql | 110 +++++ db/sqlc/queries/ark_channels.sql | 114 +++++ rpc/arkchannelrpc/ark_channel.proto | 421 ++++++++++++++++++ rpc/arkchannelrpc/ark_channel_peer.proto | 68 +++ scripts/gen_protos.sh | 26 +- 9 files changed, 745 insertions(+), 9 deletions(-) create mode 100644 db/sqlc/migrations/000032_ark_channels.down.sql create mode 100644 db/sqlc/migrations/000032_ark_channels.up.sql create mode 100644 db/sqlc/queries/ark_channels.sql create mode 100644 rpc/arkchannelrpc/ark_channel.proto create mode 100644 rpc/arkchannelrpc/ark_channel_peer.proto diff --git a/db/migrations.go b/db/migrations.go index 862b8d76f..a67c25ed9 100644 --- a/db/migrations.go +++ b/db/migrations.go @@ -10,7 +10,7 @@ const ( // daemon. // // NOTE: This MUST be updated when a new migration is added. - LatestMigrationVersion uint = 31 + LatestMigrationVersion uint = 32 ) // MigrationTarget is a functional option that can be passed to applyMigrations diff --git a/db/sqlc/AGENTS.md b/db/sqlc/AGENTS.md index 7dc81a2de..090259f87 100644 --- a/db/sqlc/AGENTS.md +++ b/db/sqlc/AGENTS.md @@ -6,9 +6,9 @@ Generated type-safe query layer for the main client database schema: chain info, internal keys, macaroons, boarding, rounds, VTXOs, OOR artifacts/session registry, ledger accounting, UTXO audit, unilateral exit, vHTLC recovery, pending intents, spending reservations, credit -operations, and the activity log. Generated by `sqlc` from -`db/sqlc/queries/*.sql`; regenerate with `make sqlc`. Do not edit by -hand, except `db_custom.go`. +operations, Ark channel coordination, and the activity log. Generated by +`sqlc` from `db/sqlc/queries/*.sql`; regenerate with `make sqlc`. Do not +edit by hand, except `db_custom.go`. ## Key Types diff --git a/db/sqlc/CLAUDE.md b/db/sqlc/CLAUDE.md index 7dc81a2de..090259f87 100644 --- a/db/sqlc/CLAUDE.md +++ b/db/sqlc/CLAUDE.md @@ -6,9 +6,9 @@ Generated type-safe query layer for the main client database schema: chain info, internal keys, macaroons, boarding, rounds, VTXOs, OOR artifacts/session registry, ledger accounting, UTXO audit, unilateral exit, vHTLC recovery, pending intents, spending reservations, credit -operations, and the activity log. Generated by `sqlc` from -`db/sqlc/queries/*.sql`; regenerate with `make sqlc`. Do not edit by -hand, except `db_custom.go`. +operations, Ark channel coordination, and the activity log. Generated by +`sqlc` from `db/sqlc/queries/*.sql`; regenerate with `make sqlc`. Do not +edit by hand, except `db_custom.go`. ## Key Types diff --git a/db/sqlc/migrations/000032_ark_channels.down.sql b/db/sqlc/migrations/000032_ark_channels.down.sql new file mode 100644 index 000000000..819cb37f1 --- /dev/null +++ b/db/sqlc/migrations/000032_ark_channels.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS ark_channels; diff --git a/db/sqlc/migrations/000032_ark_channels.up.sql b/db/sqlc/migrations/000032_ark_channels.up.sql new file mode 100644 index 000000000..ce3c1bdbf --- /dev/null +++ b/db/sqlc/migrations/000032_ark_channels.up.sql @@ -0,0 +1,110 @@ +-- Ark channel coordination stores only facts that cross the Ark and lnd +-- databases. Lightning commitments, HTLCs, invoices, and payment attempts +-- remain exclusively in lnd. +CREATE TABLE IF NOT EXISTS ark_channels ( + channel_id BLOB PRIMARY KEY NOT NULL, + pending_channel_id BLOB NOT NULL UNIQUE, + reserved_scid BLOB NOT NULL, + capacity BIGINT NOT NULL CHECK (capacity > 0), + client_node_key BLOB NOT NULL, + hub_node_key BLOB NOT NULL, + client_ark_key BLOB NOT NULL, + hub_ark_key BLOB NOT NULL, + ark_operator_key BLOB NOT NULL, + client_channel_key BLOB NOT NULL, + hub_channel_key BLOB NOT NULL, + funder_key BLOB NOT NULL, + channel_delay BIGINT NOT NULL, + funder_delay BIGINT NOT NULL, + min_exit_delay BIGINT NOT NULL, + + phase INTEGER NOT NULL CHECK (phase BETWEEN 1 AND 13), + oor_session_id BLOB, + source_index BIGINT, + source_amount BIGINT, + source_ark_tx BLOB, + backing_tx BLOB, + channel_point_txid BLOB, + channel_point_index BIGINT, + -- The unsigned backing has exactly one output, at index zero. + authorized_backing_txid BLOB CHECK ( + authorized_backing_txid IS NULL OR + (length(authorized_backing_txid) = 32 AND oor_session_id IS NOT NULL AND + (channel_point_txid IS NULL OR + channel_point_txid = authorized_backing_txid)) + ), + funding_signature BLOB CHECK (funding_signature IS NULL OR + (authorized_backing_txid IS NOT NULL AND length(funding_signature) = 64)), + client_finalized BOOLEAN NOT NULL DEFAULT FALSE, + hub_finalized BOOLEAN NOT NULL DEFAULT FALSE, + oor_finalized BOOLEAN NOT NULL DEFAULT FALSE, + oor_aborted BOOLEAN NOT NULL DEFAULT FALSE, + backing_published BOOLEAN NOT NULL DEFAULT FALSE, + close_initiator INTEGER CHECK (close_initiator IN (1, 2)), + close_client_script BLOB, + close_hub_script BLOB, + close_fee_rate_sat_per_kw BIGINT, + cooperative_close_tx BLOB, + cooperative_close_txid BLOB, + close_commitment_height BIGINT, + close_client_balance BIGINT, + close_hub_balance BIGINT, + client_recovery_ready BOOLEAN NOT NULL DEFAULT FALSE, + hub_recovery_ready BOOLEAN NOT NULL DEFAULT FALSE, + source_spent_outpoint_txid BLOB, + source_spent_outpoint_index BIGINT, + source_spending_txid BLOB, + pre_ponr_started_at BIGINT, + failure TEXT, + + revision BIGINT NOT NULL CHECK (revision > 0), + created_at BIGINT NOT NULL, + updated_at BIGINT NOT NULL, + + CHECK ( + (oor_session_id IS NULL AND source_index IS NULL AND + source_amount IS NULL AND source_ark_tx IS NULL) OR + (oor_session_id IS NOT NULL AND source_index IS NOT NULL AND + source_amount IS NOT NULL AND source_ark_tx IS NOT NULL) + ), + CHECK ( + (backing_tx IS NULL AND channel_point_txid IS NULL AND + channel_point_index IS NULL) OR + (backing_tx IS NOT NULL AND channel_point_txid IS NOT NULL AND + channel_point_index IS NOT NULL) + ), + CHECK ( + (close_initiator IS NULL AND close_client_script IS NULL AND + close_hub_script IS NULL AND close_fee_rate_sat_per_kw IS NULL) OR + (close_initiator IS NOT NULL AND close_client_script IS NOT NULL AND + close_hub_script IS NOT NULL AND close_fee_rate_sat_per_kw IS NOT NULL) + ), + CHECK ( + (cooperative_close_tx IS NULL AND cooperative_close_txid IS NULL AND + close_commitment_height IS NULL AND close_client_balance IS NULL AND + close_hub_balance IS NULL) OR + (cooperative_close_tx IS NOT NULL AND cooperative_close_txid IS NOT NULL AND + close_commitment_height IS NOT NULL AND close_client_balance IS NOT NULL AND + close_hub_balance IS NOT NULL) + ), + CHECK (channel_delay >= 0 AND channel_delay <= 4294967295), + CHECK (funder_delay >= 0 AND funder_delay <= 4294967295), + CHECK (min_exit_delay >= 0 AND min_exit_delay <= 4294967295) +); + +CREATE INDEX IF NOT EXISTS idx_ark_channels_phase_created + ON ark_channels(phase, created_at ASC); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_ark_channels_reserved_scid + ON ark_channels(reserved_scid); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_ark_channels_source + ON ark_channels(oor_session_id, source_index) + WHERE oor_session_id IS NOT NULL AND source_index IS NOT NULL; + +CREATE UNIQUE INDEX IF NOT EXISTS idx_ark_channels_channel_point + ON ark_channels(channel_point_txid, channel_point_index) + WHERE channel_point_txid IS NOT NULL; + +CREATE INDEX idx_ark_channels_client_created + ON ark_channels(client_node_key, created_at, channel_id); diff --git a/db/sqlc/queries/ark_channels.sql b/db/sqlc/queries/ark_channels.sql new file mode 100644 index 000000000..503eb30a7 --- /dev/null +++ b/db/sqlc/queries/ark_channels.sql @@ -0,0 +1,114 @@ +-- Ark channel coordination queries. + +-- name: InsertArkChannel :execrows +INSERT INTO ark_channels ( + channel_id, pending_channel_id, reserved_scid, capacity, + client_node_key, hub_node_key, client_ark_key, + hub_ark_key, ark_operator_key, client_channel_key, hub_channel_key, + funder_key, channel_delay, funder_delay, min_exit_delay, phase, + oor_session_id, source_index, source_amount, source_ark_tx, + backing_tx, channel_point_txid, channel_point_index, client_finalized, + hub_finalized, oor_finalized, oor_aborted, backing_published, + client_recovery_ready, hub_recovery_ready, + source_spent_outpoint_txid, + source_spent_outpoint_index, source_spending_txid, + close_initiator, close_client_script, close_hub_script, + close_fee_rate_sat_per_kw, cooperative_close_tx, + cooperative_close_txid, close_commitment_height, close_client_balance, + close_hub_balance, failure, revision, created_at, + updated_at, pre_ponr_started_at +) 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, $35, $36, $37, $38, $39, $40, + $41, $42, $43, $44, $45, $46, + sqlc.arg(pre_ponr_started_at) +) +ON CONFLICT (channel_id) DO NOTHING; + +-- name: GetArkChannel :one +SELECT * FROM ark_channels +WHERE channel_id = $1; + +-- name: AuthorizeArkFundingBacking :execrows +UPDATE ark_channels SET authorized_backing_txid = sqlc.arg(txid), + revision = revision + 1, updated_at = sqlc.arg(updated_at) +WHERE channel_id = sqlc.arg(channel_id) AND revision = sqlc.arg(revision) + AND client_node_key = sqlc.arg(owner_key) + AND authorized_backing_txid IS NULL AND phase = 2; + +-- name: RecordArkFundingSignature :execrows +UPDATE ark_channels SET funding_signature = sqlc.arg(signature), + revision = revision + 1, updated_at = sqlc.arg(updated_at) +WHERE channel_id = sqlc.arg(channel_id) AND revision = sqlc.arg(revision) + AND client_node_key = sqlc.arg(owner_key) AND phase = 2 + AND authorized_backing_txid = sqlc.arg(txid) AND funding_signature IS NULL; + +-- name: GetArkChannelByPendingID :one +SELECT * FROM ark_channels +WHERE pending_channel_id = $1; + +-- name: GetArkChannelBySCID :one +SELECT * FROM ark_channels WHERE reserved_scid = $1; + +-- name: GetArkChannelByChannelPoint :one +SELECT * FROM ark_channels +WHERE channel_point_txid = $1 AND channel_point_index = $2; + +-- name: ListNonTerminalArkChannels :many +SELECT * FROM ark_channels +-- Phase 8 is closed and phase 10 is failed. A cooperatively closed channel +-- remains resumable because its signed replacement VTXOs still need source +-- ancestry defense. Cancelling also remains resumable. +WHERE phase NOT IN (8, 10) + OR (phase = 8 AND cooperative_close_txid IS NOT NULL) +ORDER BY created_at ASC, channel_id ASC; + +-- name: ListPeerArkChannels :many +SELECT * FROM ark_channels +WHERE client_node_key = $1 AND + (phase NOT IN (8, 10) OR (phase = 8 AND cooperative_close_txid IS NOT NULL)) +ORDER BY created_at ASC, channel_id ASC; + +-- name: ListArkRecoveryPeers :many +SELECT DISTINCT client_node_key FROM ark_channels +WHERE phase NOT IN (8, 10) OR (phase = 8 AND cooperative_close_txid IS NOT NULL) +ORDER BY client_node_key; + +-- name: CompareAndSwapArkChannel :execrows +UPDATE ark_channels SET + phase = $3, + oor_session_id = $4, + source_index = $5, + source_amount = $6, + source_ark_tx = $7, + backing_tx = $8, + channel_point_txid = $9, + channel_point_index = $10, + client_finalized = $11, + hub_finalized = $12, + oor_finalized = $13, + oor_aborted = $14, + client_recovery_ready = $15, + hub_recovery_ready = $16, + source_spent_outpoint_txid = $17, + source_spent_outpoint_index = $18, + source_spending_txid = $19, + backing_published = $20, + close_initiator = $21, + close_client_script = $22, + close_hub_script = $23, + close_fee_rate_sat_per_kw = $24, + cooperative_close_tx = $25, + cooperative_close_txid = $26, + close_commitment_height = $27, + close_client_balance = $28, + close_hub_balance = $29, + failure = $30, + pre_ponr_started_at = COALESCE( + pre_ponr_started_at, sqlc.arg(pre_ponr_started_at) + ), + revision = revision + 1, + updated_at = $31 +WHERE channel_id = $1 AND revision = $2 + AND client_node_key = sqlc.arg(owner_key); diff --git a/rpc/arkchannelrpc/ark_channel.proto b/rpc/arkchannelrpc/ark_channel.proto new file mode 100644 index 000000000..d9ed3049e --- /dev/null +++ b/rpc/arkchannelrpc/ark_channel.proto @@ -0,0 +1,421 @@ +syntax = "proto3"; + +package arkchannelrpc; + +option go_package = "github.com/lightninglabs/wavelength/rpc/arkchannelrpc"; + +// ArkChannelService is the local Wavelength control surface for channels +// backed by unpublished Ark transactions. +service ArkChannelService { + // PromoteVTXO turns existing wallet liquidity into an active OOR-backed + // channel. The daemon derives every protocol parameter from amount_sat. + rpc PromoteVTXO (PromoteVTXORequest) returns (PromoteVTXOResponse); + + // PayLightningInvoice atomically holds the private leg, asks the hub to + // dispatch the public invoice, and settles with the public preimage. + rpc PayLightningInvoice (PayLightningInvoiceRequest) + returns (PayLightningInvoiceResponse); + + // MaterializeAndForceClose publishes the Ark ancestry, exact channel + // backing, and lnd's latest commitment transaction. + rpc MaterializeAndForceClose (MaterializeAndForceCloseRequest) + returns (MaterializeAndForceCloseResponse); + + // RefreshChannel settles one clean channel into ordinary replacement + // VTXOs without materializing its Lightning channel point. + rpc RefreshChannel (RefreshChannelRequest) returns (RefreshChannelResponse); + + // GetChannel returns the durable Ark lifecycle state for one channel. + rpc GetChannel (GetChannelRequest) returns (GetChannelResponse); + + // ListChannels returns every channel that still needs recovery, + // observation, or operator action. + rpc ListChannels (ListChannelsRequest) returns (ListChannelsResponse); +} + +message PromoteVTXORequest { + int64 amount_sat = 1; + string idempotency_key = 2; +} + +message PromoteVTXOResponse { + ArkChannel channel = 1; +} + +message PayLightningInvoiceRequest { + string payment_request = 1; + uint64 max_fee_sat = 2; +} + +message PayLightningInvoiceResponse { + bytes payment_hash = 1; + bytes preimage = 2; + int64 private_amount_sat = 3; + int64 fee_sat = 4; + bytes channel_id = 5; +} + +message MaterializeAndForceCloseRequest { + bytes channel_id = 1; +} + +message MaterializeAndForceCloseResponse { + ArkChannel channel = 1; + bytes backing_txid = 2; + bytes commitment_txid = 3; +} + +message GetPeerInfoRequest { +} + +message GetPeerInfoResponse { + bytes hub_node_key = 1; + bytes hub_ark_key = 2; + bytes hub_channel_key = 3; + bytes ark_operator_key = 4; + uint32 channel_delay = 5; + uint32 funder_delay = 6; + uint32 min_exit_delay = 7; + reserved 8; + reserved "hub_funder_key"; +} + +message RegisterPromotionRequest { + ChannelTerms terms = 1; +} + +message RegisterPromotionResponse { + ArkChannel channel = 1; +} + +message GetFundingChannelRequest { + bytes channel_id = 1; +} + +message GetFundingChannelResponse { + ChannelTerms terms = 1; + ChannelVTXOBinding binding = 2; + ChannelBacking backing = 3; + uint32 phase = 4; + bool oor_finalized = 5; + bool client_recovery_ready = 6; + string failure = 7; + uint64 revision = 8; + bool oor_aborted = 9; + bool hub_recovery_ready = 10; +} + +message BindPreparedOORRequest { + bytes channel_id = 1; + ChannelVTXOBinding binding = 2; +} + +message BindPreparedOORResponse { + ArkChannel channel = 1; +} + +message SignBackingRequest { + bytes channel_id = 1; + ChannelTerms terms = 2; + ChannelVTXOBinding binding = 3; + bytes funding_psbt = 4; +} + +message SignBackingResponse { + bytes signature = 1; +} + +message InstallBackingRequest { + bytes channel_id = 1; + ChannelTerms terms = 2; + ChannelVTXOBinding binding = 3; + ChannelBacking backing = 4; +} + +message InstallBackingResponse { +} + +message InstallRecoveryPackageRequest { + bytes channel_id = 1; + ChannelTerms terms = 2; + ChannelVTXOBinding binding = 3; + ChannelRecoveryPackage recovery = 4; +} + +message InstallRecoveryPackageResponse { +} + +message OORRecoverySource { + bytes txid = 1; + uint32 output_index = 2; + int64 amount_sat = 3; + bytes pk_script = 4; +} + +message ChannelRecoveryPackage { + ChannelRecoveryDescriptor source_descriptor = 1; + repeated ChannelRecoveryOORPackage oor_packages = 2; +} + +message ChannelRecoveryDescriptor { + repeated ChannelRecoveryAncestry ancestry = 1; + string round_id = 2; + bytes commitment_txid = 3; + int32 batch_expiry = 4; + int32 chain_depth = 5; + int32 created_height = 6; + int32 construction_version = 7; +} + +message ChannelRecoveryAncestry { + bytes tree_path = 1; + bytes commitment_txid = 2; + repeated uint32 input_indices = 3; + uint32 tree_depth = 4; + int32 commitment_height = 5; +} + +message ChannelRecoveryOORPackage { + bytes session_id = 1; + int32 direction = 2; + bytes ark_psbt = 3; + repeated bytes checkpoint_psbts = 4; +} + +message FundingStatusRequest { + ChannelTerms terms = 1; + ChannelBacking backing = 2; +} + +message FundingStatusResponse { + bool ready = 1; +} + +enum ChannelEventType { + CHANNEL_EVENT_TYPE_UNSPECIFIED = 0; + CHANNEL_EVENT_TYPE_FUNDING_FINALIZED = 1; + CHANNEL_EVENT_TYPE_OOR_FINALIZED = 2; + CHANNEL_EVENT_TYPE_RECOVERY_PACKAGE_INSTALLED = 6; + CHANNEL_EVENT_TYPE_OOR_ABORTED = 9; + + reserved 3, 4, 5, 7, 8; + reserved "CHANNEL_EVENT_TYPE_FUNDING_PEER_READY"; +} + +message ApplyChannelEventRequest { + bytes channel_id = 1; + ChannelEventType event_type = 2; + uint32 party = 3; + bytes oor_session_id = 4; + bytes channel_point_txid = 5; + uint32 channel_point_index = 6; + string failure_reason = 7; +} + +message ApplyChannelEventResponse { + ArkChannel channel = 1; +} + +message PrepareOutgoingPaymentRequest { + string payment_request = 1; + uint64 max_fee_sat = 2; +} + +message PrepareOutgoingPaymentResponse { + bytes payment_hash = 1; + int64 private_amount_sat = 2; + int64 fee_sat = 3; + bytes channel_id = 4; + uint64 reserved_scid = 5; +} + +message CancelOutgoingPaymentRequest { + bytes payment_hash = 1; + string reason = 2; +} + +message CancelOutgoingPaymentResponse { + bool cancelled = 1; +} + +message RegisterIncomingPaymentRequest { + bytes payment_hash = 1; + int64 amount_sat = 2; + uint64 reserved_scid = 3; +} + +message RegisterIncomingPaymentResponse { + bool registered = 1; + reserved 2; + reserved "channel_capacity_sat"; + bytes channel_id = 3; +} + +message CancelIncomingPaymentRequest { + bytes payment_hash = 1; + string reason = 2; +} + +message CancelIncomingPaymentResponse { + bool cancelled = 1; +} + +message ChannelTerms { + bytes channel_id = 1; + uint32 kind = 2; + uint32 funder = 3; + bytes pending_channel_id = 4; + uint64 reserved_scid = 5; + int64 capacity_sat = 6; + bytes client_node_key = 7; + bytes hub_node_key = 8; + reserved 9; + reserved "payment_hash"; + ChannelVTXOTerms vtxo = 10; +} + +message ChannelVTXOTerms { + bytes client_ark_key = 1; + bytes hub_ark_key = 2; + bytes ark_operator_key = 3; + bytes client_channel_key = 4; + bytes hub_channel_key = 5; + bytes funder_key = 6; + uint32 channel_delay = 7; + uint32 funder_delay = 8; + uint32 min_exit_delay = 9; +} + +message ChannelVTXOBinding { + bytes oor_session_id = 1; + bytes outpoint_txid = 2; + uint32 outpoint_index = 3; + int64 amount_sat = 4; + bytes ark_transaction = 5; + bytes policy_template = 6; + bytes pk_script = 7; +} + +message ChannelBacking { + bytes transaction = 1; + bytes channel_point_txid = 2; + uint32 channel_point_index = 3; +} + +message RefreshChannelRequest { + // channel_id is the 32-byte durable Ark channel identifier. + bytes channel_id = 1; + reserved 2; + reserved "fee_rate_sat_per_kw"; +} + +message RefreshChannelResponse { + ArkChannel channel = 1; +} + +message GetChannelRequest { + bytes channel_id = 1; +} + +message GetChannelResponse { + ArkChannel channel = 1; +} + +message ListChannelsRequest { +} + +message ListChannelsResponse { + repeated ArkChannel channels = 1; +} + +message ArkChannel { + bytes channel_id = 1; + string kind = 2; + string phase = 3; + string funder = 4; + int64 capacity_sat = 5; + string source_outpoint = 6; + string channel_point = 7; + bytes refresh_oor_txid = 8; + uint64 revision = 9; + uint64 reserved_scid = 10; + int64 local_balance_sat = 11; + int64 remote_balance_sat = 12; + bool balance_available = 13; + string balance_error = 14; +} + +message GetCooperativeCloseTermsRequest { + bytes channel_id = 1; + bytes client_delivery_script = 2; + reserved 3; + reserved "fee_rate_sat_per_kw"; +} + +message GetCooperativeCloseTermsResponse { + CooperativeCloseRequest request = 1; + reserved 2, 3; + reserved "clean_state", "settlement"; +} + +message CompleteCooperativeCloseRequest { + bytes channel_id = 1; + CooperativeCloseProposal proposal = 2; + reserved 3; + reserved "client_signature"; + CooperativeCloseRequest request = 4; +} + +message CompleteCooperativeCloseResponse { + CooperativeClose settlement = 1; +} + +message ConfirmCooperativeCloseRequest { + bytes channel_id = 1; + bytes authorization_receipt = 2; +} + +message ConfirmCooperativeCloseResponse { +} + +message PublishCooperativeCloseRequest { + bytes channel_id = 1; + bytes settlement_txid = 2; +} + +message PublishCooperativeCloseResponse { + bytes settlement_txid = 1; + bool hub_finalized = 2; +} + +message AbortCooperativeCloseRequest { + bytes channel_id = 1; +} + +message AbortCooperativeCloseResponse { + ArkChannel channel = 1; +} + +message CooperativeCloseRequest { + bytes client_delivery_script = 1; + bytes hub_delivery_script = 2; + reserved 3; + reserved "fee_rate_sat_per_kw"; +} + +message CooperativeCloseProposal { + bytes transaction = 1; + uint64 commitment_height = 2; + int64 client_balance_sat = 3; + int64 hub_balance_sat = 4; + int64 client_output_sat = 5; + int64 hub_output_sat = 6; + reserved 7; + reserved "fee_sat"; +} + +message CooperativeClose { + CooperativeCloseProposal proposal = 1; + bytes transaction = 2; + bytes txid = 3; +} diff --git a/rpc/arkchannelrpc/ark_channel_peer.proto b/rpc/arkchannelrpc/ark_channel_peer.proto new file mode 100644 index 000000000..beacb5c29 --- /dev/null +++ b/rpc/arkchannelrpc/ark_channel_peer.proto @@ -0,0 +1,68 @@ +syntax = "proto3"; + +package arkchannelrpc; + +import "ark_channel.proto"; + +option go_package = "github.com/lightninglabs/wavelength/rpc/arkchannelrpc"; + +// ArkChannelPeerService coordinates authenticated cooperative closes. +// It is served only over the peer mailbox, never through local gRPC. +service ArkChannelPeerService { + // GetCooperativeCloseTerms quotes the two payout destinations. It does not + // reserve, sign, or quiesce; the client persists the terms first. + rpc GetCooperativeCloseTerms (GetCooperativeCloseTermsRequest) + returns (GetCooperativeCloseTermsResponse); + + // CompleteCooperativeClose lets the hub validate clean lnd balances and + // durably authorize the exact 3-of-3 OOR checkpoint. The client and Ark + // operator sign later in the ordinary OOR protocol. + rpc CompleteCooperativeClose (CompleteCooperativeCloseRequest) + returns (CompleteCooperativeCloseResponse); + + // ConfirmCooperativeClose proves the client durably received the exact + // hub authorization before OOR submission can start. + rpc ConfirmCooperativeClose (ConfirmCooperativeCloseRequest) + returns (ConfirmCooperativeCloseResponse); + + // PublishCooperativeClose reports the finalized ordinary OOR session and + // waits for the hub to observe its replacement VTXO and archive lnd. + rpc PublishCooperativeClose (PublishCooperativeCloseRequest) + returns (PublishCooperativeCloseResponse); + + // AbortCooperativeClose releases the hub's quiescence barrier before the + // ordinary OOR crosses its signing point of no return. + rpc AbortCooperativeClose (AbortCooperativeCloseRequest) + returns (AbortCooperativeCloseResponse); +} + +// ArkChannelFundingPeerService coordinates authenticated channel creation +// and the public Lightning bridge. It is served only over the peer mailbox. +service ArkChannelFundingPeerService { + rpc GetPeerInfo (GetPeerInfoRequest) returns (GetPeerInfoResponse); + rpc RegisterPromotion (RegisterPromotionRequest) + returns (RegisterPromotionResponse); + rpc GetFundingChannel (GetFundingChannelRequest) + returns (GetFundingChannelResponse); + rpc BindPreparedOOR (BindPreparedOORRequest) + returns (BindPreparedOORResponse); + rpc SignBacking (SignBackingRequest) returns (SignBackingResponse); + rpc InstallBacking (InstallBackingRequest) returns (InstallBackingResponse); + rpc InstallRecoveryPackage (InstallRecoveryPackageRequest) + returns (InstallRecoveryPackageResponse); + rpc FundingFinalized (FundingStatusRequest) returns (FundingStatusResponse); + rpc ChannelActive (FundingStatusRequest) returns (FundingStatusResponse); + // ApplyChannelEvent accepts only peer-owned facts. The receiver must bind + // party-bearing events to the authenticated mailbox party and reject + // local lnd, chain, or publication evidence. + rpc ApplyChannelEvent (ApplyChannelEventRequest) + returns (ApplyChannelEventResponse); + rpc PrepareOutgoingPayment (PrepareOutgoingPaymentRequest) + returns (PrepareOutgoingPaymentResponse); + rpc CancelOutgoingPayment (CancelOutgoingPaymentRequest) + returns (CancelOutgoingPaymentResponse); + rpc RegisterIncomingPayment (RegisterIncomingPaymentRequest) + returns (RegisterIncomingPaymentResponse); + rpc CancelIncomingPayment (CancelIncomingPaymentRequest) + returns (CancelIncomingPaymentResponse); +} diff --git a/scripts/gen_protos.sh b/scripts/gen_protos.sh index 0ca981a47..f1f1be69f 100755 --- a/scripts/gen_protos.sh +++ b/scripts/gen_protos.sh @@ -39,12 +39,29 @@ function generate() { for file in *.proto; do echo " Generating ${file}" + # Local controls use gRPC; authenticated peer controls use only + # mailbox RPC. Do not generate the opposite transport adapter. + grpc=1 + mailbox=1 + case "${package}/${file}" in + rpc/arkchannelrpc/ark_channel.proto) mailbox=0 ;; + rpc/arkchannelrpc/ark_channel_peer.proto) grpc=0 ;; + mailbox/pb/*) mailbox=0 ;; + esac + # Generate the standard Go protos. protoc -I/usr/local/include -I"${googleapis_include}" -I. -I.. \ --go_out=. --go_opt=paths=source_relative \ - --go-grpc_out=. --go-grpc_opt=paths=source_relative \ "${file}" + if [ "${grpc}" = "1" ]; then + protoc -I/usr/local/include -I"${googleapis_include}" -I. -I.. \ + --go-grpc_out=. --go-grpc_opt=paths=source_relative \ + "${file}" + else + rm -f "${file%.proto}_grpc.pb.go" + fi + gateway_config="${file%.proto}.yaml" if [ "${gateway}" = "1" ] && [ -f "${gateway_config}" ]; then check_gateway_config "${file}" "${gateway_config}" @@ -59,10 +76,12 @@ function generate() { # # The mailbox edge proto (mailboxpb) defines the underlying transport and # should not get an RPC-over-mailbox overlay, so we exclude it. - if [ "${package}" != "mailbox/pb" ]; then + if [ "${mailbox}" = "1" ]; then protoc -I/usr/local/include -I"${googleapis_include}" -I. -I.. \ --mailboxrpc_out=. --mailboxrpc_opt=paths=source_relative \ "${file}" + else + rm -f "${file%.proto}_mailboxrpc.pb.go" fi done @@ -95,6 +114,9 @@ generate "rpc/swapclientrpc" 1 # Generate optional daemon-owned simplified wallet RPC protos. generate "rpc/wavewalletrpc" 1 +# Generate Ark-channel local and authenticated peer control protos. +generate "rpc/arkchannelrpc" + # Generate waverpc protos for the client daemon's own gRPC API. generate "waverpc" 1 From 9d06e13dce5f1cde7438faf8d05e00179e68807b Mon Sep 17 00:00:00 2001 From: sputn1ck Date: Wed, 18 Nov 2026 18:44:17 +0100 Subject: [PATCH 2/7] multi: Generate channel RPC and storage bindings Generate the local and peer transports separately so the mailbox accepts only the authenticated peer service. --- db/sqlc/ark_channels.sql.go | 769 +++ db/sqlc/models.go | 52 + db/sqlc/querier.go | 15 + db/sqlc/schemas/generated_schema.sql | 108 + rpc/arkchannelrpc/ark_channel.pb.go | 4119 +++++++++++++++++ rpc/arkchannelrpc/ark_channel_grpc.pb.go | 339 ++ rpc/arkchannelrpc/ark_channel_peer.pb.go | 156 + .../ark_channel_peer_mailboxrpc.pb.go | 717 +++ rpc/arkchannelrpc/transport_test.go | 101 + 9 files changed, 6376 insertions(+) create mode 100644 db/sqlc/ark_channels.sql.go create mode 100644 rpc/arkchannelrpc/ark_channel.pb.go create mode 100644 rpc/arkchannelrpc/ark_channel_grpc.pb.go create mode 100644 rpc/arkchannelrpc/ark_channel_peer.pb.go create mode 100644 rpc/arkchannelrpc/ark_channel_peer_mailboxrpc.pb.go create mode 100644 rpc/arkchannelrpc/transport_test.go diff --git a/db/sqlc/ark_channels.sql.go b/db/sqlc/ark_channels.sql.go new file mode 100644 index 000000000..dbb796e5c --- /dev/null +++ b/db/sqlc/ark_channels.sql.go @@ -0,0 +1,769 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.29.0 +// source: ark_channels.sql + +package sqlc + +import ( + "context" + "database/sql" +) + +const AuthorizeArkFundingBacking = `-- name: AuthorizeArkFundingBacking :execrows +UPDATE ark_channels SET authorized_backing_txid = $1, + revision = revision + 1, updated_at = $2 +WHERE channel_id = $3 AND revision = $4 + AND client_node_key = $5 + AND authorized_backing_txid IS NULL AND phase = 2 +` + +type AuthorizeArkFundingBackingParams struct { + Txid []byte + UpdatedAt int64 + ChannelID []byte + Revision int64 + OwnerKey []byte +} + +func (q *Queries) AuthorizeArkFundingBacking(ctx context.Context, arg AuthorizeArkFundingBackingParams) (int64, error) { + result, err := q.db.ExecContext(ctx, AuthorizeArkFundingBacking, + arg.Txid, + arg.UpdatedAt, + arg.ChannelID, + arg.Revision, + arg.OwnerKey, + ) + if err != nil { + return 0, err + } + return result.RowsAffected() +} + +const CompareAndSwapArkChannel = `-- name: CompareAndSwapArkChannel :execrows +UPDATE ark_channels SET + phase = $3, + oor_session_id = $4, + source_index = $5, + source_amount = $6, + source_ark_tx = $7, + backing_tx = $8, + channel_point_txid = $9, + channel_point_index = $10, + client_finalized = $11, + hub_finalized = $12, + oor_finalized = $13, + oor_aborted = $14, + client_recovery_ready = $15, + hub_recovery_ready = $16, + source_spent_outpoint_txid = $17, + source_spent_outpoint_index = $18, + source_spending_txid = $19, + backing_published = $20, + close_initiator = $21, + close_client_script = $22, + close_hub_script = $23, + close_fee_rate_sat_per_kw = $24, + cooperative_close_tx = $25, + cooperative_close_txid = $26, + close_commitment_height = $27, + close_client_balance = $28, + close_hub_balance = $29, + failure = $30, + pre_ponr_started_at = COALESCE( + pre_ponr_started_at, $32 + ), + revision = revision + 1, + updated_at = $31 +WHERE channel_id = $1 AND revision = $2 + AND client_node_key = $33 +` + +type CompareAndSwapArkChannelParams struct { + ChannelID []byte + Revision int64 + Phase int32 + OorSessionID []byte + SourceIndex sql.NullInt64 + SourceAmount sql.NullInt64 + SourceArkTx []byte + BackingTx []byte + ChannelPointTxid []byte + ChannelPointIndex sql.NullInt64 + ClientFinalized bool + HubFinalized bool + OorFinalized bool + OorAborted bool + ClientRecoveryReady bool + HubRecoveryReady bool + SourceSpentOutpointTxid []byte + SourceSpentOutpointIndex sql.NullInt64 + SourceSpendingTxid []byte + BackingPublished bool + CloseInitiator sql.NullInt32 + CloseClientScript []byte + CloseHubScript []byte + CloseFeeRateSatPerKw sql.NullInt64 + CooperativeCloseTx []byte + CooperativeCloseTxid []byte + CloseCommitmentHeight sql.NullInt64 + CloseClientBalance sql.NullInt64 + CloseHubBalance sql.NullInt64 + Failure sql.NullString + UpdatedAt int64 + PrePonrStartedAt sql.NullInt64 + OwnerKey []byte +} + +func (q *Queries) CompareAndSwapArkChannel(ctx context.Context, arg CompareAndSwapArkChannelParams) (int64, error) { + result, err := q.db.ExecContext(ctx, CompareAndSwapArkChannel, + arg.ChannelID, + arg.Revision, + arg.Phase, + arg.OorSessionID, + arg.SourceIndex, + arg.SourceAmount, + arg.SourceArkTx, + arg.BackingTx, + arg.ChannelPointTxid, + arg.ChannelPointIndex, + arg.ClientFinalized, + arg.HubFinalized, + arg.OorFinalized, + arg.OorAborted, + arg.ClientRecoveryReady, + arg.HubRecoveryReady, + arg.SourceSpentOutpointTxid, + arg.SourceSpentOutpointIndex, + arg.SourceSpendingTxid, + arg.BackingPublished, + arg.CloseInitiator, + arg.CloseClientScript, + arg.CloseHubScript, + arg.CloseFeeRateSatPerKw, + arg.CooperativeCloseTx, + arg.CooperativeCloseTxid, + arg.CloseCommitmentHeight, + arg.CloseClientBalance, + arg.CloseHubBalance, + arg.Failure, + arg.UpdatedAt, + arg.PrePonrStartedAt, + arg.OwnerKey, + ) + if err != nil { + return 0, err + } + return result.RowsAffected() +} + +const GetArkChannel = `-- name: GetArkChannel :one +SELECT channel_id, pending_channel_id, reserved_scid, capacity, client_node_key, hub_node_key, client_ark_key, hub_ark_key, ark_operator_key, client_channel_key, hub_channel_key, funder_key, channel_delay, funder_delay, min_exit_delay, phase, oor_session_id, source_index, source_amount, source_ark_tx, backing_tx, channel_point_txid, channel_point_index, authorized_backing_txid, funding_signature, client_finalized, hub_finalized, oor_finalized, oor_aborted, backing_published, close_initiator, close_client_script, close_hub_script, close_fee_rate_sat_per_kw, cooperative_close_tx, cooperative_close_txid, close_commitment_height, close_client_balance, close_hub_balance, client_recovery_ready, hub_recovery_ready, source_spent_outpoint_txid, source_spent_outpoint_index, source_spending_txid, pre_ponr_started_at, failure, revision, created_at, updated_at FROM ark_channels +WHERE channel_id = $1 +` + +func (q *Queries) GetArkChannel(ctx context.Context, channelID []byte) (ArkChannel, error) { + row := q.db.QueryRowContext(ctx, GetArkChannel, channelID) + var i ArkChannel + err := row.Scan( + &i.ChannelID, + &i.PendingChannelID, + &i.ReservedScid, + &i.Capacity, + &i.ClientNodeKey, + &i.HubNodeKey, + &i.ClientArkKey, + &i.HubArkKey, + &i.ArkOperatorKey, + &i.ClientChannelKey, + &i.HubChannelKey, + &i.FunderKey, + &i.ChannelDelay, + &i.FunderDelay, + &i.MinExitDelay, + &i.Phase, + &i.OorSessionID, + &i.SourceIndex, + &i.SourceAmount, + &i.SourceArkTx, + &i.BackingTx, + &i.ChannelPointTxid, + &i.ChannelPointIndex, + &i.AuthorizedBackingTxid, + &i.FundingSignature, + &i.ClientFinalized, + &i.HubFinalized, + &i.OorFinalized, + &i.OorAborted, + &i.BackingPublished, + &i.CloseInitiator, + &i.CloseClientScript, + &i.CloseHubScript, + &i.CloseFeeRateSatPerKw, + &i.CooperativeCloseTx, + &i.CooperativeCloseTxid, + &i.CloseCommitmentHeight, + &i.CloseClientBalance, + &i.CloseHubBalance, + &i.ClientRecoveryReady, + &i.HubRecoveryReady, + &i.SourceSpentOutpointTxid, + &i.SourceSpentOutpointIndex, + &i.SourceSpendingTxid, + &i.PrePonrStartedAt, + &i.Failure, + &i.Revision, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const GetArkChannelByChannelPoint = `-- name: GetArkChannelByChannelPoint :one +SELECT channel_id, pending_channel_id, reserved_scid, capacity, client_node_key, hub_node_key, client_ark_key, hub_ark_key, ark_operator_key, client_channel_key, hub_channel_key, funder_key, channel_delay, funder_delay, min_exit_delay, phase, oor_session_id, source_index, source_amount, source_ark_tx, backing_tx, channel_point_txid, channel_point_index, authorized_backing_txid, funding_signature, client_finalized, hub_finalized, oor_finalized, oor_aborted, backing_published, close_initiator, close_client_script, close_hub_script, close_fee_rate_sat_per_kw, cooperative_close_tx, cooperative_close_txid, close_commitment_height, close_client_balance, close_hub_balance, client_recovery_ready, hub_recovery_ready, source_spent_outpoint_txid, source_spent_outpoint_index, source_spending_txid, pre_ponr_started_at, failure, revision, created_at, updated_at FROM ark_channels +WHERE channel_point_txid = $1 AND channel_point_index = $2 +` + +type GetArkChannelByChannelPointParams struct { + ChannelPointTxid []byte + ChannelPointIndex sql.NullInt64 +} + +func (q *Queries) GetArkChannelByChannelPoint(ctx context.Context, arg GetArkChannelByChannelPointParams) (ArkChannel, error) { + row := q.db.QueryRowContext(ctx, GetArkChannelByChannelPoint, arg.ChannelPointTxid, arg.ChannelPointIndex) + var i ArkChannel + err := row.Scan( + &i.ChannelID, + &i.PendingChannelID, + &i.ReservedScid, + &i.Capacity, + &i.ClientNodeKey, + &i.HubNodeKey, + &i.ClientArkKey, + &i.HubArkKey, + &i.ArkOperatorKey, + &i.ClientChannelKey, + &i.HubChannelKey, + &i.FunderKey, + &i.ChannelDelay, + &i.FunderDelay, + &i.MinExitDelay, + &i.Phase, + &i.OorSessionID, + &i.SourceIndex, + &i.SourceAmount, + &i.SourceArkTx, + &i.BackingTx, + &i.ChannelPointTxid, + &i.ChannelPointIndex, + &i.AuthorizedBackingTxid, + &i.FundingSignature, + &i.ClientFinalized, + &i.HubFinalized, + &i.OorFinalized, + &i.OorAborted, + &i.BackingPublished, + &i.CloseInitiator, + &i.CloseClientScript, + &i.CloseHubScript, + &i.CloseFeeRateSatPerKw, + &i.CooperativeCloseTx, + &i.CooperativeCloseTxid, + &i.CloseCommitmentHeight, + &i.CloseClientBalance, + &i.CloseHubBalance, + &i.ClientRecoveryReady, + &i.HubRecoveryReady, + &i.SourceSpentOutpointTxid, + &i.SourceSpentOutpointIndex, + &i.SourceSpendingTxid, + &i.PrePonrStartedAt, + &i.Failure, + &i.Revision, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const GetArkChannelByPendingID = `-- name: GetArkChannelByPendingID :one +SELECT channel_id, pending_channel_id, reserved_scid, capacity, client_node_key, hub_node_key, client_ark_key, hub_ark_key, ark_operator_key, client_channel_key, hub_channel_key, funder_key, channel_delay, funder_delay, min_exit_delay, phase, oor_session_id, source_index, source_amount, source_ark_tx, backing_tx, channel_point_txid, channel_point_index, authorized_backing_txid, funding_signature, client_finalized, hub_finalized, oor_finalized, oor_aborted, backing_published, close_initiator, close_client_script, close_hub_script, close_fee_rate_sat_per_kw, cooperative_close_tx, cooperative_close_txid, close_commitment_height, close_client_balance, close_hub_balance, client_recovery_ready, hub_recovery_ready, source_spent_outpoint_txid, source_spent_outpoint_index, source_spending_txid, pre_ponr_started_at, failure, revision, created_at, updated_at FROM ark_channels +WHERE pending_channel_id = $1 +` + +func (q *Queries) GetArkChannelByPendingID(ctx context.Context, pendingChannelID []byte) (ArkChannel, error) { + row := q.db.QueryRowContext(ctx, GetArkChannelByPendingID, pendingChannelID) + var i ArkChannel + err := row.Scan( + &i.ChannelID, + &i.PendingChannelID, + &i.ReservedScid, + &i.Capacity, + &i.ClientNodeKey, + &i.HubNodeKey, + &i.ClientArkKey, + &i.HubArkKey, + &i.ArkOperatorKey, + &i.ClientChannelKey, + &i.HubChannelKey, + &i.FunderKey, + &i.ChannelDelay, + &i.FunderDelay, + &i.MinExitDelay, + &i.Phase, + &i.OorSessionID, + &i.SourceIndex, + &i.SourceAmount, + &i.SourceArkTx, + &i.BackingTx, + &i.ChannelPointTxid, + &i.ChannelPointIndex, + &i.AuthorizedBackingTxid, + &i.FundingSignature, + &i.ClientFinalized, + &i.HubFinalized, + &i.OorFinalized, + &i.OorAborted, + &i.BackingPublished, + &i.CloseInitiator, + &i.CloseClientScript, + &i.CloseHubScript, + &i.CloseFeeRateSatPerKw, + &i.CooperativeCloseTx, + &i.CooperativeCloseTxid, + &i.CloseCommitmentHeight, + &i.CloseClientBalance, + &i.CloseHubBalance, + &i.ClientRecoveryReady, + &i.HubRecoveryReady, + &i.SourceSpentOutpointTxid, + &i.SourceSpentOutpointIndex, + &i.SourceSpendingTxid, + &i.PrePonrStartedAt, + &i.Failure, + &i.Revision, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const GetArkChannelBySCID = `-- name: GetArkChannelBySCID :one +SELECT channel_id, pending_channel_id, reserved_scid, capacity, client_node_key, hub_node_key, client_ark_key, hub_ark_key, ark_operator_key, client_channel_key, hub_channel_key, funder_key, channel_delay, funder_delay, min_exit_delay, phase, oor_session_id, source_index, source_amount, source_ark_tx, backing_tx, channel_point_txid, channel_point_index, authorized_backing_txid, funding_signature, client_finalized, hub_finalized, oor_finalized, oor_aborted, backing_published, close_initiator, close_client_script, close_hub_script, close_fee_rate_sat_per_kw, cooperative_close_tx, cooperative_close_txid, close_commitment_height, close_client_balance, close_hub_balance, client_recovery_ready, hub_recovery_ready, source_spent_outpoint_txid, source_spent_outpoint_index, source_spending_txid, pre_ponr_started_at, failure, revision, created_at, updated_at FROM ark_channels WHERE reserved_scid = $1 +` + +func (q *Queries) GetArkChannelBySCID(ctx context.Context, reservedScid []byte) (ArkChannel, error) { + row := q.db.QueryRowContext(ctx, GetArkChannelBySCID, reservedScid) + var i ArkChannel + err := row.Scan( + &i.ChannelID, + &i.PendingChannelID, + &i.ReservedScid, + &i.Capacity, + &i.ClientNodeKey, + &i.HubNodeKey, + &i.ClientArkKey, + &i.HubArkKey, + &i.ArkOperatorKey, + &i.ClientChannelKey, + &i.HubChannelKey, + &i.FunderKey, + &i.ChannelDelay, + &i.FunderDelay, + &i.MinExitDelay, + &i.Phase, + &i.OorSessionID, + &i.SourceIndex, + &i.SourceAmount, + &i.SourceArkTx, + &i.BackingTx, + &i.ChannelPointTxid, + &i.ChannelPointIndex, + &i.AuthorizedBackingTxid, + &i.FundingSignature, + &i.ClientFinalized, + &i.HubFinalized, + &i.OorFinalized, + &i.OorAborted, + &i.BackingPublished, + &i.CloseInitiator, + &i.CloseClientScript, + &i.CloseHubScript, + &i.CloseFeeRateSatPerKw, + &i.CooperativeCloseTx, + &i.CooperativeCloseTxid, + &i.CloseCommitmentHeight, + &i.CloseClientBalance, + &i.CloseHubBalance, + &i.ClientRecoveryReady, + &i.HubRecoveryReady, + &i.SourceSpentOutpointTxid, + &i.SourceSpentOutpointIndex, + &i.SourceSpendingTxid, + &i.PrePonrStartedAt, + &i.Failure, + &i.Revision, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const InsertArkChannel = `-- name: InsertArkChannel :execrows + +INSERT INTO ark_channels ( + channel_id, pending_channel_id, reserved_scid, capacity, + client_node_key, hub_node_key, client_ark_key, + hub_ark_key, ark_operator_key, client_channel_key, hub_channel_key, + funder_key, channel_delay, funder_delay, min_exit_delay, phase, + oor_session_id, source_index, source_amount, source_ark_tx, + backing_tx, channel_point_txid, channel_point_index, client_finalized, + hub_finalized, oor_finalized, oor_aborted, backing_published, + client_recovery_ready, hub_recovery_ready, + source_spent_outpoint_txid, + source_spent_outpoint_index, source_spending_txid, + close_initiator, close_client_script, close_hub_script, + close_fee_rate_sat_per_kw, cooperative_close_tx, + cooperative_close_txid, close_commitment_height, close_client_balance, + close_hub_balance, failure, revision, created_at, + updated_at, pre_ponr_started_at +) 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, $35, $36, $37, $38, $39, $40, + $41, $42, $43, $44, $45, $46, + $47 +) +ON CONFLICT (channel_id) DO NOTHING +` + +type InsertArkChannelParams struct { + ChannelID []byte + PendingChannelID []byte + ReservedScid []byte + Capacity int64 + ClientNodeKey []byte + HubNodeKey []byte + ClientArkKey []byte + HubArkKey []byte + ArkOperatorKey []byte + ClientChannelKey []byte + HubChannelKey []byte + FunderKey []byte + ChannelDelay int64 + FunderDelay int64 + MinExitDelay int64 + Phase int32 + OorSessionID []byte + SourceIndex sql.NullInt64 + SourceAmount sql.NullInt64 + SourceArkTx []byte + BackingTx []byte + ChannelPointTxid []byte + ChannelPointIndex sql.NullInt64 + ClientFinalized bool + HubFinalized bool + OorFinalized bool + OorAborted bool + BackingPublished bool + ClientRecoveryReady bool + HubRecoveryReady bool + SourceSpentOutpointTxid []byte + SourceSpentOutpointIndex sql.NullInt64 + SourceSpendingTxid []byte + CloseInitiator sql.NullInt32 + CloseClientScript []byte + CloseHubScript []byte + CloseFeeRateSatPerKw sql.NullInt64 + CooperativeCloseTx []byte + CooperativeCloseTxid []byte + CloseCommitmentHeight sql.NullInt64 + CloseClientBalance sql.NullInt64 + CloseHubBalance sql.NullInt64 + Failure sql.NullString + Revision int64 + CreatedAt int64 + UpdatedAt int64 + PrePonrStartedAt sql.NullInt64 +} + +// Ark channel coordination queries. +func (q *Queries) InsertArkChannel(ctx context.Context, arg InsertArkChannelParams) (int64, error) { + result, err := q.db.ExecContext(ctx, InsertArkChannel, + arg.ChannelID, + arg.PendingChannelID, + arg.ReservedScid, + arg.Capacity, + arg.ClientNodeKey, + arg.HubNodeKey, + arg.ClientArkKey, + arg.HubArkKey, + arg.ArkOperatorKey, + arg.ClientChannelKey, + arg.HubChannelKey, + arg.FunderKey, + arg.ChannelDelay, + arg.FunderDelay, + arg.MinExitDelay, + arg.Phase, + arg.OorSessionID, + arg.SourceIndex, + arg.SourceAmount, + arg.SourceArkTx, + arg.BackingTx, + arg.ChannelPointTxid, + arg.ChannelPointIndex, + arg.ClientFinalized, + arg.HubFinalized, + arg.OorFinalized, + arg.OorAborted, + arg.BackingPublished, + arg.ClientRecoveryReady, + arg.HubRecoveryReady, + arg.SourceSpentOutpointTxid, + arg.SourceSpentOutpointIndex, + arg.SourceSpendingTxid, + arg.CloseInitiator, + arg.CloseClientScript, + arg.CloseHubScript, + arg.CloseFeeRateSatPerKw, + arg.CooperativeCloseTx, + arg.CooperativeCloseTxid, + arg.CloseCommitmentHeight, + arg.CloseClientBalance, + arg.CloseHubBalance, + arg.Failure, + arg.Revision, + arg.CreatedAt, + arg.UpdatedAt, + arg.PrePonrStartedAt, + ) + if err != nil { + return 0, err + } + return result.RowsAffected() +} + +const ListArkRecoveryPeers = `-- name: ListArkRecoveryPeers :many +SELECT DISTINCT client_node_key FROM ark_channels +WHERE phase NOT IN (8, 10) OR (phase = 8 AND cooperative_close_txid IS NOT NULL) +ORDER BY client_node_key +` + +func (q *Queries) ListArkRecoveryPeers(ctx context.Context) ([][]byte, error) { + rows, err := q.db.QueryContext(ctx, ListArkRecoveryPeers) + if err != nil { + return nil, err + } + defer rows.Close() + var items [][]byte + for rows.Next() { + var client_node_key []byte + if err := rows.Scan(&client_node_key); err != nil { + return nil, err + } + items = append(items, client_node_key) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const ListNonTerminalArkChannels = `-- name: ListNonTerminalArkChannels :many +SELECT channel_id, pending_channel_id, reserved_scid, capacity, client_node_key, hub_node_key, client_ark_key, hub_ark_key, ark_operator_key, client_channel_key, hub_channel_key, funder_key, channel_delay, funder_delay, min_exit_delay, phase, oor_session_id, source_index, source_amount, source_ark_tx, backing_tx, channel_point_txid, channel_point_index, authorized_backing_txid, funding_signature, client_finalized, hub_finalized, oor_finalized, oor_aborted, backing_published, close_initiator, close_client_script, close_hub_script, close_fee_rate_sat_per_kw, cooperative_close_tx, cooperative_close_txid, close_commitment_height, close_client_balance, close_hub_balance, client_recovery_ready, hub_recovery_ready, source_spent_outpoint_txid, source_spent_outpoint_index, source_spending_txid, pre_ponr_started_at, failure, revision, created_at, updated_at FROM ark_channels +WHERE phase NOT IN (8, 10) + OR (phase = 8 AND cooperative_close_txid IS NOT NULL) +ORDER BY created_at ASC, channel_id ASC +` + +// Phase 8 is closed and phase 10 is failed. A cooperatively closed channel +// remains resumable because its signed replacement VTXOs still need source +// ancestry defense. Cancelling also remains resumable. +func (q *Queries) ListNonTerminalArkChannels(ctx context.Context) ([]ArkChannel, error) { + rows, err := q.db.QueryContext(ctx, ListNonTerminalArkChannels) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ArkChannel + for rows.Next() { + var i ArkChannel + if err := rows.Scan( + &i.ChannelID, + &i.PendingChannelID, + &i.ReservedScid, + &i.Capacity, + &i.ClientNodeKey, + &i.HubNodeKey, + &i.ClientArkKey, + &i.HubArkKey, + &i.ArkOperatorKey, + &i.ClientChannelKey, + &i.HubChannelKey, + &i.FunderKey, + &i.ChannelDelay, + &i.FunderDelay, + &i.MinExitDelay, + &i.Phase, + &i.OorSessionID, + &i.SourceIndex, + &i.SourceAmount, + &i.SourceArkTx, + &i.BackingTx, + &i.ChannelPointTxid, + &i.ChannelPointIndex, + &i.AuthorizedBackingTxid, + &i.FundingSignature, + &i.ClientFinalized, + &i.HubFinalized, + &i.OorFinalized, + &i.OorAborted, + &i.BackingPublished, + &i.CloseInitiator, + &i.CloseClientScript, + &i.CloseHubScript, + &i.CloseFeeRateSatPerKw, + &i.CooperativeCloseTx, + &i.CooperativeCloseTxid, + &i.CloseCommitmentHeight, + &i.CloseClientBalance, + &i.CloseHubBalance, + &i.ClientRecoveryReady, + &i.HubRecoveryReady, + &i.SourceSpentOutpointTxid, + &i.SourceSpentOutpointIndex, + &i.SourceSpendingTxid, + &i.PrePonrStartedAt, + &i.Failure, + &i.Revision, + &i.CreatedAt, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const ListPeerArkChannels = `-- name: ListPeerArkChannels :many +SELECT channel_id, pending_channel_id, reserved_scid, capacity, client_node_key, hub_node_key, client_ark_key, hub_ark_key, ark_operator_key, client_channel_key, hub_channel_key, funder_key, channel_delay, funder_delay, min_exit_delay, phase, oor_session_id, source_index, source_amount, source_ark_tx, backing_tx, channel_point_txid, channel_point_index, authorized_backing_txid, funding_signature, client_finalized, hub_finalized, oor_finalized, oor_aborted, backing_published, close_initiator, close_client_script, close_hub_script, close_fee_rate_sat_per_kw, cooperative_close_tx, cooperative_close_txid, close_commitment_height, close_client_balance, close_hub_balance, client_recovery_ready, hub_recovery_ready, source_spent_outpoint_txid, source_spent_outpoint_index, source_spending_txid, pre_ponr_started_at, failure, revision, created_at, updated_at FROM ark_channels +WHERE client_node_key = $1 AND + (phase NOT IN (8, 10) OR (phase = 8 AND cooperative_close_txid IS NOT NULL)) +ORDER BY created_at ASC, channel_id ASC +` + +func (q *Queries) ListPeerArkChannels(ctx context.Context, clientNodeKey []byte) ([]ArkChannel, error) { + rows, err := q.db.QueryContext(ctx, ListPeerArkChannels, clientNodeKey) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ArkChannel + for rows.Next() { + var i ArkChannel + if err := rows.Scan( + &i.ChannelID, + &i.PendingChannelID, + &i.ReservedScid, + &i.Capacity, + &i.ClientNodeKey, + &i.HubNodeKey, + &i.ClientArkKey, + &i.HubArkKey, + &i.ArkOperatorKey, + &i.ClientChannelKey, + &i.HubChannelKey, + &i.FunderKey, + &i.ChannelDelay, + &i.FunderDelay, + &i.MinExitDelay, + &i.Phase, + &i.OorSessionID, + &i.SourceIndex, + &i.SourceAmount, + &i.SourceArkTx, + &i.BackingTx, + &i.ChannelPointTxid, + &i.ChannelPointIndex, + &i.AuthorizedBackingTxid, + &i.FundingSignature, + &i.ClientFinalized, + &i.HubFinalized, + &i.OorFinalized, + &i.OorAborted, + &i.BackingPublished, + &i.CloseInitiator, + &i.CloseClientScript, + &i.CloseHubScript, + &i.CloseFeeRateSatPerKw, + &i.CooperativeCloseTx, + &i.CooperativeCloseTxid, + &i.CloseCommitmentHeight, + &i.CloseClientBalance, + &i.CloseHubBalance, + &i.ClientRecoveryReady, + &i.HubRecoveryReady, + &i.SourceSpentOutpointTxid, + &i.SourceSpentOutpointIndex, + &i.SourceSpendingTxid, + &i.PrePonrStartedAt, + &i.Failure, + &i.Revision, + &i.CreatedAt, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const RecordArkFundingSignature = `-- name: RecordArkFundingSignature :execrows +UPDATE ark_channels SET funding_signature = $1, + revision = revision + 1, updated_at = $2 +WHERE channel_id = $3 AND revision = $4 + AND client_node_key = $5 AND phase = 2 + AND authorized_backing_txid = $6 AND funding_signature IS NULL +` + +type RecordArkFundingSignatureParams struct { + Signature []byte + UpdatedAt int64 + ChannelID []byte + Revision int64 + OwnerKey []byte + Txid []byte +} + +func (q *Queries) RecordArkFundingSignature(ctx context.Context, arg RecordArkFundingSignatureParams) (int64, error) { + result, err := q.db.ExecContext(ctx, RecordArkFundingSignature, + arg.Signature, + arg.UpdatedAt, + arg.ChannelID, + arg.Revision, + arg.OwnerKey, + arg.Txid, + ) + if err != nil { + return 0, err + } + return result.RowsAffected() +} diff --git a/db/sqlc/models.go b/db/sqlc/models.go index 43cfee991..140e2cd70 100644 --- a/db/sqlc/models.go +++ b/db/sqlc/models.go @@ -63,6 +63,58 @@ type ActivityStatus struct { Name string } +type ArkChannel struct { + ChannelID []byte + PendingChannelID []byte + ReservedScid []byte + Capacity int64 + ClientNodeKey []byte + HubNodeKey []byte + ClientArkKey []byte + HubArkKey []byte + ArkOperatorKey []byte + ClientChannelKey []byte + HubChannelKey []byte + FunderKey []byte + ChannelDelay int64 + FunderDelay int64 + MinExitDelay int64 + Phase int32 + OorSessionID []byte + SourceIndex sql.NullInt64 + SourceAmount sql.NullInt64 + SourceArkTx []byte + BackingTx []byte + ChannelPointTxid []byte + ChannelPointIndex sql.NullInt64 + AuthorizedBackingTxid []byte + FundingSignature []byte + ClientFinalized bool + HubFinalized bool + OorFinalized bool + OorAborted bool + BackingPublished bool + CloseInitiator sql.NullInt32 + CloseClientScript []byte + CloseHubScript []byte + CloseFeeRateSatPerKw sql.NullInt64 + CooperativeCloseTx []byte + CooperativeCloseTxid []byte + CloseCommitmentHeight sql.NullInt64 + CloseClientBalance sql.NullInt64 + CloseHubBalance sql.NullInt64 + ClientRecoveryReady bool + HubRecoveryReady bool + SourceSpentOutpointTxid []byte + SourceSpentOutpointIndex sql.NullInt64 + SourceSpendingTxid []byte + PrePonrStartedAt sql.NullInt64 + Failure sql.NullString + Revision int64 + CreatedAt int64 + UpdatedAt int64 +} + type AssetDeposit struct { RequestID string Status string diff --git a/db/sqlc/querier.go b/db/sqlc/querier.go index 35bb3f0b7..1aa6b9921 100644 --- a/db/sqlc/querier.go +++ b/db/sqlc/querier.go @@ -17,6 +17,7 @@ type Querier interface { // returns the event_seq the database assigned (monotonic, not necessarily // contiguous). Callers use it as the resumable-subscribe cursor for the update. AppendActivityEvent(ctx context.Context, arg AppendActivityEventParams) (int64, error) + AuthorizeArkFundingBacking(ctx context.Context, arg AuthorizeArkFundingBackingParams) (int64, error) // BackfillLedgerRoundUuid stamps the canonical UUID string form onto every // entry carrying the given raw round_id that does not have one yet. The // round_uuid IS NULL guard makes re-running the backfill (e.g. after a crash @@ -25,6 +26,7 @@ type Querier interface { CancelVHTLCRecoveryJob(ctx context.Context, arg CancelVHTLCRecoveryJobParams) (int64, error) ClearPendingIntentAnchorByOutpoint(ctx context.Context, arg ClearPendingIntentAnchorByOutpointParams) error CloseRoundAdmissionDeadline(ctx context.Context, roundID string) error + CompareAndSwapArkChannel(ctx context.Context, arg CompareAndSwapArkChannelParams) (int64, error) CompleteVHTLCRecoveryJob(ctx context.Context, arg CompleteVHTLCRecoveryJobParams) (int64, error) ConstrainRoundAdmissionDeadline(ctx context.Context, arg ConstrainRoundAdmissionDeadlineParams) error // CountActivityEntriesByStatus returns the number of current-state rows in the @@ -105,6 +107,10 @@ type Querier interface { FinalizeRound(ctx context.Context, arg FinalizeRoundParams) error // GetActivityEntry returns one entry by its canonical id. GetActivityEntry(ctx context.Context, canonicalID string) (ActivityEntry, error) + GetArkChannel(ctx context.Context, channelID []byte) (ArkChannel, error) + GetArkChannelByChannelPoint(ctx context.Context, arg GetArkChannelByChannelPointParams) (ArkChannel, error) + GetArkChannelByPendingID(ctx context.Context, pendingChannelID []byte) (ArkChannel, error) + GetArkChannelBySCID(ctx context.Context, reservedScid []byte) (ArkChannel, error) GetAssetDeposit(ctx context.Context, requestID string) (AssetDeposit, error) GetAssetDepositByOutpoint(ctx context.Context, arg GetAssetDepositByOutpointParams) (AssetDeposit, error) GetAssetDepositClaim(ctx context.Context, requestID string) (AssetDepositClaim, error) @@ -190,6 +196,8 @@ type Querier interface { // The ledger actor uses it to recognise a boarding deposit's funding input as // a UTXO whose value it already credited to wallet_balance. GetWalletUTXOLogCreatedByOutpoint(ctx context.Context, arg GetWalletUTXOLogCreatedByOutpointParams) (WalletUtxoLog, error) + // Ark channel coordination queries. + InsertArkChannel(ctx context.Context, arg InsertArkChannelParams) (int64, error) // InsertAssetDeposit records a deposit request before the asset backend // funds it. A request ID already recorded inserts nothing. InsertAssetDeposit(ctx context.Context, arg InsertAssetDepositParams) (int64, error) @@ -272,6 +280,7 @@ type Querier interface { ListAllCreditOperations(ctx context.Context) ([]CreditOperation, error) ListAllOORSessionRegistry(ctx context.Context) ([]OorSessionRegistry, error) ListAllVTXOs(ctx context.Context) ([]Vtxo, error) + ListArkRecoveryPeers(ctx context.Context) ([][]byte, error) ListAssetDepositClaimsByStatus(ctx context.Context, status string) ([]AssetDepositClaim, error) ListAssetDeposits(ctx context.Context) ([]AssetDeposit, error) ListAssetDepositsByStatus(ctx context.Context, status string) ([]AssetDeposit, error) @@ -397,6 +406,10 @@ type Querier interface { // Also filter on spent = FALSE to handle VTXOs marked spent via the earlier // flag before the status field was introduced. ListLiveVTXOs(ctx context.Context) ([]Vtxo, error) + // Phase 8 is closed and phase 10 is failed. A cooperatively closed channel + // remains resumable because its signed replacement VTXOs still need source + // ancestry defense. Cancelling also remains resumable. + ListNonTerminalArkChannels(ctx context.Context) ([]ArkChannel, error) // Status 1 = Completed, 2 = Failed (anchored to Go iota in // db/credit_operation_store.go CreditOpStatus). ListNonTerminalCreditOperations(ctx context.Context) ([]CreditOperation, error) @@ -421,6 +434,7 @@ type Querier interface { // ListOwnedAssetEngineProofs returns every output the wallet holds or held. ListOwnedAssetEngineProofs(ctx context.Context) ([]AssetEngineProof, error) ListOwnedReceiveScripts(ctx context.Context) ([]OwnedReceiveScript, error) + ListPeerArkChannels(ctx context.Context, clientNodeKey []byte) ([]ArkChannel, error) // Only status = 'pending' rows replay; a 'failed' intent is terminally // retired and must not be re-submitted on restart. ListPendingBoardIntents(ctx context.Context) ([]ListPendingBoardIntentsRow, error) @@ -575,6 +589,7 @@ type Querier interface { // while returning the current canonical projection for every selected event. // Removed internal activity has no replay rows and cannot reappear here. ReadCurrentActivityEvents(ctx context.Context, arg ReadCurrentActivityEventsParams) ([]ReadCurrentActivityEventsRow, error) + RecordArkFundingSignature(ctx context.Context, arg RecordArkFundingSignatureParams) (int64, error) RenewOwnedReceiveScriptRegistration(ctx context.Context, arg RenewOwnedReceiveScriptRegistrationParams) (int64, error) // RepairCreditReceivePollCapActivity narrowly reopens an inbound credit // receive that an older client marked terminal after exhausting its local poll diff --git a/db/sqlc/schemas/generated_schema.sql b/db/sqlc/schemas/generated_schema.sql index 6719b5a81..4d50074d1 100644 --- a/db/sqlc/schemas/generated_schema.sql +++ b/db/sqlc/schemas/generated_schema.sql @@ -78,6 +78,97 @@ CREATE TABLE activity_statuses ( name TEXT UNIQUE NOT NULL ); +CREATE TABLE ark_channels ( + channel_id BLOB PRIMARY KEY NOT NULL, + pending_channel_id BLOB NOT NULL UNIQUE, + reserved_scid BLOB NOT NULL, + capacity BIGINT NOT NULL CHECK (capacity > 0), + client_node_key BLOB NOT NULL, + hub_node_key BLOB NOT NULL, + client_ark_key BLOB NOT NULL, + hub_ark_key BLOB NOT NULL, + ark_operator_key BLOB NOT NULL, + client_channel_key BLOB NOT NULL, + hub_channel_key BLOB NOT NULL, + funder_key BLOB NOT NULL, + channel_delay BIGINT NOT NULL, + funder_delay BIGINT NOT NULL, + min_exit_delay BIGINT NOT NULL, + + phase INTEGER NOT NULL CHECK (phase BETWEEN 1 AND 13), + oor_session_id BLOB, + source_index BIGINT, + source_amount BIGINT, + source_ark_tx BLOB, + backing_tx BLOB, + channel_point_txid BLOB, + channel_point_index BIGINT, + -- The unsigned backing has exactly one output, at index zero. + authorized_backing_txid BLOB CHECK ( + authorized_backing_txid IS NULL OR + (length(authorized_backing_txid) = 32 AND oor_session_id IS NOT NULL AND + (channel_point_txid IS NULL OR + channel_point_txid = authorized_backing_txid)) + ), + funding_signature BLOB CHECK (funding_signature IS NULL OR + (authorized_backing_txid IS NOT NULL AND length(funding_signature) = 64)), + client_finalized BOOLEAN NOT NULL DEFAULT FALSE, + hub_finalized BOOLEAN NOT NULL DEFAULT FALSE, + oor_finalized BOOLEAN NOT NULL DEFAULT FALSE, + oor_aborted BOOLEAN NOT NULL DEFAULT FALSE, + backing_published BOOLEAN NOT NULL DEFAULT FALSE, + close_initiator INTEGER CHECK (close_initiator IN (1, 2)), + close_client_script BLOB, + close_hub_script BLOB, + close_fee_rate_sat_per_kw BIGINT, + cooperative_close_tx BLOB, + cooperative_close_txid BLOB, + close_commitment_height BIGINT, + close_client_balance BIGINT, + close_hub_balance BIGINT, + client_recovery_ready BOOLEAN NOT NULL DEFAULT FALSE, + hub_recovery_ready BOOLEAN NOT NULL DEFAULT FALSE, + source_spent_outpoint_txid BLOB, + source_spent_outpoint_index BIGINT, + source_spending_txid BLOB, + pre_ponr_started_at BIGINT, + failure TEXT, + + revision BIGINT NOT NULL CHECK (revision > 0), + created_at BIGINT NOT NULL, + updated_at BIGINT NOT NULL, + + CHECK ( + (oor_session_id IS NULL AND source_index IS NULL AND + source_amount IS NULL AND source_ark_tx IS NULL) OR + (oor_session_id IS NOT NULL AND source_index IS NOT NULL AND + source_amount IS NOT NULL AND source_ark_tx IS NOT NULL) + ), + CHECK ( + (backing_tx IS NULL AND channel_point_txid IS NULL AND + channel_point_index IS NULL) OR + (backing_tx IS NOT NULL AND channel_point_txid IS NOT NULL AND + channel_point_index IS NOT NULL) + ), + CHECK ( + (close_initiator IS NULL AND close_client_script IS NULL AND + close_hub_script IS NULL AND close_fee_rate_sat_per_kw IS NULL) OR + (close_initiator IS NOT NULL AND close_client_script IS NOT NULL AND + close_hub_script IS NOT NULL AND close_fee_rate_sat_per_kw IS NOT NULL) + ), + CHECK ( + (cooperative_close_tx IS NULL AND cooperative_close_txid IS NULL AND + close_commitment_height IS NULL AND close_client_balance IS NULL AND + close_hub_balance IS NULL) OR + (cooperative_close_tx IS NOT NULL AND cooperative_close_txid IS NOT NULL AND + close_commitment_height IS NOT NULL AND close_client_balance IS NOT NULL AND + close_hub_balance IS NOT NULL) + ), + CHECK (channel_delay >= 0 AND channel_delay <= 4294967295), + CHECK (funder_delay >= 0 AND funder_delay <= 4294967295), + CHECK (min_exit_delay >= 0 AND min_exit_delay <= 4294967295) +); + CREATE TABLE ask_results ( -- promise_id links to the original Ask message. promise_id TEXT PRIMARY KEY, @@ -560,6 +651,23 @@ CREATE INDEX idx_activity_entries_updated CREATE INDEX idx_activity_events_canonical ON activity_events (canonical_id); +CREATE UNIQUE INDEX idx_ark_channels_channel_point + ON ark_channels(channel_point_txid, channel_point_index) + WHERE channel_point_txid IS NOT NULL; + +CREATE INDEX idx_ark_channels_client_created + ON ark_channels(client_node_key, created_at, channel_id); + +CREATE INDEX idx_ark_channels_phase_created + ON ark_channels(phase, created_at ASC); + +CREATE UNIQUE INDEX idx_ark_channels_reserved_scid + ON ark_channels(reserved_scid); + +CREATE UNIQUE INDEX idx_ark_channels_source + ON ark_channels(oor_session_id, source_index) + WHERE oor_session_id IS NOT NULL AND source_index IS NOT NULL; + CREATE INDEX idx_ask_results_expires ON ask_results(expires_at); diff --git a/rpc/arkchannelrpc/ark_channel.pb.go b/rpc/arkchannelrpc/ark_channel.pb.go new file mode 100644 index 000000000..fae8af6ae --- /dev/null +++ b/rpc/arkchannelrpc/ark_channel.pb.go @@ -0,0 +1,4119 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc v3.21.12 +// source: ark_channel.proto + +package arkchannelrpc + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type ChannelEventType int32 + +const ( + ChannelEventType_CHANNEL_EVENT_TYPE_UNSPECIFIED ChannelEventType = 0 + ChannelEventType_CHANNEL_EVENT_TYPE_FUNDING_FINALIZED ChannelEventType = 1 + ChannelEventType_CHANNEL_EVENT_TYPE_OOR_FINALIZED ChannelEventType = 2 + ChannelEventType_CHANNEL_EVENT_TYPE_RECOVERY_PACKAGE_INSTALLED ChannelEventType = 6 + ChannelEventType_CHANNEL_EVENT_TYPE_OOR_ABORTED ChannelEventType = 9 +) + +// Enum value maps for ChannelEventType. +var ( + ChannelEventType_name = map[int32]string{ + 0: "CHANNEL_EVENT_TYPE_UNSPECIFIED", + 1: "CHANNEL_EVENT_TYPE_FUNDING_FINALIZED", + 2: "CHANNEL_EVENT_TYPE_OOR_FINALIZED", + 6: "CHANNEL_EVENT_TYPE_RECOVERY_PACKAGE_INSTALLED", + 9: "CHANNEL_EVENT_TYPE_OOR_ABORTED", + } + ChannelEventType_value = map[string]int32{ + "CHANNEL_EVENT_TYPE_UNSPECIFIED": 0, + "CHANNEL_EVENT_TYPE_FUNDING_FINALIZED": 1, + "CHANNEL_EVENT_TYPE_OOR_FINALIZED": 2, + "CHANNEL_EVENT_TYPE_RECOVERY_PACKAGE_INSTALLED": 6, + "CHANNEL_EVENT_TYPE_OOR_ABORTED": 9, + } +) + +func (x ChannelEventType) Enum() *ChannelEventType { + p := new(ChannelEventType) + *p = x + return p +} + +func (x ChannelEventType) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (ChannelEventType) Descriptor() protoreflect.EnumDescriptor { + return file_ark_channel_proto_enumTypes[0].Descriptor() +} + +func (ChannelEventType) Type() protoreflect.EnumType { + return &file_ark_channel_proto_enumTypes[0] +} + +func (x ChannelEventType) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use ChannelEventType.Descriptor instead. +func (ChannelEventType) EnumDescriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{0} +} + +type PromoteVTXORequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + AmountSat int64 `protobuf:"varint,1,opt,name=amount_sat,json=amountSat,proto3" json:"amount_sat,omitempty"` + IdempotencyKey string `protobuf:"bytes,2,opt,name=idempotency_key,json=idempotencyKey,proto3" json:"idempotency_key,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PromoteVTXORequest) Reset() { + *x = PromoteVTXORequest{} + mi := &file_ark_channel_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PromoteVTXORequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PromoteVTXORequest) ProtoMessage() {} + +func (x *PromoteVTXORequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PromoteVTXORequest.ProtoReflect.Descriptor instead. +func (*PromoteVTXORequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{0} +} + +func (x *PromoteVTXORequest) GetAmountSat() int64 { + if x != nil { + return x.AmountSat + } + return 0 +} + +func (x *PromoteVTXORequest) GetIdempotencyKey() string { + if x != nil { + return x.IdempotencyKey + } + return "" +} + +type PromoteVTXOResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Channel *ArkChannel `protobuf:"bytes,1,opt,name=channel,proto3" json:"channel,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PromoteVTXOResponse) Reset() { + *x = PromoteVTXOResponse{} + mi := &file_ark_channel_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PromoteVTXOResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PromoteVTXOResponse) ProtoMessage() {} + +func (x *PromoteVTXOResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PromoteVTXOResponse.ProtoReflect.Descriptor instead. +func (*PromoteVTXOResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{1} +} + +func (x *PromoteVTXOResponse) GetChannel() *ArkChannel { + if x != nil { + return x.Channel + } + return nil +} + +type PayLightningInvoiceRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + PaymentRequest string `protobuf:"bytes,1,opt,name=payment_request,json=paymentRequest,proto3" json:"payment_request,omitempty"` + MaxFeeSat uint64 `protobuf:"varint,2,opt,name=max_fee_sat,json=maxFeeSat,proto3" json:"max_fee_sat,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PayLightningInvoiceRequest) Reset() { + *x = PayLightningInvoiceRequest{} + mi := &file_ark_channel_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PayLightningInvoiceRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PayLightningInvoiceRequest) ProtoMessage() {} + +func (x *PayLightningInvoiceRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PayLightningInvoiceRequest.ProtoReflect.Descriptor instead. +func (*PayLightningInvoiceRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{2} +} + +func (x *PayLightningInvoiceRequest) GetPaymentRequest() string { + if x != nil { + return x.PaymentRequest + } + return "" +} + +func (x *PayLightningInvoiceRequest) GetMaxFeeSat() uint64 { + if x != nil { + return x.MaxFeeSat + } + return 0 +} + +type PayLightningInvoiceResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + PaymentHash []byte `protobuf:"bytes,1,opt,name=payment_hash,json=paymentHash,proto3" json:"payment_hash,omitempty"` + Preimage []byte `protobuf:"bytes,2,opt,name=preimage,proto3" json:"preimage,omitempty"` + PrivateAmountSat int64 `protobuf:"varint,3,opt,name=private_amount_sat,json=privateAmountSat,proto3" json:"private_amount_sat,omitempty"` + FeeSat int64 `protobuf:"varint,4,opt,name=fee_sat,json=feeSat,proto3" json:"fee_sat,omitempty"` + ChannelId []byte `protobuf:"bytes,5,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PayLightningInvoiceResponse) Reset() { + *x = PayLightningInvoiceResponse{} + mi := &file_ark_channel_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PayLightningInvoiceResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PayLightningInvoiceResponse) ProtoMessage() {} + +func (x *PayLightningInvoiceResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PayLightningInvoiceResponse.ProtoReflect.Descriptor instead. +func (*PayLightningInvoiceResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{3} +} + +func (x *PayLightningInvoiceResponse) GetPaymentHash() []byte { + if x != nil { + return x.PaymentHash + } + return nil +} + +func (x *PayLightningInvoiceResponse) GetPreimage() []byte { + if x != nil { + return x.Preimage + } + return nil +} + +func (x *PayLightningInvoiceResponse) GetPrivateAmountSat() int64 { + if x != nil { + return x.PrivateAmountSat + } + return 0 +} + +func (x *PayLightningInvoiceResponse) GetFeeSat() int64 { + if x != nil { + return x.FeeSat + } + return 0 +} + +func (x *PayLightningInvoiceResponse) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +type MaterializeAndForceCloseRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + ChannelId []byte `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *MaterializeAndForceCloseRequest) Reset() { + *x = MaterializeAndForceCloseRequest{} + mi := &file_ark_channel_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *MaterializeAndForceCloseRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MaterializeAndForceCloseRequest) ProtoMessage() {} + +func (x *MaterializeAndForceCloseRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[4] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MaterializeAndForceCloseRequest.ProtoReflect.Descriptor instead. +func (*MaterializeAndForceCloseRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{4} +} + +func (x *MaterializeAndForceCloseRequest) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +type MaterializeAndForceCloseResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Channel *ArkChannel `protobuf:"bytes,1,opt,name=channel,proto3" json:"channel,omitempty"` + BackingTxid []byte `protobuf:"bytes,2,opt,name=backing_txid,json=backingTxid,proto3" json:"backing_txid,omitempty"` + CommitmentTxid []byte `protobuf:"bytes,3,opt,name=commitment_txid,json=commitmentTxid,proto3" json:"commitment_txid,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *MaterializeAndForceCloseResponse) Reset() { + *x = MaterializeAndForceCloseResponse{} + mi := &file_ark_channel_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *MaterializeAndForceCloseResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MaterializeAndForceCloseResponse) ProtoMessage() {} + +func (x *MaterializeAndForceCloseResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[5] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MaterializeAndForceCloseResponse.ProtoReflect.Descriptor instead. +func (*MaterializeAndForceCloseResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{5} +} + +func (x *MaterializeAndForceCloseResponse) GetChannel() *ArkChannel { + if x != nil { + return x.Channel + } + return nil +} + +func (x *MaterializeAndForceCloseResponse) GetBackingTxid() []byte { + if x != nil { + return x.BackingTxid + } + return nil +} + +func (x *MaterializeAndForceCloseResponse) GetCommitmentTxid() []byte { + if x != nil { + return x.CommitmentTxid + } + return nil +} + +type GetPeerInfoRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetPeerInfoRequest) Reset() { + *x = GetPeerInfoRequest{} + mi := &file_ark_channel_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetPeerInfoRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetPeerInfoRequest) ProtoMessage() {} + +func (x *GetPeerInfoRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[6] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetPeerInfoRequest.ProtoReflect.Descriptor instead. +func (*GetPeerInfoRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{6} +} + +type GetPeerInfoResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + HubNodeKey []byte `protobuf:"bytes,1,opt,name=hub_node_key,json=hubNodeKey,proto3" json:"hub_node_key,omitempty"` + HubArkKey []byte `protobuf:"bytes,2,opt,name=hub_ark_key,json=hubArkKey,proto3" json:"hub_ark_key,omitempty"` + HubChannelKey []byte `protobuf:"bytes,3,opt,name=hub_channel_key,json=hubChannelKey,proto3" json:"hub_channel_key,omitempty"` + ArkOperatorKey []byte `protobuf:"bytes,4,opt,name=ark_operator_key,json=arkOperatorKey,proto3" json:"ark_operator_key,omitempty"` + ChannelDelay uint32 `protobuf:"varint,5,opt,name=channel_delay,json=channelDelay,proto3" json:"channel_delay,omitempty"` + FunderDelay uint32 `protobuf:"varint,6,opt,name=funder_delay,json=funderDelay,proto3" json:"funder_delay,omitempty"` + MinExitDelay uint32 `protobuf:"varint,7,opt,name=min_exit_delay,json=minExitDelay,proto3" json:"min_exit_delay,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetPeerInfoResponse) Reset() { + *x = GetPeerInfoResponse{} + mi := &file_ark_channel_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetPeerInfoResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetPeerInfoResponse) ProtoMessage() {} + +func (x *GetPeerInfoResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[7] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetPeerInfoResponse.ProtoReflect.Descriptor instead. +func (*GetPeerInfoResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{7} +} + +func (x *GetPeerInfoResponse) GetHubNodeKey() []byte { + if x != nil { + return x.HubNodeKey + } + return nil +} + +func (x *GetPeerInfoResponse) GetHubArkKey() []byte { + if x != nil { + return x.HubArkKey + } + return nil +} + +func (x *GetPeerInfoResponse) GetHubChannelKey() []byte { + if x != nil { + return x.HubChannelKey + } + return nil +} + +func (x *GetPeerInfoResponse) GetArkOperatorKey() []byte { + if x != nil { + return x.ArkOperatorKey + } + return nil +} + +func (x *GetPeerInfoResponse) GetChannelDelay() uint32 { + if x != nil { + return x.ChannelDelay + } + return 0 +} + +func (x *GetPeerInfoResponse) GetFunderDelay() uint32 { + if x != nil { + return x.FunderDelay + } + return 0 +} + +func (x *GetPeerInfoResponse) GetMinExitDelay() uint32 { + if x != nil { + return x.MinExitDelay + } + return 0 +} + +type RegisterPromotionRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Terms *ChannelTerms `protobuf:"bytes,1,opt,name=terms,proto3" json:"terms,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RegisterPromotionRequest) Reset() { + *x = RegisterPromotionRequest{} + mi := &file_ark_channel_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RegisterPromotionRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RegisterPromotionRequest) ProtoMessage() {} + +func (x *RegisterPromotionRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[8] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RegisterPromotionRequest.ProtoReflect.Descriptor instead. +func (*RegisterPromotionRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{8} +} + +func (x *RegisterPromotionRequest) GetTerms() *ChannelTerms { + if x != nil { + return x.Terms + } + return nil +} + +type RegisterPromotionResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Channel *ArkChannel `protobuf:"bytes,1,opt,name=channel,proto3" json:"channel,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RegisterPromotionResponse) Reset() { + *x = RegisterPromotionResponse{} + mi := &file_ark_channel_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RegisterPromotionResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RegisterPromotionResponse) ProtoMessage() {} + +func (x *RegisterPromotionResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[9] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RegisterPromotionResponse.ProtoReflect.Descriptor instead. +func (*RegisterPromotionResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{9} +} + +func (x *RegisterPromotionResponse) GetChannel() *ArkChannel { + if x != nil { + return x.Channel + } + return nil +} + +type GetFundingChannelRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + ChannelId []byte `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetFundingChannelRequest) Reset() { + *x = GetFundingChannelRequest{} + mi := &file_ark_channel_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetFundingChannelRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetFundingChannelRequest) ProtoMessage() {} + +func (x *GetFundingChannelRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[10] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetFundingChannelRequest.ProtoReflect.Descriptor instead. +func (*GetFundingChannelRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{10} +} + +func (x *GetFundingChannelRequest) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +type GetFundingChannelResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Terms *ChannelTerms `protobuf:"bytes,1,opt,name=terms,proto3" json:"terms,omitempty"` + Binding *ChannelVTXOBinding `protobuf:"bytes,2,opt,name=binding,proto3" json:"binding,omitempty"` + Backing *ChannelBacking `protobuf:"bytes,3,opt,name=backing,proto3" json:"backing,omitempty"` + Phase uint32 `protobuf:"varint,4,opt,name=phase,proto3" json:"phase,omitempty"` + OorFinalized bool `protobuf:"varint,5,opt,name=oor_finalized,json=oorFinalized,proto3" json:"oor_finalized,omitempty"` + ClientRecoveryReady bool `protobuf:"varint,6,opt,name=client_recovery_ready,json=clientRecoveryReady,proto3" json:"client_recovery_ready,omitempty"` + Failure string `protobuf:"bytes,7,opt,name=failure,proto3" json:"failure,omitempty"` + Revision uint64 `protobuf:"varint,8,opt,name=revision,proto3" json:"revision,omitempty"` + OorAborted bool `protobuf:"varint,9,opt,name=oor_aborted,json=oorAborted,proto3" json:"oor_aborted,omitempty"` + HubRecoveryReady bool `protobuf:"varint,10,opt,name=hub_recovery_ready,json=hubRecoveryReady,proto3" json:"hub_recovery_ready,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetFundingChannelResponse) Reset() { + *x = GetFundingChannelResponse{} + mi := &file_ark_channel_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetFundingChannelResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetFundingChannelResponse) ProtoMessage() {} + +func (x *GetFundingChannelResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[11] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetFundingChannelResponse.ProtoReflect.Descriptor instead. +func (*GetFundingChannelResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{11} +} + +func (x *GetFundingChannelResponse) GetTerms() *ChannelTerms { + if x != nil { + return x.Terms + } + return nil +} + +func (x *GetFundingChannelResponse) GetBinding() *ChannelVTXOBinding { + if x != nil { + return x.Binding + } + return nil +} + +func (x *GetFundingChannelResponse) GetBacking() *ChannelBacking { + if x != nil { + return x.Backing + } + return nil +} + +func (x *GetFundingChannelResponse) GetPhase() uint32 { + if x != nil { + return x.Phase + } + return 0 +} + +func (x *GetFundingChannelResponse) GetOorFinalized() bool { + if x != nil { + return x.OorFinalized + } + return false +} + +func (x *GetFundingChannelResponse) GetClientRecoveryReady() bool { + if x != nil { + return x.ClientRecoveryReady + } + return false +} + +func (x *GetFundingChannelResponse) GetFailure() string { + if x != nil { + return x.Failure + } + return "" +} + +func (x *GetFundingChannelResponse) GetRevision() uint64 { + if x != nil { + return x.Revision + } + return 0 +} + +func (x *GetFundingChannelResponse) GetOorAborted() bool { + if x != nil { + return x.OorAborted + } + return false +} + +func (x *GetFundingChannelResponse) GetHubRecoveryReady() bool { + if x != nil { + return x.HubRecoveryReady + } + return false +} + +type BindPreparedOORRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + ChannelId []byte `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + Binding *ChannelVTXOBinding `protobuf:"bytes,2,opt,name=binding,proto3" json:"binding,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *BindPreparedOORRequest) Reset() { + *x = BindPreparedOORRequest{} + mi := &file_ark_channel_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *BindPreparedOORRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*BindPreparedOORRequest) ProtoMessage() {} + +func (x *BindPreparedOORRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[12] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use BindPreparedOORRequest.ProtoReflect.Descriptor instead. +func (*BindPreparedOORRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{12} +} + +func (x *BindPreparedOORRequest) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +func (x *BindPreparedOORRequest) GetBinding() *ChannelVTXOBinding { + if x != nil { + return x.Binding + } + return nil +} + +type BindPreparedOORResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Channel *ArkChannel `protobuf:"bytes,1,opt,name=channel,proto3" json:"channel,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *BindPreparedOORResponse) Reset() { + *x = BindPreparedOORResponse{} + mi := &file_ark_channel_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *BindPreparedOORResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*BindPreparedOORResponse) ProtoMessage() {} + +func (x *BindPreparedOORResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[13] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use BindPreparedOORResponse.ProtoReflect.Descriptor instead. +func (*BindPreparedOORResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{13} +} + +func (x *BindPreparedOORResponse) GetChannel() *ArkChannel { + if x != nil { + return x.Channel + } + return nil +} + +type SignBackingRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + ChannelId []byte `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + Terms *ChannelTerms `protobuf:"bytes,2,opt,name=terms,proto3" json:"terms,omitempty"` + Binding *ChannelVTXOBinding `protobuf:"bytes,3,opt,name=binding,proto3" json:"binding,omitempty"` + FundingPsbt []byte `protobuf:"bytes,4,opt,name=funding_psbt,json=fundingPsbt,proto3" json:"funding_psbt,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SignBackingRequest) Reset() { + *x = SignBackingRequest{} + mi := &file_ark_channel_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SignBackingRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SignBackingRequest) ProtoMessage() {} + +func (x *SignBackingRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[14] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SignBackingRequest.ProtoReflect.Descriptor instead. +func (*SignBackingRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{14} +} + +func (x *SignBackingRequest) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +func (x *SignBackingRequest) GetTerms() *ChannelTerms { + if x != nil { + return x.Terms + } + return nil +} + +func (x *SignBackingRequest) GetBinding() *ChannelVTXOBinding { + if x != nil { + return x.Binding + } + return nil +} + +func (x *SignBackingRequest) GetFundingPsbt() []byte { + if x != nil { + return x.FundingPsbt + } + return nil +} + +type SignBackingResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Signature []byte `protobuf:"bytes,1,opt,name=signature,proto3" json:"signature,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SignBackingResponse) Reset() { + *x = SignBackingResponse{} + mi := &file_ark_channel_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SignBackingResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SignBackingResponse) ProtoMessage() {} + +func (x *SignBackingResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[15] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SignBackingResponse.ProtoReflect.Descriptor instead. +func (*SignBackingResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{15} +} + +func (x *SignBackingResponse) GetSignature() []byte { + if x != nil { + return x.Signature + } + return nil +} + +type InstallBackingRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + ChannelId []byte `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + Terms *ChannelTerms `protobuf:"bytes,2,opt,name=terms,proto3" json:"terms,omitempty"` + Binding *ChannelVTXOBinding `protobuf:"bytes,3,opt,name=binding,proto3" json:"binding,omitempty"` + Backing *ChannelBacking `protobuf:"bytes,4,opt,name=backing,proto3" json:"backing,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *InstallBackingRequest) Reset() { + *x = InstallBackingRequest{} + mi := &file_ark_channel_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *InstallBackingRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*InstallBackingRequest) ProtoMessage() {} + +func (x *InstallBackingRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[16] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use InstallBackingRequest.ProtoReflect.Descriptor instead. +func (*InstallBackingRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{16} +} + +func (x *InstallBackingRequest) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +func (x *InstallBackingRequest) GetTerms() *ChannelTerms { + if x != nil { + return x.Terms + } + return nil +} + +func (x *InstallBackingRequest) GetBinding() *ChannelVTXOBinding { + if x != nil { + return x.Binding + } + return nil +} + +func (x *InstallBackingRequest) GetBacking() *ChannelBacking { + if x != nil { + return x.Backing + } + return nil +} + +type InstallBackingResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *InstallBackingResponse) Reset() { + *x = InstallBackingResponse{} + mi := &file_ark_channel_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *InstallBackingResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*InstallBackingResponse) ProtoMessage() {} + +func (x *InstallBackingResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[17] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use InstallBackingResponse.ProtoReflect.Descriptor instead. +func (*InstallBackingResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{17} +} + +type InstallRecoveryPackageRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + ChannelId []byte `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + Terms *ChannelTerms `protobuf:"bytes,2,opt,name=terms,proto3" json:"terms,omitempty"` + Binding *ChannelVTXOBinding `protobuf:"bytes,3,opt,name=binding,proto3" json:"binding,omitempty"` + Recovery *ChannelRecoveryPackage `protobuf:"bytes,4,opt,name=recovery,proto3" json:"recovery,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *InstallRecoveryPackageRequest) Reset() { + *x = InstallRecoveryPackageRequest{} + mi := &file_ark_channel_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *InstallRecoveryPackageRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*InstallRecoveryPackageRequest) ProtoMessage() {} + +func (x *InstallRecoveryPackageRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[18] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use InstallRecoveryPackageRequest.ProtoReflect.Descriptor instead. +func (*InstallRecoveryPackageRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{18} +} + +func (x *InstallRecoveryPackageRequest) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +func (x *InstallRecoveryPackageRequest) GetTerms() *ChannelTerms { + if x != nil { + return x.Terms + } + return nil +} + +func (x *InstallRecoveryPackageRequest) GetBinding() *ChannelVTXOBinding { + if x != nil { + return x.Binding + } + return nil +} + +func (x *InstallRecoveryPackageRequest) GetRecovery() *ChannelRecoveryPackage { + if x != nil { + return x.Recovery + } + return nil +} + +type InstallRecoveryPackageResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *InstallRecoveryPackageResponse) Reset() { + *x = InstallRecoveryPackageResponse{} + mi := &file_ark_channel_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *InstallRecoveryPackageResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*InstallRecoveryPackageResponse) ProtoMessage() {} + +func (x *InstallRecoveryPackageResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[19] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use InstallRecoveryPackageResponse.ProtoReflect.Descriptor instead. +func (*InstallRecoveryPackageResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{19} +} + +type OORRecoverySource struct { + state protoimpl.MessageState `protogen:"open.v1"` + Txid []byte `protobuf:"bytes,1,opt,name=txid,proto3" json:"txid,omitempty"` + OutputIndex uint32 `protobuf:"varint,2,opt,name=output_index,json=outputIndex,proto3" json:"output_index,omitempty"` + AmountSat int64 `protobuf:"varint,3,opt,name=amount_sat,json=amountSat,proto3" json:"amount_sat,omitempty"` + PkScript []byte `protobuf:"bytes,4,opt,name=pk_script,json=pkScript,proto3" json:"pk_script,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *OORRecoverySource) Reset() { + *x = OORRecoverySource{} + mi := &file_ark_channel_proto_msgTypes[20] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *OORRecoverySource) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*OORRecoverySource) ProtoMessage() {} + +func (x *OORRecoverySource) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[20] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use OORRecoverySource.ProtoReflect.Descriptor instead. +func (*OORRecoverySource) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{20} +} + +func (x *OORRecoverySource) GetTxid() []byte { + if x != nil { + return x.Txid + } + return nil +} + +func (x *OORRecoverySource) GetOutputIndex() uint32 { + if x != nil { + return x.OutputIndex + } + return 0 +} + +func (x *OORRecoverySource) GetAmountSat() int64 { + if x != nil { + return x.AmountSat + } + return 0 +} + +func (x *OORRecoverySource) GetPkScript() []byte { + if x != nil { + return x.PkScript + } + return nil +} + +type ChannelRecoveryPackage struct { + state protoimpl.MessageState `protogen:"open.v1"` + SourceDescriptor *ChannelRecoveryDescriptor `protobuf:"bytes,1,opt,name=source_descriptor,json=sourceDescriptor,proto3" json:"source_descriptor,omitempty"` + OorPackages []*ChannelRecoveryOORPackage `protobuf:"bytes,2,rep,name=oor_packages,json=oorPackages,proto3" json:"oor_packages,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ChannelRecoveryPackage) Reset() { + *x = ChannelRecoveryPackage{} + mi := &file_ark_channel_proto_msgTypes[21] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ChannelRecoveryPackage) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ChannelRecoveryPackage) ProtoMessage() {} + +func (x *ChannelRecoveryPackage) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[21] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ChannelRecoveryPackage.ProtoReflect.Descriptor instead. +func (*ChannelRecoveryPackage) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{21} +} + +func (x *ChannelRecoveryPackage) GetSourceDescriptor() *ChannelRecoveryDescriptor { + if x != nil { + return x.SourceDescriptor + } + return nil +} + +func (x *ChannelRecoveryPackage) GetOorPackages() []*ChannelRecoveryOORPackage { + if x != nil { + return x.OorPackages + } + return nil +} + +type ChannelRecoveryDescriptor struct { + state protoimpl.MessageState `protogen:"open.v1"` + Ancestry []*ChannelRecoveryAncestry `protobuf:"bytes,1,rep,name=ancestry,proto3" json:"ancestry,omitempty"` + RoundId string `protobuf:"bytes,2,opt,name=round_id,json=roundId,proto3" json:"round_id,omitempty"` + CommitmentTxid []byte `protobuf:"bytes,3,opt,name=commitment_txid,json=commitmentTxid,proto3" json:"commitment_txid,omitempty"` + BatchExpiry int32 `protobuf:"varint,4,opt,name=batch_expiry,json=batchExpiry,proto3" json:"batch_expiry,omitempty"` + ChainDepth int32 `protobuf:"varint,5,opt,name=chain_depth,json=chainDepth,proto3" json:"chain_depth,omitempty"` + CreatedHeight int32 `protobuf:"varint,6,opt,name=created_height,json=createdHeight,proto3" json:"created_height,omitempty"` + ConstructionVersion int32 `protobuf:"varint,7,opt,name=construction_version,json=constructionVersion,proto3" json:"construction_version,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ChannelRecoveryDescriptor) Reset() { + *x = ChannelRecoveryDescriptor{} + mi := &file_ark_channel_proto_msgTypes[22] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ChannelRecoveryDescriptor) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ChannelRecoveryDescriptor) ProtoMessage() {} + +func (x *ChannelRecoveryDescriptor) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[22] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ChannelRecoveryDescriptor.ProtoReflect.Descriptor instead. +func (*ChannelRecoveryDescriptor) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{22} +} + +func (x *ChannelRecoveryDescriptor) GetAncestry() []*ChannelRecoveryAncestry { + if x != nil { + return x.Ancestry + } + return nil +} + +func (x *ChannelRecoveryDescriptor) GetRoundId() string { + if x != nil { + return x.RoundId + } + return "" +} + +func (x *ChannelRecoveryDescriptor) GetCommitmentTxid() []byte { + if x != nil { + return x.CommitmentTxid + } + return nil +} + +func (x *ChannelRecoveryDescriptor) GetBatchExpiry() int32 { + if x != nil { + return x.BatchExpiry + } + return 0 +} + +func (x *ChannelRecoveryDescriptor) GetChainDepth() int32 { + if x != nil { + return x.ChainDepth + } + return 0 +} + +func (x *ChannelRecoveryDescriptor) GetCreatedHeight() int32 { + if x != nil { + return x.CreatedHeight + } + return 0 +} + +func (x *ChannelRecoveryDescriptor) GetConstructionVersion() int32 { + if x != nil { + return x.ConstructionVersion + } + return 0 +} + +type ChannelRecoveryAncestry struct { + state protoimpl.MessageState `protogen:"open.v1"` + TreePath []byte `protobuf:"bytes,1,opt,name=tree_path,json=treePath,proto3" json:"tree_path,omitempty"` + CommitmentTxid []byte `protobuf:"bytes,2,opt,name=commitment_txid,json=commitmentTxid,proto3" json:"commitment_txid,omitempty"` + InputIndices []uint32 `protobuf:"varint,3,rep,packed,name=input_indices,json=inputIndices,proto3" json:"input_indices,omitempty"` + TreeDepth uint32 `protobuf:"varint,4,opt,name=tree_depth,json=treeDepth,proto3" json:"tree_depth,omitempty"` + CommitmentHeight int32 `protobuf:"varint,5,opt,name=commitment_height,json=commitmentHeight,proto3" json:"commitment_height,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ChannelRecoveryAncestry) Reset() { + *x = ChannelRecoveryAncestry{} + mi := &file_ark_channel_proto_msgTypes[23] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ChannelRecoveryAncestry) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ChannelRecoveryAncestry) ProtoMessage() {} + +func (x *ChannelRecoveryAncestry) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[23] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ChannelRecoveryAncestry.ProtoReflect.Descriptor instead. +func (*ChannelRecoveryAncestry) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{23} +} + +func (x *ChannelRecoveryAncestry) GetTreePath() []byte { + if x != nil { + return x.TreePath + } + return nil +} + +func (x *ChannelRecoveryAncestry) GetCommitmentTxid() []byte { + if x != nil { + return x.CommitmentTxid + } + return nil +} + +func (x *ChannelRecoveryAncestry) GetInputIndices() []uint32 { + if x != nil { + return x.InputIndices + } + return nil +} + +func (x *ChannelRecoveryAncestry) GetTreeDepth() uint32 { + if x != nil { + return x.TreeDepth + } + return 0 +} + +func (x *ChannelRecoveryAncestry) GetCommitmentHeight() int32 { + if x != nil { + return x.CommitmentHeight + } + return 0 +} + +type ChannelRecoveryOORPackage struct { + state protoimpl.MessageState `protogen:"open.v1"` + SessionId []byte `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"` + Direction int32 `protobuf:"varint,2,opt,name=direction,proto3" json:"direction,omitempty"` + ArkPsbt []byte `protobuf:"bytes,3,opt,name=ark_psbt,json=arkPsbt,proto3" json:"ark_psbt,omitempty"` + CheckpointPsbts [][]byte `protobuf:"bytes,4,rep,name=checkpoint_psbts,json=checkpointPsbts,proto3" json:"checkpoint_psbts,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ChannelRecoveryOORPackage) Reset() { + *x = ChannelRecoveryOORPackage{} + mi := &file_ark_channel_proto_msgTypes[24] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ChannelRecoveryOORPackage) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ChannelRecoveryOORPackage) ProtoMessage() {} + +func (x *ChannelRecoveryOORPackage) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[24] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ChannelRecoveryOORPackage.ProtoReflect.Descriptor instead. +func (*ChannelRecoveryOORPackage) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{24} +} + +func (x *ChannelRecoveryOORPackage) GetSessionId() []byte { + if x != nil { + return x.SessionId + } + return nil +} + +func (x *ChannelRecoveryOORPackage) GetDirection() int32 { + if x != nil { + return x.Direction + } + return 0 +} + +func (x *ChannelRecoveryOORPackage) GetArkPsbt() []byte { + if x != nil { + return x.ArkPsbt + } + return nil +} + +func (x *ChannelRecoveryOORPackage) GetCheckpointPsbts() [][]byte { + if x != nil { + return x.CheckpointPsbts + } + return nil +} + +type FundingStatusRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Terms *ChannelTerms `protobuf:"bytes,1,opt,name=terms,proto3" json:"terms,omitempty"` + Backing *ChannelBacking `protobuf:"bytes,2,opt,name=backing,proto3" json:"backing,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FundingStatusRequest) Reset() { + *x = FundingStatusRequest{} + mi := &file_ark_channel_proto_msgTypes[25] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FundingStatusRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FundingStatusRequest) ProtoMessage() {} + +func (x *FundingStatusRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[25] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FundingStatusRequest.ProtoReflect.Descriptor instead. +func (*FundingStatusRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{25} +} + +func (x *FundingStatusRequest) GetTerms() *ChannelTerms { + if x != nil { + return x.Terms + } + return nil +} + +func (x *FundingStatusRequest) GetBacking() *ChannelBacking { + if x != nil { + return x.Backing + } + return nil +} + +type FundingStatusResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Ready bool `protobuf:"varint,1,opt,name=ready,proto3" json:"ready,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FundingStatusResponse) Reset() { + *x = FundingStatusResponse{} + mi := &file_ark_channel_proto_msgTypes[26] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FundingStatusResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FundingStatusResponse) ProtoMessage() {} + +func (x *FundingStatusResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[26] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FundingStatusResponse.ProtoReflect.Descriptor instead. +func (*FundingStatusResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{26} +} + +func (x *FundingStatusResponse) GetReady() bool { + if x != nil { + return x.Ready + } + return false +} + +type ApplyChannelEventRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + ChannelId []byte `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + EventType ChannelEventType `protobuf:"varint,2,opt,name=event_type,json=eventType,proto3,enum=arkchannelrpc.ChannelEventType" json:"event_type,omitempty"` + Party uint32 `protobuf:"varint,3,opt,name=party,proto3" json:"party,omitempty"` + OorSessionId []byte `protobuf:"bytes,4,opt,name=oor_session_id,json=oorSessionId,proto3" json:"oor_session_id,omitempty"` + ChannelPointTxid []byte `protobuf:"bytes,5,opt,name=channel_point_txid,json=channelPointTxid,proto3" json:"channel_point_txid,omitempty"` + ChannelPointIndex uint32 `protobuf:"varint,6,opt,name=channel_point_index,json=channelPointIndex,proto3" json:"channel_point_index,omitempty"` + FailureReason string `protobuf:"bytes,7,opt,name=failure_reason,json=failureReason,proto3" json:"failure_reason,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ApplyChannelEventRequest) Reset() { + *x = ApplyChannelEventRequest{} + mi := &file_ark_channel_proto_msgTypes[27] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ApplyChannelEventRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ApplyChannelEventRequest) ProtoMessage() {} + +func (x *ApplyChannelEventRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[27] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ApplyChannelEventRequest.ProtoReflect.Descriptor instead. +func (*ApplyChannelEventRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{27} +} + +func (x *ApplyChannelEventRequest) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +func (x *ApplyChannelEventRequest) GetEventType() ChannelEventType { + if x != nil { + return x.EventType + } + return ChannelEventType_CHANNEL_EVENT_TYPE_UNSPECIFIED +} + +func (x *ApplyChannelEventRequest) GetParty() uint32 { + if x != nil { + return x.Party + } + return 0 +} + +func (x *ApplyChannelEventRequest) GetOorSessionId() []byte { + if x != nil { + return x.OorSessionId + } + return nil +} + +func (x *ApplyChannelEventRequest) GetChannelPointTxid() []byte { + if x != nil { + return x.ChannelPointTxid + } + return nil +} + +func (x *ApplyChannelEventRequest) GetChannelPointIndex() uint32 { + if x != nil { + return x.ChannelPointIndex + } + return 0 +} + +func (x *ApplyChannelEventRequest) GetFailureReason() string { + if x != nil { + return x.FailureReason + } + return "" +} + +type ApplyChannelEventResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Channel *ArkChannel `protobuf:"bytes,1,opt,name=channel,proto3" json:"channel,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ApplyChannelEventResponse) Reset() { + *x = ApplyChannelEventResponse{} + mi := &file_ark_channel_proto_msgTypes[28] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ApplyChannelEventResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ApplyChannelEventResponse) ProtoMessage() {} + +func (x *ApplyChannelEventResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[28] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ApplyChannelEventResponse.ProtoReflect.Descriptor instead. +func (*ApplyChannelEventResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{28} +} + +func (x *ApplyChannelEventResponse) GetChannel() *ArkChannel { + if x != nil { + return x.Channel + } + return nil +} + +type PrepareOutgoingPaymentRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + PaymentRequest string `protobuf:"bytes,1,opt,name=payment_request,json=paymentRequest,proto3" json:"payment_request,omitempty"` + MaxFeeSat uint64 `protobuf:"varint,2,opt,name=max_fee_sat,json=maxFeeSat,proto3" json:"max_fee_sat,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PrepareOutgoingPaymentRequest) Reset() { + *x = PrepareOutgoingPaymentRequest{} + mi := &file_ark_channel_proto_msgTypes[29] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PrepareOutgoingPaymentRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PrepareOutgoingPaymentRequest) ProtoMessage() {} + +func (x *PrepareOutgoingPaymentRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[29] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PrepareOutgoingPaymentRequest.ProtoReflect.Descriptor instead. +func (*PrepareOutgoingPaymentRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{29} +} + +func (x *PrepareOutgoingPaymentRequest) GetPaymentRequest() string { + if x != nil { + return x.PaymentRequest + } + return "" +} + +func (x *PrepareOutgoingPaymentRequest) GetMaxFeeSat() uint64 { + if x != nil { + return x.MaxFeeSat + } + return 0 +} + +type PrepareOutgoingPaymentResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + PaymentHash []byte `protobuf:"bytes,1,opt,name=payment_hash,json=paymentHash,proto3" json:"payment_hash,omitempty"` + PrivateAmountSat int64 `protobuf:"varint,2,opt,name=private_amount_sat,json=privateAmountSat,proto3" json:"private_amount_sat,omitempty"` + FeeSat int64 `protobuf:"varint,3,opt,name=fee_sat,json=feeSat,proto3" json:"fee_sat,omitempty"` + ChannelId []byte `protobuf:"bytes,4,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + ReservedScid uint64 `protobuf:"varint,5,opt,name=reserved_scid,json=reservedScid,proto3" json:"reserved_scid,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PrepareOutgoingPaymentResponse) Reset() { + *x = PrepareOutgoingPaymentResponse{} + mi := &file_ark_channel_proto_msgTypes[30] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PrepareOutgoingPaymentResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PrepareOutgoingPaymentResponse) ProtoMessage() {} + +func (x *PrepareOutgoingPaymentResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[30] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PrepareOutgoingPaymentResponse.ProtoReflect.Descriptor instead. +func (*PrepareOutgoingPaymentResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{30} +} + +func (x *PrepareOutgoingPaymentResponse) GetPaymentHash() []byte { + if x != nil { + return x.PaymentHash + } + return nil +} + +func (x *PrepareOutgoingPaymentResponse) GetPrivateAmountSat() int64 { + if x != nil { + return x.PrivateAmountSat + } + return 0 +} + +func (x *PrepareOutgoingPaymentResponse) GetFeeSat() int64 { + if x != nil { + return x.FeeSat + } + return 0 +} + +func (x *PrepareOutgoingPaymentResponse) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +func (x *PrepareOutgoingPaymentResponse) GetReservedScid() uint64 { + if x != nil { + return x.ReservedScid + } + return 0 +} + +type CancelOutgoingPaymentRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + PaymentHash []byte `protobuf:"bytes,1,opt,name=payment_hash,json=paymentHash,proto3" json:"payment_hash,omitempty"` + Reason string `protobuf:"bytes,2,opt,name=reason,proto3" json:"reason,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CancelOutgoingPaymentRequest) Reset() { + *x = CancelOutgoingPaymentRequest{} + mi := &file_ark_channel_proto_msgTypes[31] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CancelOutgoingPaymentRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CancelOutgoingPaymentRequest) ProtoMessage() {} + +func (x *CancelOutgoingPaymentRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[31] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CancelOutgoingPaymentRequest.ProtoReflect.Descriptor instead. +func (*CancelOutgoingPaymentRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{31} +} + +func (x *CancelOutgoingPaymentRequest) GetPaymentHash() []byte { + if x != nil { + return x.PaymentHash + } + return nil +} + +func (x *CancelOutgoingPaymentRequest) GetReason() string { + if x != nil { + return x.Reason + } + return "" +} + +type CancelOutgoingPaymentResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Cancelled bool `protobuf:"varint,1,opt,name=cancelled,proto3" json:"cancelled,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CancelOutgoingPaymentResponse) Reset() { + *x = CancelOutgoingPaymentResponse{} + mi := &file_ark_channel_proto_msgTypes[32] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CancelOutgoingPaymentResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CancelOutgoingPaymentResponse) ProtoMessage() {} + +func (x *CancelOutgoingPaymentResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[32] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CancelOutgoingPaymentResponse.ProtoReflect.Descriptor instead. +func (*CancelOutgoingPaymentResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{32} +} + +func (x *CancelOutgoingPaymentResponse) GetCancelled() bool { + if x != nil { + return x.Cancelled + } + return false +} + +type RegisterIncomingPaymentRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + PaymentHash []byte `protobuf:"bytes,1,opt,name=payment_hash,json=paymentHash,proto3" json:"payment_hash,omitempty"` + AmountSat int64 `protobuf:"varint,2,opt,name=amount_sat,json=amountSat,proto3" json:"amount_sat,omitempty"` + ReservedScid uint64 `protobuf:"varint,3,opt,name=reserved_scid,json=reservedScid,proto3" json:"reserved_scid,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RegisterIncomingPaymentRequest) Reset() { + *x = RegisterIncomingPaymentRequest{} + mi := &file_ark_channel_proto_msgTypes[33] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RegisterIncomingPaymentRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RegisterIncomingPaymentRequest) ProtoMessage() {} + +func (x *RegisterIncomingPaymentRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[33] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RegisterIncomingPaymentRequest.ProtoReflect.Descriptor instead. +func (*RegisterIncomingPaymentRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{33} +} + +func (x *RegisterIncomingPaymentRequest) GetPaymentHash() []byte { + if x != nil { + return x.PaymentHash + } + return nil +} + +func (x *RegisterIncomingPaymentRequest) GetAmountSat() int64 { + if x != nil { + return x.AmountSat + } + return 0 +} + +func (x *RegisterIncomingPaymentRequest) GetReservedScid() uint64 { + if x != nil { + return x.ReservedScid + } + return 0 +} + +type RegisterIncomingPaymentResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Registered bool `protobuf:"varint,1,opt,name=registered,proto3" json:"registered,omitempty"` + ChannelId []byte `protobuf:"bytes,3,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RegisterIncomingPaymentResponse) Reset() { + *x = RegisterIncomingPaymentResponse{} + mi := &file_ark_channel_proto_msgTypes[34] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RegisterIncomingPaymentResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RegisterIncomingPaymentResponse) ProtoMessage() {} + +func (x *RegisterIncomingPaymentResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[34] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RegisterIncomingPaymentResponse.ProtoReflect.Descriptor instead. +func (*RegisterIncomingPaymentResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{34} +} + +func (x *RegisterIncomingPaymentResponse) GetRegistered() bool { + if x != nil { + return x.Registered + } + return false +} + +func (x *RegisterIncomingPaymentResponse) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +type CancelIncomingPaymentRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + PaymentHash []byte `protobuf:"bytes,1,opt,name=payment_hash,json=paymentHash,proto3" json:"payment_hash,omitempty"` + Reason string `protobuf:"bytes,2,opt,name=reason,proto3" json:"reason,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CancelIncomingPaymentRequest) Reset() { + *x = CancelIncomingPaymentRequest{} + mi := &file_ark_channel_proto_msgTypes[35] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CancelIncomingPaymentRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CancelIncomingPaymentRequest) ProtoMessage() {} + +func (x *CancelIncomingPaymentRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[35] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CancelIncomingPaymentRequest.ProtoReflect.Descriptor instead. +func (*CancelIncomingPaymentRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{35} +} + +func (x *CancelIncomingPaymentRequest) GetPaymentHash() []byte { + if x != nil { + return x.PaymentHash + } + return nil +} + +func (x *CancelIncomingPaymentRequest) GetReason() string { + if x != nil { + return x.Reason + } + return "" +} + +type CancelIncomingPaymentResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Cancelled bool `protobuf:"varint,1,opt,name=cancelled,proto3" json:"cancelled,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CancelIncomingPaymentResponse) Reset() { + *x = CancelIncomingPaymentResponse{} + mi := &file_ark_channel_proto_msgTypes[36] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CancelIncomingPaymentResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CancelIncomingPaymentResponse) ProtoMessage() {} + +func (x *CancelIncomingPaymentResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[36] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CancelIncomingPaymentResponse.ProtoReflect.Descriptor instead. +func (*CancelIncomingPaymentResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{36} +} + +func (x *CancelIncomingPaymentResponse) GetCancelled() bool { + if x != nil { + return x.Cancelled + } + return false +} + +type ChannelTerms struct { + state protoimpl.MessageState `protogen:"open.v1"` + ChannelId []byte `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + Kind uint32 `protobuf:"varint,2,opt,name=kind,proto3" json:"kind,omitempty"` + Funder uint32 `protobuf:"varint,3,opt,name=funder,proto3" json:"funder,omitempty"` + PendingChannelId []byte `protobuf:"bytes,4,opt,name=pending_channel_id,json=pendingChannelId,proto3" json:"pending_channel_id,omitempty"` + ReservedScid uint64 `protobuf:"varint,5,opt,name=reserved_scid,json=reservedScid,proto3" json:"reserved_scid,omitempty"` + CapacitySat int64 `protobuf:"varint,6,opt,name=capacity_sat,json=capacitySat,proto3" json:"capacity_sat,omitempty"` + ClientNodeKey []byte `protobuf:"bytes,7,opt,name=client_node_key,json=clientNodeKey,proto3" json:"client_node_key,omitempty"` + HubNodeKey []byte `protobuf:"bytes,8,opt,name=hub_node_key,json=hubNodeKey,proto3" json:"hub_node_key,omitempty"` + Vtxo *ChannelVTXOTerms `protobuf:"bytes,10,opt,name=vtxo,proto3" json:"vtxo,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ChannelTerms) Reset() { + *x = ChannelTerms{} + mi := &file_ark_channel_proto_msgTypes[37] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ChannelTerms) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ChannelTerms) ProtoMessage() {} + +func (x *ChannelTerms) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[37] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ChannelTerms.ProtoReflect.Descriptor instead. +func (*ChannelTerms) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{37} +} + +func (x *ChannelTerms) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +func (x *ChannelTerms) GetKind() uint32 { + if x != nil { + return x.Kind + } + return 0 +} + +func (x *ChannelTerms) GetFunder() uint32 { + if x != nil { + return x.Funder + } + return 0 +} + +func (x *ChannelTerms) GetPendingChannelId() []byte { + if x != nil { + return x.PendingChannelId + } + return nil +} + +func (x *ChannelTerms) GetReservedScid() uint64 { + if x != nil { + return x.ReservedScid + } + return 0 +} + +func (x *ChannelTerms) GetCapacitySat() int64 { + if x != nil { + return x.CapacitySat + } + return 0 +} + +func (x *ChannelTerms) GetClientNodeKey() []byte { + if x != nil { + return x.ClientNodeKey + } + return nil +} + +func (x *ChannelTerms) GetHubNodeKey() []byte { + if x != nil { + return x.HubNodeKey + } + return nil +} + +func (x *ChannelTerms) GetVtxo() *ChannelVTXOTerms { + if x != nil { + return x.Vtxo + } + return nil +} + +type ChannelVTXOTerms struct { + state protoimpl.MessageState `protogen:"open.v1"` + ClientArkKey []byte `protobuf:"bytes,1,opt,name=client_ark_key,json=clientArkKey,proto3" json:"client_ark_key,omitempty"` + HubArkKey []byte `protobuf:"bytes,2,opt,name=hub_ark_key,json=hubArkKey,proto3" json:"hub_ark_key,omitempty"` + ArkOperatorKey []byte `protobuf:"bytes,3,opt,name=ark_operator_key,json=arkOperatorKey,proto3" json:"ark_operator_key,omitempty"` + ClientChannelKey []byte `protobuf:"bytes,4,opt,name=client_channel_key,json=clientChannelKey,proto3" json:"client_channel_key,omitempty"` + HubChannelKey []byte `protobuf:"bytes,5,opt,name=hub_channel_key,json=hubChannelKey,proto3" json:"hub_channel_key,omitempty"` + FunderKey []byte `protobuf:"bytes,6,opt,name=funder_key,json=funderKey,proto3" json:"funder_key,omitempty"` + ChannelDelay uint32 `protobuf:"varint,7,opt,name=channel_delay,json=channelDelay,proto3" json:"channel_delay,omitempty"` + FunderDelay uint32 `protobuf:"varint,8,opt,name=funder_delay,json=funderDelay,proto3" json:"funder_delay,omitempty"` + MinExitDelay uint32 `protobuf:"varint,9,opt,name=min_exit_delay,json=minExitDelay,proto3" json:"min_exit_delay,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ChannelVTXOTerms) Reset() { + *x = ChannelVTXOTerms{} + mi := &file_ark_channel_proto_msgTypes[38] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ChannelVTXOTerms) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ChannelVTXOTerms) ProtoMessage() {} + +func (x *ChannelVTXOTerms) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[38] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ChannelVTXOTerms.ProtoReflect.Descriptor instead. +func (*ChannelVTXOTerms) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{38} +} + +func (x *ChannelVTXOTerms) GetClientArkKey() []byte { + if x != nil { + return x.ClientArkKey + } + return nil +} + +func (x *ChannelVTXOTerms) GetHubArkKey() []byte { + if x != nil { + return x.HubArkKey + } + return nil +} + +func (x *ChannelVTXOTerms) GetArkOperatorKey() []byte { + if x != nil { + return x.ArkOperatorKey + } + return nil +} + +func (x *ChannelVTXOTerms) GetClientChannelKey() []byte { + if x != nil { + return x.ClientChannelKey + } + return nil +} + +func (x *ChannelVTXOTerms) GetHubChannelKey() []byte { + if x != nil { + return x.HubChannelKey + } + return nil +} + +func (x *ChannelVTXOTerms) GetFunderKey() []byte { + if x != nil { + return x.FunderKey + } + return nil +} + +func (x *ChannelVTXOTerms) GetChannelDelay() uint32 { + if x != nil { + return x.ChannelDelay + } + return 0 +} + +func (x *ChannelVTXOTerms) GetFunderDelay() uint32 { + if x != nil { + return x.FunderDelay + } + return 0 +} + +func (x *ChannelVTXOTerms) GetMinExitDelay() uint32 { + if x != nil { + return x.MinExitDelay + } + return 0 +} + +type ChannelVTXOBinding struct { + state protoimpl.MessageState `protogen:"open.v1"` + OorSessionId []byte `protobuf:"bytes,1,opt,name=oor_session_id,json=oorSessionId,proto3" json:"oor_session_id,omitempty"` + OutpointTxid []byte `protobuf:"bytes,2,opt,name=outpoint_txid,json=outpointTxid,proto3" json:"outpoint_txid,omitempty"` + OutpointIndex uint32 `protobuf:"varint,3,opt,name=outpoint_index,json=outpointIndex,proto3" json:"outpoint_index,omitempty"` + AmountSat int64 `protobuf:"varint,4,opt,name=amount_sat,json=amountSat,proto3" json:"amount_sat,omitempty"` + ArkTransaction []byte `protobuf:"bytes,5,opt,name=ark_transaction,json=arkTransaction,proto3" json:"ark_transaction,omitempty"` + PolicyTemplate []byte `protobuf:"bytes,6,opt,name=policy_template,json=policyTemplate,proto3" json:"policy_template,omitempty"` + PkScript []byte `protobuf:"bytes,7,opt,name=pk_script,json=pkScript,proto3" json:"pk_script,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ChannelVTXOBinding) Reset() { + *x = ChannelVTXOBinding{} + mi := &file_ark_channel_proto_msgTypes[39] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ChannelVTXOBinding) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ChannelVTXOBinding) ProtoMessage() {} + +func (x *ChannelVTXOBinding) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[39] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ChannelVTXOBinding.ProtoReflect.Descriptor instead. +func (*ChannelVTXOBinding) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{39} +} + +func (x *ChannelVTXOBinding) GetOorSessionId() []byte { + if x != nil { + return x.OorSessionId + } + return nil +} + +func (x *ChannelVTXOBinding) GetOutpointTxid() []byte { + if x != nil { + return x.OutpointTxid + } + return nil +} + +func (x *ChannelVTXOBinding) GetOutpointIndex() uint32 { + if x != nil { + return x.OutpointIndex + } + return 0 +} + +func (x *ChannelVTXOBinding) GetAmountSat() int64 { + if x != nil { + return x.AmountSat + } + return 0 +} + +func (x *ChannelVTXOBinding) GetArkTransaction() []byte { + if x != nil { + return x.ArkTransaction + } + return nil +} + +func (x *ChannelVTXOBinding) GetPolicyTemplate() []byte { + if x != nil { + return x.PolicyTemplate + } + return nil +} + +func (x *ChannelVTXOBinding) GetPkScript() []byte { + if x != nil { + return x.PkScript + } + return nil +} + +type ChannelBacking struct { + state protoimpl.MessageState `protogen:"open.v1"` + Transaction []byte `protobuf:"bytes,1,opt,name=transaction,proto3" json:"transaction,omitempty"` + ChannelPointTxid []byte `protobuf:"bytes,2,opt,name=channel_point_txid,json=channelPointTxid,proto3" json:"channel_point_txid,omitempty"` + ChannelPointIndex uint32 `protobuf:"varint,3,opt,name=channel_point_index,json=channelPointIndex,proto3" json:"channel_point_index,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ChannelBacking) Reset() { + *x = ChannelBacking{} + mi := &file_ark_channel_proto_msgTypes[40] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ChannelBacking) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ChannelBacking) ProtoMessage() {} + +func (x *ChannelBacking) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[40] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ChannelBacking.ProtoReflect.Descriptor instead. +func (*ChannelBacking) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{40} +} + +func (x *ChannelBacking) GetTransaction() []byte { + if x != nil { + return x.Transaction + } + return nil +} + +func (x *ChannelBacking) GetChannelPointTxid() []byte { + if x != nil { + return x.ChannelPointTxid + } + return nil +} + +func (x *ChannelBacking) GetChannelPointIndex() uint32 { + if x != nil { + return x.ChannelPointIndex + } + return 0 +} + +type RefreshChannelRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // channel_id is the 32-byte durable Ark channel identifier. + ChannelId []byte `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RefreshChannelRequest) Reset() { + *x = RefreshChannelRequest{} + mi := &file_ark_channel_proto_msgTypes[41] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RefreshChannelRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RefreshChannelRequest) ProtoMessage() {} + +func (x *RefreshChannelRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[41] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RefreshChannelRequest.ProtoReflect.Descriptor instead. +func (*RefreshChannelRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{41} +} + +func (x *RefreshChannelRequest) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +type RefreshChannelResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Channel *ArkChannel `protobuf:"bytes,1,opt,name=channel,proto3" json:"channel,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RefreshChannelResponse) Reset() { + *x = RefreshChannelResponse{} + mi := &file_ark_channel_proto_msgTypes[42] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RefreshChannelResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RefreshChannelResponse) ProtoMessage() {} + +func (x *RefreshChannelResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[42] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RefreshChannelResponse.ProtoReflect.Descriptor instead. +func (*RefreshChannelResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{42} +} + +func (x *RefreshChannelResponse) GetChannel() *ArkChannel { + if x != nil { + return x.Channel + } + return nil +} + +type GetChannelRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + ChannelId []byte `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetChannelRequest) Reset() { + *x = GetChannelRequest{} + mi := &file_ark_channel_proto_msgTypes[43] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetChannelRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetChannelRequest) ProtoMessage() {} + +func (x *GetChannelRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[43] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetChannelRequest.ProtoReflect.Descriptor instead. +func (*GetChannelRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{43} +} + +func (x *GetChannelRequest) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +type GetChannelResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Channel *ArkChannel `protobuf:"bytes,1,opt,name=channel,proto3" json:"channel,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetChannelResponse) Reset() { + *x = GetChannelResponse{} + mi := &file_ark_channel_proto_msgTypes[44] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetChannelResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetChannelResponse) ProtoMessage() {} + +func (x *GetChannelResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[44] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetChannelResponse.ProtoReflect.Descriptor instead. +func (*GetChannelResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{44} +} + +func (x *GetChannelResponse) GetChannel() *ArkChannel { + if x != nil { + return x.Channel + } + return nil +} + +type ListChannelsRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListChannelsRequest) Reset() { + *x = ListChannelsRequest{} + mi := &file_ark_channel_proto_msgTypes[45] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListChannelsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListChannelsRequest) ProtoMessage() {} + +func (x *ListChannelsRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[45] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListChannelsRequest.ProtoReflect.Descriptor instead. +func (*ListChannelsRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{45} +} + +type ListChannelsResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Channels []*ArkChannel `protobuf:"bytes,1,rep,name=channels,proto3" json:"channels,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListChannelsResponse) Reset() { + *x = ListChannelsResponse{} + mi := &file_ark_channel_proto_msgTypes[46] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListChannelsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListChannelsResponse) ProtoMessage() {} + +func (x *ListChannelsResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[46] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListChannelsResponse.ProtoReflect.Descriptor instead. +func (*ListChannelsResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{46} +} + +func (x *ListChannelsResponse) GetChannels() []*ArkChannel { + if x != nil { + return x.Channels + } + return nil +} + +type ArkChannel struct { + state protoimpl.MessageState `protogen:"open.v1"` + ChannelId []byte `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + Kind string `protobuf:"bytes,2,opt,name=kind,proto3" json:"kind,omitempty"` + Phase string `protobuf:"bytes,3,opt,name=phase,proto3" json:"phase,omitempty"` + Funder string `protobuf:"bytes,4,opt,name=funder,proto3" json:"funder,omitempty"` + CapacitySat int64 `protobuf:"varint,5,opt,name=capacity_sat,json=capacitySat,proto3" json:"capacity_sat,omitempty"` + SourceOutpoint string `protobuf:"bytes,6,opt,name=source_outpoint,json=sourceOutpoint,proto3" json:"source_outpoint,omitempty"` + ChannelPoint string `protobuf:"bytes,7,opt,name=channel_point,json=channelPoint,proto3" json:"channel_point,omitempty"` + RefreshOorTxid []byte `protobuf:"bytes,8,opt,name=refresh_oor_txid,json=refreshOorTxid,proto3" json:"refresh_oor_txid,omitempty"` + Revision uint64 `protobuf:"varint,9,opt,name=revision,proto3" json:"revision,omitempty"` + ReservedScid uint64 `protobuf:"varint,10,opt,name=reserved_scid,json=reservedScid,proto3" json:"reserved_scid,omitempty"` + LocalBalanceSat int64 `protobuf:"varint,11,opt,name=local_balance_sat,json=localBalanceSat,proto3" json:"local_balance_sat,omitempty"` + RemoteBalanceSat int64 `protobuf:"varint,12,opt,name=remote_balance_sat,json=remoteBalanceSat,proto3" json:"remote_balance_sat,omitempty"` + BalanceAvailable bool `protobuf:"varint,13,opt,name=balance_available,json=balanceAvailable,proto3" json:"balance_available,omitempty"` + BalanceError string `protobuf:"bytes,14,opt,name=balance_error,json=balanceError,proto3" json:"balance_error,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ArkChannel) Reset() { + *x = ArkChannel{} + mi := &file_ark_channel_proto_msgTypes[47] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ArkChannel) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ArkChannel) ProtoMessage() {} + +func (x *ArkChannel) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[47] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ArkChannel.ProtoReflect.Descriptor instead. +func (*ArkChannel) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{47} +} + +func (x *ArkChannel) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +func (x *ArkChannel) GetKind() string { + if x != nil { + return x.Kind + } + return "" +} + +func (x *ArkChannel) GetPhase() string { + if x != nil { + return x.Phase + } + return "" +} + +func (x *ArkChannel) GetFunder() string { + if x != nil { + return x.Funder + } + return "" +} + +func (x *ArkChannel) GetCapacitySat() int64 { + if x != nil { + return x.CapacitySat + } + return 0 +} + +func (x *ArkChannel) GetSourceOutpoint() string { + if x != nil { + return x.SourceOutpoint + } + return "" +} + +func (x *ArkChannel) GetChannelPoint() string { + if x != nil { + return x.ChannelPoint + } + return "" +} + +func (x *ArkChannel) GetRefreshOorTxid() []byte { + if x != nil { + return x.RefreshOorTxid + } + return nil +} + +func (x *ArkChannel) GetRevision() uint64 { + if x != nil { + return x.Revision + } + return 0 +} + +func (x *ArkChannel) GetReservedScid() uint64 { + if x != nil { + return x.ReservedScid + } + return 0 +} + +func (x *ArkChannel) GetLocalBalanceSat() int64 { + if x != nil { + return x.LocalBalanceSat + } + return 0 +} + +func (x *ArkChannel) GetRemoteBalanceSat() int64 { + if x != nil { + return x.RemoteBalanceSat + } + return 0 +} + +func (x *ArkChannel) GetBalanceAvailable() bool { + if x != nil { + return x.BalanceAvailable + } + return false +} + +func (x *ArkChannel) GetBalanceError() string { + if x != nil { + return x.BalanceError + } + return "" +} + +type GetCooperativeCloseTermsRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + ChannelId []byte `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + ClientDeliveryScript []byte `protobuf:"bytes,2,opt,name=client_delivery_script,json=clientDeliveryScript,proto3" json:"client_delivery_script,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetCooperativeCloseTermsRequest) Reset() { + *x = GetCooperativeCloseTermsRequest{} + mi := &file_ark_channel_proto_msgTypes[48] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetCooperativeCloseTermsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetCooperativeCloseTermsRequest) ProtoMessage() {} + +func (x *GetCooperativeCloseTermsRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[48] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetCooperativeCloseTermsRequest.ProtoReflect.Descriptor instead. +func (*GetCooperativeCloseTermsRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{48} +} + +func (x *GetCooperativeCloseTermsRequest) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +func (x *GetCooperativeCloseTermsRequest) GetClientDeliveryScript() []byte { + if x != nil { + return x.ClientDeliveryScript + } + return nil +} + +type GetCooperativeCloseTermsResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Request *CooperativeCloseRequest `protobuf:"bytes,1,opt,name=request,proto3" json:"request,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetCooperativeCloseTermsResponse) Reset() { + *x = GetCooperativeCloseTermsResponse{} + mi := &file_ark_channel_proto_msgTypes[49] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetCooperativeCloseTermsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetCooperativeCloseTermsResponse) ProtoMessage() {} + +func (x *GetCooperativeCloseTermsResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[49] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetCooperativeCloseTermsResponse.ProtoReflect.Descriptor instead. +func (*GetCooperativeCloseTermsResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{49} +} + +func (x *GetCooperativeCloseTermsResponse) GetRequest() *CooperativeCloseRequest { + if x != nil { + return x.Request + } + return nil +} + +type CompleteCooperativeCloseRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + ChannelId []byte `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + Proposal *CooperativeCloseProposal `protobuf:"bytes,2,opt,name=proposal,proto3" json:"proposal,omitempty"` + Request *CooperativeCloseRequest `protobuf:"bytes,4,opt,name=request,proto3" json:"request,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CompleteCooperativeCloseRequest) Reset() { + *x = CompleteCooperativeCloseRequest{} + mi := &file_ark_channel_proto_msgTypes[50] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CompleteCooperativeCloseRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CompleteCooperativeCloseRequest) ProtoMessage() {} + +func (x *CompleteCooperativeCloseRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[50] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CompleteCooperativeCloseRequest.ProtoReflect.Descriptor instead. +func (*CompleteCooperativeCloseRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{50} +} + +func (x *CompleteCooperativeCloseRequest) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +func (x *CompleteCooperativeCloseRequest) GetProposal() *CooperativeCloseProposal { + if x != nil { + return x.Proposal + } + return nil +} + +func (x *CompleteCooperativeCloseRequest) GetRequest() *CooperativeCloseRequest { + if x != nil { + return x.Request + } + return nil +} + +type CompleteCooperativeCloseResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Settlement *CooperativeClose `protobuf:"bytes,1,opt,name=settlement,proto3" json:"settlement,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CompleteCooperativeCloseResponse) Reset() { + *x = CompleteCooperativeCloseResponse{} + mi := &file_ark_channel_proto_msgTypes[51] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CompleteCooperativeCloseResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CompleteCooperativeCloseResponse) ProtoMessage() {} + +func (x *CompleteCooperativeCloseResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[51] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CompleteCooperativeCloseResponse.ProtoReflect.Descriptor instead. +func (*CompleteCooperativeCloseResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{51} +} + +func (x *CompleteCooperativeCloseResponse) GetSettlement() *CooperativeClose { + if x != nil { + return x.Settlement + } + return nil +} + +type ConfirmCooperativeCloseRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + ChannelId []byte `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + AuthorizationReceipt []byte `protobuf:"bytes,2,opt,name=authorization_receipt,json=authorizationReceipt,proto3" json:"authorization_receipt,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ConfirmCooperativeCloseRequest) Reset() { + *x = ConfirmCooperativeCloseRequest{} + mi := &file_ark_channel_proto_msgTypes[52] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ConfirmCooperativeCloseRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ConfirmCooperativeCloseRequest) ProtoMessage() {} + +func (x *ConfirmCooperativeCloseRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[52] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ConfirmCooperativeCloseRequest.ProtoReflect.Descriptor instead. +func (*ConfirmCooperativeCloseRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{52} +} + +func (x *ConfirmCooperativeCloseRequest) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +func (x *ConfirmCooperativeCloseRequest) GetAuthorizationReceipt() []byte { + if x != nil { + return x.AuthorizationReceipt + } + return nil +} + +type ConfirmCooperativeCloseResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ConfirmCooperativeCloseResponse) Reset() { + *x = ConfirmCooperativeCloseResponse{} + mi := &file_ark_channel_proto_msgTypes[53] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ConfirmCooperativeCloseResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ConfirmCooperativeCloseResponse) ProtoMessage() {} + +func (x *ConfirmCooperativeCloseResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[53] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ConfirmCooperativeCloseResponse.ProtoReflect.Descriptor instead. +func (*ConfirmCooperativeCloseResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{53} +} + +type PublishCooperativeCloseRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + ChannelId []byte `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + SettlementTxid []byte `protobuf:"bytes,2,opt,name=settlement_txid,json=settlementTxid,proto3" json:"settlement_txid,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PublishCooperativeCloseRequest) Reset() { + *x = PublishCooperativeCloseRequest{} + mi := &file_ark_channel_proto_msgTypes[54] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PublishCooperativeCloseRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PublishCooperativeCloseRequest) ProtoMessage() {} + +func (x *PublishCooperativeCloseRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[54] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PublishCooperativeCloseRequest.ProtoReflect.Descriptor instead. +func (*PublishCooperativeCloseRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{54} +} + +func (x *PublishCooperativeCloseRequest) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +func (x *PublishCooperativeCloseRequest) GetSettlementTxid() []byte { + if x != nil { + return x.SettlementTxid + } + return nil +} + +type PublishCooperativeCloseResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + SettlementTxid []byte `protobuf:"bytes,1,opt,name=settlement_txid,json=settlementTxid,proto3" json:"settlement_txid,omitempty"` + HubFinalized bool `protobuf:"varint,2,opt,name=hub_finalized,json=hubFinalized,proto3" json:"hub_finalized,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PublishCooperativeCloseResponse) Reset() { + *x = PublishCooperativeCloseResponse{} + mi := &file_ark_channel_proto_msgTypes[55] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PublishCooperativeCloseResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PublishCooperativeCloseResponse) ProtoMessage() {} + +func (x *PublishCooperativeCloseResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[55] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PublishCooperativeCloseResponse.ProtoReflect.Descriptor instead. +func (*PublishCooperativeCloseResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{55} +} + +func (x *PublishCooperativeCloseResponse) GetSettlementTxid() []byte { + if x != nil { + return x.SettlementTxid + } + return nil +} + +func (x *PublishCooperativeCloseResponse) GetHubFinalized() bool { + if x != nil { + return x.HubFinalized + } + return false +} + +type AbortCooperativeCloseRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + ChannelId []byte `protobuf:"bytes,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AbortCooperativeCloseRequest) Reset() { + *x = AbortCooperativeCloseRequest{} + mi := &file_ark_channel_proto_msgTypes[56] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AbortCooperativeCloseRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AbortCooperativeCloseRequest) ProtoMessage() {} + +func (x *AbortCooperativeCloseRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[56] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AbortCooperativeCloseRequest.ProtoReflect.Descriptor instead. +func (*AbortCooperativeCloseRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{56} +} + +func (x *AbortCooperativeCloseRequest) GetChannelId() []byte { + if x != nil { + return x.ChannelId + } + return nil +} + +type AbortCooperativeCloseResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Channel *ArkChannel `protobuf:"bytes,1,opt,name=channel,proto3" json:"channel,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AbortCooperativeCloseResponse) Reset() { + *x = AbortCooperativeCloseResponse{} + mi := &file_ark_channel_proto_msgTypes[57] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AbortCooperativeCloseResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AbortCooperativeCloseResponse) ProtoMessage() {} + +func (x *AbortCooperativeCloseResponse) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[57] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AbortCooperativeCloseResponse.ProtoReflect.Descriptor instead. +func (*AbortCooperativeCloseResponse) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{57} +} + +func (x *AbortCooperativeCloseResponse) GetChannel() *ArkChannel { + if x != nil { + return x.Channel + } + return nil +} + +type CooperativeCloseRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + ClientDeliveryScript []byte `protobuf:"bytes,1,opt,name=client_delivery_script,json=clientDeliveryScript,proto3" json:"client_delivery_script,omitempty"` + HubDeliveryScript []byte `protobuf:"bytes,2,opt,name=hub_delivery_script,json=hubDeliveryScript,proto3" json:"hub_delivery_script,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CooperativeCloseRequest) Reset() { + *x = CooperativeCloseRequest{} + mi := &file_ark_channel_proto_msgTypes[58] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CooperativeCloseRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CooperativeCloseRequest) ProtoMessage() {} + +func (x *CooperativeCloseRequest) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[58] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CooperativeCloseRequest.ProtoReflect.Descriptor instead. +func (*CooperativeCloseRequest) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{58} +} + +func (x *CooperativeCloseRequest) GetClientDeliveryScript() []byte { + if x != nil { + return x.ClientDeliveryScript + } + return nil +} + +func (x *CooperativeCloseRequest) GetHubDeliveryScript() []byte { + if x != nil { + return x.HubDeliveryScript + } + return nil +} + +type CooperativeCloseProposal struct { + state protoimpl.MessageState `protogen:"open.v1"` + Transaction []byte `protobuf:"bytes,1,opt,name=transaction,proto3" json:"transaction,omitempty"` + CommitmentHeight uint64 `protobuf:"varint,2,opt,name=commitment_height,json=commitmentHeight,proto3" json:"commitment_height,omitempty"` + ClientBalanceSat int64 `protobuf:"varint,3,opt,name=client_balance_sat,json=clientBalanceSat,proto3" json:"client_balance_sat,omitempty"` + HubBalanceSat int64 `protobuf:"varint,4,opt,name=hub_balance_sat,json=hubBalanceSat,proto3" json:"hub_balance_sat,omitempty"` + ClientOutputSat int64 `protobuf:"varint,5,opt,name=client_output_sat,json=clientOutputSat,proto3" json:"client_output_sat,omitempty"` + HubOutputSat int64 `protobuf:"varint,6,opt,name=hub_output_sat,json=hubOutputSat,proto3" json:"hub_output_sat,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CooperativeCloseProposal) Reset() { + *x = CooperativeCloseProposal{} + mi := &file_ark_channel_proto_msgTypes[59] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CooperativeCloseProposal) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CooperativeCloseProposal) ProtoMessage() {} + +func (x *CooperativeCloseProposal) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[59] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CooperativeCloseProposal.ProtoReflect.Descriptor instead. +func (*CooperativeCloseProposal) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{59} +} + +func (x *CooperativeCloseProposal) GetTransaction() []byte { + if x != nil { + return x.Transaction + } + return nil +} + +func (x *CooperativeCloseProposal) GetCommitmentHeight() uint64 { + if x != nil { + return x.CommitmentHeight + } + return 0 +} + +func (x *CooperativeCloseProposal) GetClientBalanceSat() int64 { + if x != nil { + return x.ClientBalanceSat + } + return 0 +} + +func (x *CooperativeCloseProposal) GetHubBalanceSat() int64 { + if x != nil { + return x.HubBalanceSat + } + return 0 +} + +func (x *CooperativeCloseProposal) GetClientOutputSat() int64 { + if x != nil { + return x.ClientOutputSat + } + return 0 +} + +func (x *CooperativeCloseProposal) GetHubOutputSat() int64 { + if x != nil { + return x.HubOutputSat + } + return 0 +} + +type CooperativeClose struct { + state protoimpl.MessageState `protogen:"open.v1"` + Proposal *CooperativeCloseProposal `protobuf:"bytes,1,opt,name=proposal,proto3" json:"proposal,omitempty"` + Transaction []byte `protobuf:"bytes,2,opt,name=transaction,proto3" json:"transaction,omitempty"` + Txid []byte `protobuf:"bytes,3,opt,name=txid,proto3" json:"txid,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CooperativeClose) Reset() { + *x = CooperativeClose{} + mi := &file_ark_channel_proto_msgTypes[60] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CooperativeClose) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CooperativeClose) ProtoMessage() {} + +func (x *CooperativeClose) ProtoReflect() protoreflect.Message { + mi := &file_ark_channel_proto_msgTypes[60] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CooperativeClose.ProtoReflect.Descriptor instead. +func (*CooperativeClose) Descriptor() ([]byte, []int) { + return file_ark_channel_proto_rawDescGZIP(), []int{60} +} + +func (x *CooperativeClose) GetProposal() *CooperativeCloseProposal { + if x != nil { + return x.Proposal + } + return nil +} + +func (x *CooperativeClose) GetTransaction() []byte { + if x != nil { + return x.Transaction + } + return nil +} + +func (x *CooperativeClose) GetTxid() []byte { + if x != nil { + return x.Txid + } + return nil +} + +var File_ark_channel_proto protoreflect.FileDescriptor + +const file_ark_channel_proto_rawDesc = "" + + "\n" + + "\x11ark_channel.proto\x12\rarkchannelrpc\"\\\n" + + "\x12PromoteVTXORequest\x12\x1d\n" + + "\n" + + "amount_sat\x18\x01 \x01(\x03R\tamountSat\x12'\n" + + "\x0fidempotency_key\x18\x02 \x01(\tR\x0eidempotencyKey\"J\n" + + "\x13PromoteVTXOResponse\x123\n" + + "\achannel\x18\x01 \x01(\v2\x19.arkchannelrpc.ArkChannelR\achannel\"e\n" + + "\x1aPayLightningInvoiceRequest\x12'\n" + + "\x0fpayment_request\x18\x01 \x01(\tR\x0epaymentRequest\x12\x1e\n" + + "\vmax_fee_sat\x18\x02 \x01(\x04R\tmaxFeeSat\"\xc2\x01\n" + + "\x1bPayLightningInvoiceResponse\x12!\n" + + "\fpayment_hash\x18\x01 \x01(\fR\vpaymentHash\x12\x1a\n" + + "\bpreimage\x18\x02 \x01(\fR\bpreimage\x12,\n" + + "\x12private_amount_sat\x18\x03 \x01(\x03R\x10privateAmountSat\x12\x17\n" + + "\afee_sat\x18\x04 \x01(\x03R\x06feeSat\x12\x1d\n" + + "\n" + + "channel_id\x18\x05 \x01(\fR\tchannelId\"@\n" + + "\x1fMaterializeAndForceCloseRequest\x12\x1d\n" + + "\n" + + "channel_id\x18\x01 \x01(\fR\tchannelId\"\xa3\x01\n" + + " MaterializeAndForceCloseResponse\x123\n" + + "\achannel\x18\x01 \x01(\v2\x19.arkchannelrpc.ArkChannelR\achannel\x12!\n" + + "\fbacking_txid\x18\x02 \x01(\fR\vbackingTxid\x12'\n" + + "\x0fcommitment_txid\x18\x03 \x01(\fR\x0ecommitmentTxid\"\x14\n" + + "\x12GetPeerInfoRequest\"\xad\x02\n" + + "\x13GetPeerInfoResponse\x12 \n" + + "\fhub_node_key\x18\x01 \x01(\fR\n" + + "hubNodeKey\x12\x1e\n" + + "\vhub_ark_key\x18\x02 \x01(\fR\thubArkKey\x12&\n" + + "\x0fhub_channel_key\x18\x03 \x01(\fR\rhubChannelKey\x12(\n" + + "\x10ark_operator_key\x18\x04 \x01(\fR\x0earkOperatorKey\x12#\n" + + "\rchannel_delay\x18\x05 \x01(\rR\fchannelDelay\x12!\n" + + "\ffunder_delay\x18\x06 \x01(\rR\vfunderDelay\x12$\n" + + "\x0emin_exit_delay\x18\a \x01(\rR\fminExitDelayJ\x04\b\b\x10\tR\x0ehub_funder_key\"M\n" + + "\x18RegisterPromotionRequest\x121\n" + + "\x05terms\x18\x01 \x01(\v2\x1b.arkchannelrpc.ChannelTermsR\x05terms\"P\n" + + "\x19RegisterPromotionResponse\x123\n" + + "\achannel\x18\x01 \x01(\v2\x19.arkchannelrpc.ArkChannelR\achannel\"9\n" + + "\x18GetFundingChannelRequest\x12\x1d\n" + + "\n" + + "channel_id\x18\x01 \x01(\fR\tchannelId\"\xb8\x03\n" + + "\x19GetFundingChannelResponse\x121\n" + + "\x05terms\x18\x01 \x01(\v2\x1b.arkchannelrpc.ChannelTermsR\x05terms\x12;\n" + + "\abinding\x18\x02 \x01(\v2!.arkchannelrpc.ChannelVTXOBindingR\abinding\x127\n" + + "\abacking\x18\x03 \x01(\v2\x1d.arkchannelrpc.ChannelBackingR\abacking\x12\x14\n" + + "\x05phase\x18\x04 \x01(\rR\x05phase\x12#\n" + + "\roor_finalized\x18\x05 \x01(\bR\foorFinalized\x122\n" + + "\x15client_recovery_ready\x18\x06 \x01(\bR\x13clientRecoveryReady\x12\x18\n" + + "\afailure\x18\a \x01(\tR\afailure\x12\x1a\n" + + "\brevision\x18\b \x01(\x04R\brevision\x12\x1f\n" + + "\voor_aborted\x18\t \x01(\bR\n" + + "oorAborted\x12,\n" + + "\x12hub_recovery_ready\x18\n" + + " \x01(\bR\x10hubRecoveryReady\"t\n" + + "\x16BindPreparedOORRequest\x12\x1d\n" + + "\n" + + "channel_id\x18\x01 \x01(\fR\tchannelId\x12;\n" + + "\abinding\x18\x02 \x01(\v2!.arkchannelrpc.ChannelVTXOBindingR\abinding\"N\n" + + "\x17BindPreparedOORResponse\x123\n" + + "\achannel\x18\x01 \x01(\v2\x19.arkchannelrpc.ArkChannelR\achannel\"\xc6\x01\n" + + "\x12SignBackingRequest\x12\x1d\n" + + "\n" + + "channel_id\x18\x01 \x01(\fR\tchannelId\x121\n" + + "\x05terms\x18\x02 \x01(\v2\x1b.arkchannelrpc.ChannelTermsR\x05terms\x12;\n" + + "\abinding\x18\x03 \x01(\v2!.arkchannelrpc.ChannelVTXOBindingR\abinding\x12!\n" + + "\ffunding_psbt\x18\x04 \x01(\fR\vfundingPsbt\"3\n" + + "\x13SignBackingResponse\x12\x1c\n" + + "\tsignature\x18\x01 \x01(\fR\tsignature\"\xdf\x01\n" + + "\x15InstallBackingRequest\x12\x1d\n" + + "\n" + + "channel_id\x18\x01 \x01(\fR\tchannelId\x121\n" + + "\x05terms\x18\x02 \x01(\v2\x1b.arkchannelrpc.ChannelTermsR\x05terms\x12;\n" + + "\abinding\x18\x03 \x01(\v2!.arkchannelrpc.ChannelVTXOBindingR\abinding\x127\n" + + "\abacking\x18\x04 \x01(\v2\x1d.arkchannelrpc.ChannelBackingR\abacking\"\x18\n" + + "\x16InstallBackingResponse\"\xf1\x01\n" + + "\x1dInstallRecoveryPackageRequest\x12\x1d\n" + + "\n" + + "channel_id\x18\x01 \x01(\fR\tchannelId\x121\n" + + "\x05terms\x18\x02 \x01(\v2\x1b.arkchannelrpc.ChannelTermsR\x05terms\x12;\n" + + "\abinding\x18\x03 \x01(\v2!.arkchannelrpc.ChannelVTXOBindingR\abinding\x12A\n" + + "\brecovery\x18\x04 \x01(\v2%.arkchannelrpc.ChannelRecoveryPackageR\brecovery\" \n" + + "\x1eInstallRecoveryPackageResponse\"\x86\x01\n" + + "\x11OORRecoverySource\x12\x12\n" + + "\x04txid\x18\x01 \x01(\fR\x04txid\x12!\n" + + "\foutput_index\x18\x02 \x01(\rR\voutputIndex\x12\x1d\n" + + "\n" + + "amount_sat\x18\x03 \x01(\x03R\tamountSat\x12\x1b\n" + + "\tpk_script\x18\x04 \x01(\fR\bpkScript\"\xbc\x01\n" + + "\x16ChannelRecoveryPackage\x12U\n" + + "\x11source_descriptor\x18\x01 \x01(\v2(.arkchannelrpc.ChannelRecoveryDescriptorR\x10sourceDescriptor\x12K\n" + + "\foor_packages\x18\x02 \x03(\v2(.arkchannelrpc.ChannelRecoveryOORPackageR\voorPackages\"\xc1\x02\n" + + "\x19ChannelRecoveryDescriptor\x12B\n" + + "\bancestry\x18\x01 \x03(\v2&.arkchannelrpc.ChannelRecoveryAncestryR\bancestry\x12\x19\n" + + "\bround_id\x18\x02 \x01(\tR\aroundId\x12'\n" + + "\x0fcommitment_txid\x18\x03 \x01(\fR\x0ecommitmentTxid\x12!\n" + + "\fbatch_expiry\x18\x04 \x01(\x05R\vbatchExpiry\x12\x1f\n" + + "\vchain_depth\x18\x05 \x01(\x05R\n" + + "chainDepth\x12%\n" + + "\x0ecreated_height\x18\x06 \x01(\x05R\rcreatedHeight\x121\n" + + "\x14construction_version\x18\a \x01(\x05R\x13constructionVersion\"\xd0\x01\n" + + "\x17ChannelRecoveryAncestry\x12\x1b\n" + + "\ttree_path\x18\x01 \x01(\fR\btreePath\x12'\n" + + "\x0fcommitment_txid\x18\x02 \x01(\fR\x0ecommitmentTxid\x12#\n" + + "\rinput_indices\x18\x03 \x03(\rR\finputIndices\x12\x1d\n" + + "\n" + + "tree_depth\x18\x04 \x01(\rR\ttreeDepth\x12+\n" + + "\x11commitment_height\x18\x05 \x01(\x05R\x10commitmentHeight\"\x9e\x01\n" + + "\x19ChannelRecoveryOORPackage\x12\x1d\n" + + "\n" + + "session_id\x18\x01 \x01(\fR\tsessionId\x12\x1c\n" + + "\tdirection\x18\x02 \x01(\x05R\tdirection\x12\x19\n" + + "\bark_psbt\x18\x03 \x01(\fR\aarkPsbt\x12)\n" + + "\x10checkpoint_psbts\x18\x04 \x03(\fR\x0fcheckpointPsbts\"\x82\x01\n" + + "\x14FundingStatusRequest\x121\n" + + "\x05terms\x18\x01 \x01(\v2\x1b.arkchannelrpc.ChannelTermsR\x05terms\x127\n" + + "\abacking\x18\x02 \x01(\v2\x1d.arkchannelrpc.ChannelBackingR\abacking\"-\n" + + "\x15FundingStatusResponse\x12\x14\n" + + "\x05ready\x18\x01 \x01(\bR\x05ready\"\xba\x02\n" + + "\x18ApplyChannelEventRequest\x12\x1d\n" + + "\n" + + "channel_id\x18\x01 \x01(\fR\tchannelId\x12>\n" + + "\n" + + "event_type\x18\x02 \x01(\x0e2\x1f.arkchannelrpc.ChannelEventTypeR\teventType\x12\x14\n" + + "\x05party\x18\x03 \x01(\rR\x05party\x12$\n" + + "\x0eoor_session_id\x18\x04 \x01(\fR\foorSessionId\x12,\n" + + "\x12channel_point_txid\x18\x05 \x01(\fR\x10channelPointTxid\x12.\n" + + "\x13channel_point_index\x18\x06 \x01(\rR\x11channelPointIndex\x12%\n" + + "\x0efailure_reason\x18\a \x01(\tR\rfailureReason\"P\n" + + "\x19ApplyChannelEventResponse\x123\n" + + "\achannel\x18\x01 \x01(\v2\x19.arkchannelrpc.ArkChannelR\achannel\"h\n" + + "\x1dPrepareOutgoingPaymentRequest\x12'\n" + + "\x0fpayment_request\x18\x01 \x01(\tR\x0epaymentRequest\x12\x1e\n" + + "\vmax_fee_sat\x18\x02 \x01(\x04R\tmaxFeeSat\"\xce\x01\n" + + "\x1ePrepareOutgoingPaymentResponse\x12!\n" + + "\fpayment_hash\x18\x01 \x01(\fR\vpaymentHash\x12,\n" + + "\x12private_amount_sat\x18\x02 \x01(\x03R\x10privateAmountSat\x12\x17\n" + + "\afee_sat\x18\x03 \x01(\x03R\x06feeSat\x12\x1d\n" + + "\n" + + "channel_id\x18\x04 \x01(\fR\tchannelId\x12#\n" + + "\rreserved_scid\x18\x05 \x01(\x04R\freservedScid\"Y\n" + + "\x1cCancelOutgoingPaymentRequest\x12!\n" + + "\fpayment_hash\x18\x01 \x01(\fR\vpaymentHash\x12\x16\n" + + "\x06reason\x18\x02 \x01(\tR\x06reason\"=\n" + + "\x1dCancelOutgoingPaymentResponse\x12\x1c\n" + + "\tcancelled\x18\x01 \x01(\bR\tcancelled\"\x87\x01\n" + + "\x1eRegisterIncomingPaymentRequest\x12!\n" + + "\fpayment_hash\x18\x01 \x01(\fR\vpaymentHash\x12\x1d\n" + + "\n" + + "amount_sat\x18\x02 \x01(\x03R\tamountSat\x12#\n" + + "\rreserved_scid\x18\x03 \x01(\x04R\freservedScid\"|\n" + + "\x1fRegisterIncomingPaymentResponse\x12\x1e\n" + + "\n" + + "registered\x18\x01 \x01(\bR\n" + + "registered\x12\x1d\n" + + "\n" + + "channel_id\x18\x03 \x01(\fR\tchannelIdJ\x04\b\x02\x10\x03R\x14channel_capacity_sat\"Y\n" + + "\x1cCancelIncomingPaymentRequest\x12!\n" + + "\fpayment_hash\x18\x01 \x01(\fR\vpaymentHash\x12\x16\n" + + "\x06reason\x18\x02 \x01(\tR\x06reason\"=\n" + + "\x1dCancelIncomingPaymentResponse\x12\x1c\n" + + "\tcancelled\x18\x01 \x01(\bR\tcancelled\"\xe2\x02\n" + + "\fChannelTerms\x12\x1d\n" + + "\n" + + "channel_id\x18\x01 \x01(\fR\tchannelId\x12\x12\n" + + "\x04kind\x18\x02 \x01(\rR\x04kind\x12\x16\n" + + "\x06funder\x18\x03 \x01(\rR\x06funder\x12,\n" + + "\x12pending_channel_id\x18\x04 \x01(\fR\x10pendingChannelId\x12#\n" + + "\rreserved_scid\x18\x05 \x01(\x04R\freservedScid\x12!\n" + + "\fcapacity_sat\x18\x06 \x01(\x03R\vcapacitySat\x12&\n" + + "\x0fclient_node_key\x18\a \x01(\fR\rclientNodeKey\x12 \n" + + "\fhub_node_key\x18\b \x01(\fR\n" + + "hubNodeKey\x123\n" + + "\x04vtxo\x18\n" + + " \x01(\v2\x1f.arkchannelrpc.ChannelVTXOTermsR\x04vtxoJ\x04\b\t\x10\n" + + "R\fpayment_hash\"\xe5\x02\n" + + "\x10ChannelVTXOTerms\x12$\n" + + "\x0eclient_ark_key\x18\x01 \x01(\fR\fclientArkKey\x12\x1e\n" + + "\vhub_ark_key\x18\x02 \x01(\fR\thubArkKey\x12(\n" + + "\x10ark_operator_key\x18\x03 \x01(\fR\x0earkOperatorKey\x12,\n" + + "\x12client_channel_key\x18\x04 \x01(\fR\x10clientChannelKey\x12&\n" + + "\x0fhub_channel_key\x18\x05 \x01(\fR\rhubChannelKey\x12\x1d\n" + + "\n" + + "funder_key\x18\x06 \x01(\fR\tfunderKey\x12#\n" + + "\rchannel_delay\x18\a \x01(\rR\fchannelDelay\x12!\n" + + "\ffunder_delay\x18\b \x01(\rR\vfunderDelay\x12$\n" + + "\x0emin_exit_delay\x18\t \x01(\rR\fminExitDelay\"\x94\x02\n" + + "\x12ChannelVTXOBinding\x12$\n" + + "\x0eoor_session_id\x18\x01 \x01(\fR\foorSessionId\x12#\n" + + "\routpoint_txid\x18\x02 \x01(\fR\foutpointTxid\x12%\n" + + "\x0eoutpoint_index\x18\x03 \x01(\rR\routpointIndex\x12\x1d\n" + + "\n" + + "amount_sat\x18\x04 \x01(\x03R\tamountSat\x12'\n" + + "\x0fark_transaction\x18\x05 \x01(\fR\x0earkTransaction\x12'\n" + + "\x0fpolicy_template\x18\x06 \x01(\fR\x0epolicyTemplate\x12\x1b\n" + + "\tpk_script\x18\a \x01(\fR\bpkScript\"\x90\x01\n" + + "\x0eChannelBacking\x12 \n" + + "\vtransaction\x18\x01 \x01(\fR\vtransaction\x12,\n" + + "\x12channel_point_txid\x18\x02 \x01(\fR\x10channelPointTxid\x12.\n" + + "\x13channel_point_index\x18\x03 \x01(\rR\x11channelPointIndex\"Q\n" + + "\x15RefreshChannelRequest\x12\x1d\n" + + "\n" + + "channel_id\x18\x01 \x01(\fR\tchannelIdJ\x04\b\x02\x10\x03R\x13fee_rate_sat_per_kw\"M\n" + + "\x16RefreshChannelResponse\x123\n" + + "\achannel\x18\x01 \x01(\v2\x19.arkchannelrpc.ArkChannelR\achannel\"2\n" + + "\x11GetChannelRequest\x12\x1d\n" + + "\n" + + "channel_id\x18\x01 \x01(\fR\tchannelId\"I\n" + + "\x12GetChannelResponse\x123\n" + + "\achannel\x18\x01 \x01(\v2\x19.arkchannelrpc.ArkChannelR\achannel\"\x15\n" + + "\x13ListChannelsRequest\"M\n" + + "\x14ListChannelsResponse\x125\n" + + "\bchannels\x18\x01 \x03(\v2\x19.arkchannelrpc.ArkChannelR\bchannels\"\xf5\x03\n" + + "\n" + + "ArkChannel\x12\x1d\n" + + "\n" + + "channel_id\x18\x01 \x01(\fR\tchannelId\x12\x12\n" + + "\x04kind\x18\x02 \x01(\tR\x04kind\x12\x14\n" + + "\x05phase\x18\x03 \x01(\tR\x05phase\x12\x16\n" + + "\x06funder\x18\x04 \x01(\tR\x06funder\x12!\n" + + "\fcapacity_sat\x18\x05 \x01(\x03R\vcapacitySat\x12'\n" + + "\x0fsource_outpoint\x18\x06 \x01(\tR\x0esourceOutpoint\x12#\n" + + "\rchannel_point\x18\a \x01(\tR\fchannelPoint\x12(\n" + + "\x10refresh_oor_txid\x18\b \x01(\fR\x0erefreshOorTxid\x12\x1a\n" + + "\brevision\x18\t \x01(\x04R\brevision\x12#\n" + + "\rreserved_scid\x18\n" + + " \x01(\x04R\freservedScid\x12*\n" + + "\x11local_balance_sat\x18\v \x01(\x03R\x0flocalBalanceSat\x12,\n" + + "\x12remote_balance_sat\x18\f \x01(\x03R\x10remoteBalanceSat\x12+\n" + + "\x11balance_available\x18\r \x01(\bR\x10balanceAvailable\x12#\n" + + "\rbalance_error\x18\x0e \x01(\tR\fbalanceError\"\x91\x01\n" + + "\x1fGetCooperativeCloseTermsRequest\x12\x1d\n" + + "\n" + + "channel_id\x18\x01 \x01(\fR\tchannelId\x124\n" + + "\x16client_delivery_script\x18\x02 \x01(\fR\x14clientDeliveryScriptJ\x04\b\x03\x10\x04R\x13fee_rate_sat_per_kw\"\x89\x01\n" + + " GetCooperativeCloseTermsResponse\x12@\n" + + "\arequest\x18\x01 \x01(\v2&.arkchannelrpc.CooperativeCloseRequestR\arequestJ\x04\b\x02\x10\x03J\x04\b\x03\x10\x04R\vclean_stateR\n" + + "settlement\"\xdf\x01\n" + + "\x1fCompleteCooperativeCloseRequest\x12\x1d\n" + + "\n" + + "channel_id\x18\x01 \x01(\fR\tchannelId\x12C\n" + + "\bproposal\x18\x02 \x01(\v2'.arkchannelrpc.CooperativeCloseProposalR\bproposal\x12@\n" + + "\arequest\x18\x04 \x01(\v2&.arkchannelrpc.CooperativeCloseRequestR\arequestJ\x04\b\x03\x10\x04R\x10client_signature\"c\n" + + " CompleteCooperativeCloseResponse\x12?\n" + + "\n" + + "settlement\x18\x01 \x01(\v2\x1f.arkchannelrpc.CooperativeCloseR\n" + + "settlement\"t\n" + + "\x1eConfirmCooperativeCloseRequest\x12\x1d\n" + + "\n" + + "channel_id\x18\x01 \x01(\fR\tchannelId\x123\n" + + "\x15authorization_receipt\x18\x02 \x01(\fR\x14authorizationReceipt\"!\n" + + "\x1fConfirmCooperativeCloseResponse\"h\n" + + "\x1ePublishCooperativeCloseRequest\x12\x1d\n" + + "\n" + + "channel_id\x18\x01 \x01(\fR\tchannelId\x12'\n" + + "\x0fsettlement_txid\x18\x02 \x01(\fR\x0esettlementTxid\"o\n" + + "\x1fPublishCooperativeCloseResponse\x12'\n" + + "\x0fsettlement_txid\x18\x01 \x01(\fR\x0esettlementTxid\x12#\n" + + "\rhub_finalized\x18\x02 \x01(\bR\fhubFinalized\"=\n" + + "\x1cAbortCooperativeCloseRequest\x12\x1d\n" + + "\n" + + "channel_id\x18\x01 \x01(\fR\tchannelId\"T\n" + + "\x1dAbortCooperativeCloseResponse\x123\n" + + "\achannel\x18\x01 \x01(\v2\x19.arkchannelrpc.ArkChannelR\achannel\"\x9a\x01\n" + + "\x17CooperativeCloseRequest\x124\n" + + "\x16client_delivery_script\x18\x01 \x01(\fR\x14clientDeliveryScript\x12.\n" + + "\x13hub_delivery_script\x18\x02 \x01(\fR\x11hubDeliveryScriptJ\x04\b\x03\x10\x04R\x13fee_rate_sat_per_kw\"\xa0\x02\n" + + "\x18CooperativeCloseProposal\x12 \n" + + "\vtransaction\x18\x01 \x01(\fR\vtransaction\x12+\n" + + "\x11commitment_height\x18\x02 \x01(\x04R\x10commitmentHeight\x12,\n" + + "\x12client_balance_sat\x18\x03 \x01(\x03R\x10clientBalanceSat\x12&\n" + + "\x0fhub_balance_sat\x18\x04 \x01(\x03R\rhubBalanceSat\x12*\n" + + "\x11client_output_sat\x18\x05 \x01(\x03R\x0fclientOutputSat\x12$\n" + + "\x0ehub_output_sat\x18\x06 \x01(\x03R\fhubOutputSatJ\x04\b\a\x10\bR\afee_sat\"\x8d\x01\n" + + "\x10CooperativeClose\x12C\n" + + "\bproposal\x18\x01 \x01(\v2'.arkchannelrpc.CooperativeCloseProposalR\bproposal\x12 \n" + + "\vtransaction\x18\x02 \x01(\fR\vtransaction\x12\x12\n" + + "\x04txid\x18\x03 \x01(\fR\x04txid*\xa2\x02\n" + + "\x10ChannelEventType\x12\"\n" + + "\x1eCHANNEL_EVENT_TYPE_UNSPECIFIED\x10\x00\x12(\n" + + "$CHANNEL_EVENT_TYPE_FUNDING_FINALIZED\x10\x01\x12$\n" + + " CHANNEL_EVENT_TYPE_OOR_FINALIZED\x10\x02\x121\n" + + "-CHANNEL_EVENT_TYPE_RECOVERY_PACKAGE_INSTALLED\x10\x06\x12\"\n" + + "\x1eCHANNEL_EVENT_TYPE_OOR_ABORTED\x10\t\"\x04\b\x03\x10\x03\"\x04\b\x04\x10\x04\"\x04\b\x05\x10\x05\"\x04\b\a\x10\a\"\x04\b\b\x10\b*%CHANNEL_EVENT_TYPE_FUNDING_PEER_READY2\xdf\x04\n" + + "\x11ArkChannelService\x12T\n" + + "\vPromoteVTXO\x12!.arkchannelrpc.PromoteVTXORequest\x1a\".arkchannelrpc.PromoteVTXOResponse\x12l\n" + + "\x13PayLightningInvoice\x12).arkchannelrpc.PayLightningInvoiceRequest\x1a*.arkchannelrpc.PayLightningInvoiceResponse\x12{\n" + + "\x18MaterializeAndForceClose\x12..arkchannelrpc.MaterializeAndForceCloseRequest\x1a/.arkchannelrpc.MaterializeAndForceCloseResponse\x12]\n" + + "\x0eRefreshChannel\x12$.arkchannelrpc.RefreshChannelRequest\x1a%.arkchannelrpc.RefreshChannelResponse\x12Q\n" + + "\n" + + "GetChannel\x12 .arkchannelrpc.GetChannelRequest\x1a!.arkchannelrpc.GetChannelResponse\x12W\n" + + "\fListChannels\x12\".arkchannelrpc.ListChannelsRequest\x1a#.arkchannelrpc.ListChannelsResponseB7Z5github.com/lightninglabs/wavelength/rpc/arkchannelrpcb\x06proto3" + +var ( + file_ark_channel_proto_rawDescOnce sync.Once + file_ark_channel_proto_rawDescData []byte +) + +func file_ark_channel_proto_rawDescGZIP() []byte { + file_ark_channel_proto_rawDescOnce.Do(func() { + file_ark_channel_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_ark_channel_proto_rawDesc), len(file_ark_channel_proto_rawDesc))) + }) + return file_ark_channel_proto_rawDescData +} + +var file_ark_channel_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_ark_channel_proto_msgTypes = make([]protoimpl.MessageInfo, 61) +var file_ark_channel_proto_goTypes = []any{ + (ChannelEventType)(0), // 0: arkchannelrpc.ChannelEventType + (*PromoteVTXORequest)(nil), // 1: arkchannelrpc.PromoteVTXORequest + (*PromoteVTXOResponse)(nil), // 2: arkchannelrpc.PromoteVTXOResponse + (*PayLightningInvoiceRequest)(nil), // 3: arkchannelrpc.PayLightningInvoiceRequest + (*PayLightningInvoiceResponse)(nil), // 4: arkchannelrpc.PayLightningInvoiceResponse + (*MaterializeAndForceCloseRequest)(nil), // 5: arkchannelrpc.MaterializeAndForceCloseRequest + (*MaterializeAndForceCloseResponse)(nil), // 6: arkchannelrpc.MaterializeAndForceCloseResponse + (*GetPeerInfoRequest)(nil), // 7: arkchannelrpc.GetPeerInfoRequest + (*GetPeerInfoResponse)(nil), // 8: arkchannelrpc.GetPeerInfoResponse + (*RegisterPromotionRequest)(nil), // 9: arkchannelrpc.RegisterPromotionRequest + (*RegisterPromotionResponse)(nil), // 10: arkchannelrpc.RegisterPromotionResponse + (*GetFundingChannelRequest)(nil), // 11: arkchannelrpc.GetFundingChannelRequest + (*GetFundingChannelResponse)(nil), // 12: arkchannelrpc.GetFundingChannelResponse + (*BindPreparedOORRequest)(nil), // 13: arkchannelrpc.BindPreparedOORRequest + (*BindPreparedOORResponse)(nil), // 14: arkchannelrpc.BindPreparedOORResponse + (*SignBackingRequest)(nil), // 15: arkchannelrpc.SignBackingRequest + (*SignBackingResponse)(nil), // 16: arkchannelrpc.SignBackingResponse + (*InstallBackingRequest)(nil), // 17: arkchannelrpc.InstallBackingRequest + (*InstallBackingResponse)(nil), // 18: arkchannelrpc.InstallBackingResponse + (*InstallRecoveryPackageRequest)(nil), // 19: arkchannelrpc.InstallRecoveryPackageRequest + (*InstallRecoveryPackageResponse)(nil), // 20: arkchannelrpc.InstallRecoveryPackageResponse + (*OORRecoverySource)(nil), // 21: arkchannelrpc.OORRecoverySource + (*ChannelRecoveryPackage)(nil), // 22: arkchannelrpc.ChannelRecoveryPackage + (*ChannelRecoveryDescriptor)(nil), // 23: arkchannelrpc.ChannelRecoveryDescriptor + (*ChannelRecoveryAncestry)(nil), // 24: arkchannelrpc.ChannelRecoveryAncestry + (*ChannelRecoveryOORPackage)(nil), // 25: arkchannelrpc.ChannelRecoveryOORPackage + (*FundingStatusRequest)(nil), // 26: arkchannelrpc.FundingStatusRequest + (*FundingStatusResponse)(nil), // 27: arkchannelrpc.FundingStatusResponse + (*ApplyChannelEventRequest)(nil), // 28: arkchannelrpc.ApplyChannelEventRequest + (*ApplyChannelEventResponse)(nil), // 29: arkchannelrpc.ApplyChannelEventResponse + (*PrepareOutgoingPaymentRequest)(nil), // 30: arkchannelrpc.PrepareOutgoingPaymentRequest + (*PrepareOutgoingPaymentResponse)(nil), // 31: arkchannelrpc.PrepareOutgoingPaymentResponse + (*CancelOutgoingPaymentRequest)(nil), // 32: arkchannelrpc.CancelOutgoingPaymentRequest + (*CancelOutgoingPaymentResponse)(nil), // 33: arkchannelrpc.CancelOutgoingPaymentResponse + (*RegisterIncomingPaymentRequest)(nil), // 34: arkchannelrpc.RegisterIncomingPaymentRequest + (*RegisterIncomingPaymentResponse)(nil), // 35: arkchannelrpc.RegisterIncomingPaymentResponse + (*CancelIncomingPaymentRequest)(nil), // 36: arkchannelrpc.CancelIncomingPaymentRequest + (*CancelIncomingPaymentResponse)(nil), // 37: arkchannelrpc.CancelIncomingPaymentResponse + (*ChannelTerms)(nil), // 38: arkchannelrpc.ChannelTerms + (*ChannelVTXOTerms)(nil), // 39: arkchannelrpc.ChannelVTXOTerms + (*ChannelVTXOBinding)(nil), // 40: arkchannelrpc.ChannelVTXOBinding + (*ChannelBacking)(nil), // 41: arkchannelrpc.ChannelBacking + (*RefreshChannelRequest)(nil), // 42: arkchannelrpc.RefreshChannelRequest + (*RefreshChannelResponse)(nil), // 43: arkchannelrpc.RefreshChannelResponse + (*GetChannelRequest)(nil), // 44: arkchannelrpc.GetChannelRequest + (*GetChannelResponse)(nil), // 45: arkchannelrpc.GetChannelResponse + (*ListChannelsRequest)(nil), // 46: arkchannelrpc.ListChannelsRequest + (*ListChannelsResponse)(nil), // 47: arkchannelrpc.ListChannelsResponse + (*ArkChannel)(nil), // 48: arkchannelrpc.ArkChannel + (*GetCooperativeCloseTermsRequest)(nil), // 49: arkchannelrpc.GetCooperativeCloseTermsRequest + (*GetCooperativeCloseTermsResponse)(nil), // 50: arkchannelrpc.GetCooperativeCloseTermsResponse + (*CompleteCooperativeCloseRequest)(nil), // 51: arkchannelrpc.CompleteCooperativeCloseRequest + (*CompleteCooperativeCloseResponse)(nil), // 52: arkchannelrpc.CompleteCooperativeCloseResponse + (*ConfirmCooperativeCloseRequest)(nil), // 53: arkchannelrpc.ConfirmCooperativeCloseRequest + (*ConfirmCooperativeCloseResponse)(nil), // 54: arkchannelrpc.ConfirmCooperativeCloseResponse + (*PublishCooperativeCloseRequest)(nil), // 55: arkchannelrpc.PublishCooperativeCloseRequest + (*PublishCooperativeCloseResponse)(nil), // 56: arkchannelrpc.PublishCooperativeCloseResponse + (*AbortCooperativeCloseRequest)(nil), // 57: arkchannelrpc.AbortCooperativeCloseRequest + (*AbortCooperativeCloseResponse)(nil), // 58: arkchannelrpc.AbortCooperativeCloseResponse + (*CooperativeCloseRequest)(nil), // 59: arkchannelrpc.CooperativeCloseRequest + (*CooperativeCloseProposal)(nil), // 60: arkchannelrpc.CooperativeCloseProposal + (*CooperativeClose)(nil), // 61: arkchannelrpc.CooperativeClose +} +var file_ark_channel_proto_depIdxs = []int32{ + 48, // 0: arkchannelrpc.PromoteVTXOResponse.channel:type_name -> arkchannelrpc.ArkChannel + 48, // 1: arkchannelrpc.MaterializeAndForceCloseResponse.channel:type_name -> arkchannelrpc.ArkChannel + 38, // 2: arkchannelrpc.RegisterPromotionRequest.terms:type_name -> arkchannelrpc.ChannelTerms + 48, // 3: arkchannelrpc.RegisterPromotionResponse.channel:type_name -> arkchannelrpc.ArkChannel + 38, // 4: arkchannelrpc.GetFundingChannelResponse.terms:type_name -> arkchannelrpc.ChannelTerms + 40, // 5: arkchannelrpc.GetFundingChannelResponse.binding:type_name -> arkchannelrpc.ChannelVTXOBinding + 41, // 6: arkchannelrpc.GetFundingChannelResponse.backing:type_name -> arkchannelrpc.ChannelBacking + 40, // 7: arkchannelrpc.BindPreparedOORRequest.binding:type_name -> arkchannelrpc.ChannelVTXOBinding + 48, // 8: arkchannelrpc.BindPreparedOORResponse.channel:type_name -> arkchannelrpc.ArkChannel + 38, // 9: arkchannelrpc.SignBackingRequest.terms:type_name -> arkchannelrpc.ChannelTerms + 40, // 10: arkchannelrpc.SignBackingRequest.binding:type_name -> arkchannelrpc.ChannelVTXOBinding + 38, // 11: arkchannelrpc.InstallBackingRequest.terms:type_name -> arkchannelrpc.ChannelTerms + 40, // 12: arkchannelrpc.InstallBackingRequest.binding:type_name -> arkchannelrpc.ChannelVTXOBinding + 41, // 13: arkchannelrpc.InstallBackingRequest.backing:type_name -> arkchannelrpc.ChannelBacking + 38, // 14: arkchannelrpc.InstallRecoveryPackageRequest.terms:type_name -> arkchannelrpc.ChannelTerms + 40, // 15: arkchannelrpc.InstallRecoveryPackageRequest.binding:type_name -> arkchannelrpc.ChannelVTXOBinding + 22, // 16: arkchannelrpc.InstallRecoveryPackageRequest.recovery:type_name -> arkchannelrpc.ChannelRecoveryPackage + 23, // 17: arkchannelrpc.ChannelRecoveryPackage.source_descriptor:type_name -> arkchannelrpc.ChannelRecoveryDescriptor + 25, // 18: arkchannelrpc.ChannelRecoveryPackage.oor_packages:type_name -> arkchannelrpc.ChannelRecoveryOORPackage + 24, // 19: arkchannelrpc.ChannelRecoveryDescriptor.ancestry:type_name -> arkchannelrpc.ChannelRecoveryAncestry + 38, // 20: arkchannelrpc.FundingStatusRequest.terms:type_name -> arkchannelrpc.ChannelTerms + 41, // 21: arkchannelrpc.FundingStatusRequest.backing:type_name -> arkchannelrpc.ChannelBacking + 0, // 22: arkchannelrpc.ApplyChannelEventRequest.event_type:type_name -> arkchannelrpc.ChannelEventType + 48, // 23: arkchannelrpc.ApplyChannelEventResponse.channel:type_name -> arkchannelrpc.ArkChannel + 39, // 24: arkchannelrpc.ChannelTerms.vtxo:type_name -> arkchannelrpc.ChannelVTXOTerms + 48, // 25: arkchannelrpc.RefreshChannelResponse.channel:type_name -> arkchannelrpc.ArkChannel + 48, // 26: arkchannelrpc.GetChannelResponse.channel:type_name -> arkchannelrpc.ArkChannel + 48, // 27: arkchannelrpc.ListChannelsResponse.channels:type_name -> arkchannelrpc.ArkChannel + 59, // 28: arkchannelrpc.GetCooperativeCloseTermsResponse.request:type_name -> arkchannelrpc.CooperativeCloseRequest + 60, // 29: arkchannelrpc.CompleteCooperativeCloseRequest.proposal:type_name -> arkchannelrpc.CooperativeCloseProposal + 59, // 30: arkchannelrpc.CompleteCooperativeCloseRequest.request:type_name -> arkchannelrpc.CooperativeCloseRequest + 61, // 31: arkchannelrpc.CompleteCooperativeCloseResponse.settlement:type_name -> arkchannelrpc.CooperativeClose + 48, // 32: arkchannelrpc.AbortCooperativeCloseResponse.channel:type_name -> arkchannelrpc.ArkChannel + 60, // 33: arkchannelrpc.CooperativeClose.proposal:type_name -> arkchannelrpc.CooperativeCloseProposal + 1, // 34: arkchannelrpc.ArkChannelService.PromoteVTXO:input_type -> arkchannelrpc.PromoteVTXORequest + 3, // 35: arkchannelrpc.ArkChannelService.PayLightningInvoice:input_type -> arkchannelrpc.PayLightningInvoiceRequest + 5, // 36: arkchannelrpc.ArkChannelService.MaterializeAndForceClose:input_type -> arkchannelrpc.MaterializeAndForceCloseRequest + 42, // 37: arkchannelrpc.ArkChannelService.RefreshChannel:input_type -> arkchannelrpc.RefreshChannelRequest + 44, // 38: arkchannelrpc.ArkChannelService.GetChannel:input_type -> arkchannelrpc.GetChannelRequest + 46, // 39: arkchannelrpc.ArkChannelService.ListChannels:input_type -> arkchannelrpc.ListChannelsRequest + 2, // 40: arkchannelrpc.ArkChannelService.PromoteVTXO:output_type -> arkchannelrpc.PromoteVTXOResponse + 4, // 41: arkchannelrpc.ArkChannelService.PayLightningInvoice:output_type -> arkchannelrpc.PayLightningInvoiceResponse + 6, // 42: arkchannelrpc.ArkChannelService.MaterializeAndForceClose:output_type -> arkchannelrpc.MaterializeAndForceCloseResponse + 43, // 43: arkchannelrpc.ArkChannelService.RefreshChannel:output_type -> arkchannelrpc.RefreshChannelResponse + 45, // 44: arkchannelrpc.ArkChannelService.GetChannel:output_type -> arkchannelrpc.GetChannelResponse + 47, // 45: arkchannelrpc.ArkChannelService.ListChannels:output_type -> arkchannelrpc.ListChannelsResponse + 40, // [40:46] is the sub-list for method output_type + 34, // [34:40] is the sub-list for method input_type + 34, // [34:34] is the sub-list for extension type_name + 34, // [34:34] is the sub-list for extension extendee + 0, // [0:34] is the sub-list for field type_name +} + +func init() { file_ark_channel_proto_init() } +func file_ark_channel_proto_init() { + if File_ark_channel_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_ark_channel_proto_rawDesc), len(file_ark_channel_proto_rawDesc)), + NumEnums: 1, + NumMessages: 61, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_ark_channel_proto_goTypes, + DependencyIndexes: file_ark_channel_proto_depIdxs, + EnumInfos: file_ark_channel_proto_enumTypes, + MessageInfos: file_ark_channel_proto_msgTypes, + }.Build() + File_ark_channel_proto = out.File + file_ark_channel_proto_goTypes = nil + file_ark_channel_proto_depIdxs = nil +} diff --git a/rpc/arkchannelrpc/ark_channel_grpc.pb.go b/rpc/arkchannelrpc/ark_channel_grpc.pb.go new file mode 100644 index 000000000..f7ec344fb --- /dev/null +++ b/rpc/arkchannelrpc/ark_channel_grpc.pb.go @@ -0,0 +1,339 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.5.1 +// - protoc v3.21.12 +// source: ark_channel.proto + +package arkchannelrpc + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + ArkChannelService_PromoteVTXO_FullMethodName = "/arkchannelrpc.ArkChannelService/PromoteVTXO" + ArkChannelService_PayLightningInvoice_FullMethodName = "/arkchannelrpc.ArkChannelService/PayLightningInvoice" + ArkChannelService_MaterializeAndForceClose_FullMethodName = "/arkchannelrpc.ArkChannelService/MaterializeAndForceClose" + ArkChannelService_RefreshChannel_FullMethodName = "/arkchannelrpc.ArkChannelService/RefreshChannel" + ArkChannelService_GetChannel_FullMethodName = "/arkchannelrpc.ArkChannelService/GetChannel" + ArkChannelService_ListChannels_FullMethodName = "/arkchannelrpc.ArkChannelService/ListChannels" +) + +// ArkChannelServiceClient is the client API for ArkChannelService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// ArkChannelService is the local Wavelength control surface for channels +// backed by unpublished Ark transactions. +type ArkChannelServiceClient interface { + // PromoteVTXO turns existing wallet liquidity into an active OOR-backed + // channel. The daemon derives every protocol parameter from amount_sat. + PromoteVTXO(ctx context.Context, in *PromoteVTXORequest, opts ...grpc.CallOption) (*PromoteVTXOResponse, error) + // PayLightningInvoice atomically holds the private leg, asks the hub to + // dispatch the public invoice, and settles with the public preimage. + PayLightningInvoice(ctx context.Context, in *PayLightningInvoiceRequest, opts ...grpc.CallOption) (*PayLightningInvoiceResponse, error) + // MaterializeAndForceClose publishes the Ark ancestry, exact channel + // backing, and lnd's latest commitment transaction. + MaterializeAndForceClose(ctx context.Context, in *MaterializeAndForceCloseRequest, opts ...grpc.CallOption) (*MaterializeAndForceCloseResponse, error) + // RefreshChannel settles one clean channel into ordinary replacement + // VTXOs without materializing its Lightning channel point. + RefreshChannel(ctx context.Context, in *RefreshChannelRequest, opts ...grpc.CallOption) (*RefreshChannelResponse, error) + // GetChannel returns the durable Ark lifecycle state for one channel. + GetChannel(ctx context.Context, in *GetChannelRequest, opts ...grpc.CallOption) (*GetChannelResponse, error) + // ListChannels returns every channel that still needs recovery, + // observation, or operator action. + ListChannels(ctx context.Context, in *ListChannelsRequest, opts ...grpc.CallOption) (*ListChannelsResponse, error) +} + +type arkChannelServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewArkChannelServiceClient(cc grpc.ClientConnInterface) ArkChannelServiceClient { + return &arkChannelServiceClient{cc} +} + +func (c *arkChannelServiceClient) PromoteVTXO(ctx context.Context, in *PromoteVTXORequest, opts ...grpc.CallOption) (*PromoteVTXOResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(PromoteVTXOResponse) + err := c.cc.Invoke(ctx, ArkChannelService_PromoteVTXO_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *arkChannelServiceClient) PayLightningInvoice(ctx context.Context, in *PayLightningInvoiceRequest, opts ...grpc.CallOption) (*PayLightningInvoiceResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(PayLightningInvoiceResponse) + err := c.cc.Invoke(ctx, ArkChannelService_PayLightningInvoice_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *arkChannelServiceClient) MaterializeAndForceClose(ctx context.Context, in *MaterializeAndForceCloseRequest, opts ...grpc.CallOption) (*MaterializeAndForceCloseResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(MaterializeAndForceCloseResponse) + err := c.cc.Invoke(ctx, ArkChannelService_MaterializeAndForceClose_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *arkChannelServiceClient) RefreshChannel(ctx context.Context, in *RefreshChannelRequest, opts ...grpc.CallOption) (*RefreshChannelResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(RefreshChannelResponse) + err := c.cc.Invoke(ctx, ArkChannelService_RefreshChannel_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *arkChannelServiceClient) GetChannel(ctx context.Context, in *GetChannelRequest, opts ...grpc.CallOption) (*GetChannelResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetChannelResponse) + err := c.cc.Invoke(ctx, ArkChannelService_GetChannel_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *arkChannelServiceClient) ListChannels(ctx context.Context, in *ListChannelsRequest, opts ...grpc.CallOption) (*ListChannelsResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ListChannelsResponse) + err := c.cc.Invoke(ctx, ArkChannelService_ListChannels_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// ArkChannelServiceServer is the server API for ArkChannelService service. +// All implementations must embed UnimplementedArkChannelServiceServer +// for forward compatibility. +// +// ArkChannelService is the local Wavelength control surface for channels +// backed by unpublished Ark transactions. +type ArkChannelServiceServer interface { + // PromoteVTXO turns existing wallet liquidity into an active OOR-backed + // channel. The daemon derives every protocol parameter from amount_sat. + PromoteVTXO(context.Context, *PromoteVTXORequest) (*PromoteVTXOResponse, error) + // PayLightningInvoice atomically holds the private leg, asks the hub to + // dispatch the public invoice, and settles with the public preimage. + PayLightningInvoice(context.Context, *PayLightningInvoiceRequest) (*PayLightningInvoiceResponse, error) + // MaterializeAndForceClose publishes the Ark ancestry, exact channel + // backing, and lnd's latest commitment transaction. + MaterializeAndForceClose(context.Context, *MaterializeAndForceCloseRequest) (*MaterializeAndForceCloseResponse, error) + // RefreshChannel settles one clean channel into ordinary replacement + // VTXOs without materializing its Lightning channel point. + RefreshChannel(context.Context, *RefreshChannelRequest) (*RefreshChannelResponse, error) + // GetChannel returns the durable Ark lifecycle state for one channel. + GetChannel(context.Context, *GetChannelRequest) (*GetChannelResponse, error) + // ListChannels returns every channel that still needs recovery, + // observation, or operator action. + ListChannels(context.Context, *ListChannelsRequest) (*ListChannelsResponse, error) + mustEmbedUnimplementedArkChannelServiceServer() +} + +// UnimplementedArkChannelServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedArkChannelServiceServer struct{} + +func (UnimplementedArkChannelServiceServer) PromoteVTXO(context.Context, *PromoteVTXORequest) (*PromoteVTXOResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method PromoteVTXO not implemented") +} +func (UnimplementedArkChannelServiceServer) PayLightningInvoice(context.Context, *PayLightningInvoiceRequest) (*PayLightningInvoiceResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method PayLightningInvoice not implemented") +} +func (UnimplementedArkChannelServiceServer) MaterializeAndForceClose(context.Context, *MaterializeAndForceCloseRequest) (*MaterializeAndForceCloseResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method MaterializeAndForceClose not implemented") +} +func (UnimplementedArkChannelServiceServer) RefreshChannel(context.Context, *RefreshChannelRequest) (*RefreshChannelResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method RefreshChannel not implemented") +} +func (UnimplementedArkChannelServiceServer) GetChannel(context.Context, *GetChannelRequest) (*GetChannelResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetChannel not implemented") +} +func (UnimplementedArkChannelServiceServer) ListChannels(context.Context, *ListChannelsRequest) (*ListChannelsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ListChannels not implemented") +} +func (UnimplementedArkChannelServiceServer) mustEmbedUnimplementedArkChannelServiceServer() {} +func (UnimplementedArkChannelServiceServer) testEmbeddedByValue() {} + +// UnsafeArkChannelServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to ArkChannelServiceServer will +// result in compilation errors. +type UnsafeArkChannelServiceServer interface { + mustEmbedUnimplementedArkChannelServiceServer() +} + +func RegisterArkChannelServiceServer(s grpc.ServiceRegistrar, srv ArkChannelServiceServer) { + // If the following call pancis, it indicates UnimplementedArkChannelServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&ArkChannelService_ServiceDesc, srv) +} + +func _ArkChannelService_PromoteVTXO_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(PromoteVTXORequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ArkChannelServiceServer).PromoteVTXO(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ArkChannelService_PromoteVTXO_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ArkChannelServiceServer).PromoteVTXO(ctx, req.(*PromoteVTXORequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ArkChannelService_PayLightningInvoice_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(PayLightningInvoiceRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ArkChannelServiceServer).PayLightningInvoice(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ArkChannelService_PayLightningInvoice_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ArkChannelServiceServer).PayLightningInvoice(ctx, req.(*PayLightningInvoiceRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ArkChannelService_MaterializeAndForceClose_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MaterializeAndForceCloseRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ArkChannelServiceServer).MaterializeAndForceClose(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ArkChannelService_MaterializeAndForceClose_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ArkChannelServiceServer).MaterializeAndForceClose(ctx, req.(*MaterializeAndForceCloseRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ArkChannelService_RefreshChannel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RefreshChannelRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ArkChannelServiceServer).RefreshChannel(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ArkChannelService_RefreshChannel_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ArkChannelServiceServer).RefreshChannel(ctx, req.(*RefreshChannelRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ArkChannelService_GetChannel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetChannelRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ArkChannelServiceServer).GetChannel(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ArkChannelService_GetChannel_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ArkChannelServiceServer).GetChannel(ctx, req.(*GetChannelRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ArkChannelService_ListChannels_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ListChannelsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ArkChannelServiceServer).ListChannels(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ArkChannelService_ListChannels_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ArkChannelServiceServer).ListChannels(ctx, req.(*ListChannelsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// ArkChannelService_ServiceDesc is the grpc.ServiceDesc for ArkChannelService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var ArkChannelService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "arkchannelrpc.ArkChannelService", + HandlerType: (*ArkChannelServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "PromoteVTXO", + Handler: _ArkChannelService_PromoteVTXO_Handler, + }, + { + MethodName: "PayLightningInvoice", + Handler: _ArkChannelService_PayLightningInvoice_Handler, + }, + { + MethodName: "MaterializeAndForceClose", + Handler: _ArkChannelService_MaterializeAndForceClose_Handler, + }, + { + MethodName: "RefreshChannel", + Handler: _ArkChannelService_RefreshChannel_Handler, + }, + { + MethodName: "GetChannel", + Handler: _ArkChannelService_GetChannel_Handler, + }, + { + MethodName: "ListChannels", + Handler: _ArkChannelService_ListChannels_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "ark_channel.proto", +} diff --git a/rpc/arkchannelrpc/ark_channel_peer.pb.go b/rpc/arkchannelrpc/ark_channel_peer.pb.go new file mode 100644 index 000000000..cfcdd7343 --- /dev/null +++ b/rpc/arkchannelrpc/ark_channel_peer.pb.go @@ -0,0 +1,156 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc v3.21.12 +// source: ark_channel_peer.proto + +package arkchannelrpc + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +var File_ark_channel_peer_proto protoreflect.FileDescriptor + +const file_ark_channel_peer_proto_rawDesc = "" + + "\n" + + "\x16ark_channel_peer.proto\x12\rarkchannelrpc\x1a\x11ark_channel.proto2\xf9\x04\n" + + "\x15ArkChannelPeerService\x12{\n" + + "\x18GetCooperativeCloseTerms\x12..arkchannelrpc.GetCooperativeCloseTermsRequest\x1a/.arkchannelrpc.GetCooperativeCloseTermsResponse\x12{\n" + + "\x18CompleteCooperativeClose\x12..arkchannelrpc.CompleteCooperativeCloseRequest\x1a/.arkchannelrpc.CompleteCooperativeCloseResponse\x12x\n" + + "\x17ConfirmCooperativeClose\x12-.arkchannelrpc.ConfirmCooperativeCloseRequest\x1a..arkchannelrpc.ConfirmCooperativeCloseResponse\x12x\n" + + "\x17PublishCooperativeClose\x12-.arkchannelrpc.PublishCooperativeCloseRequest\x1a..arkchannelrpc.PublishCooperativeCloseResponse\x12r\n" + + "\x15AbortCooperativeClose\x12+.arkchannelrpc.AbortCooperativeCloseRequest\x1a,.arkchannelrpc.AbortCooperativeCloseResponse2\xce\v\n" + + "\x1cArkChannelFundingPeerService\x12T\n" + + "\vGetPeerInfo\x12!.arkchannelrpc.GetPeerInfoRequest\x1a\".arkchannelrpc.GetPeerInfoResponse\x12f\n" + + "\x11RegisterPromotion\x12'.arkchannelrpc.RegisterPromotionRequest\x1a(.arkchannelrpc.RegisterPromotionResponse\x12f\n" + + "\x11GetFundingChannel\x12'.arkchannelrpc.GetFundingChannelRequest\x1a(.arkchannelrpc.GetFundingChannelResponse\x12`\n" + + "\x0fBindPreparedOOR\x12%.arkchannelrpc.BindPreparedOORRequest\x1a&.arkchannelrpc.BindPreparedOORResponse\x12T\n" + + "\vSignBacking\x12!.arkchannelrpc.SignBackingRequest\x1a\".arkchannelrpc.SignBackingResponse\x12]\n" + + "\x0eInstallBacking\x12$.arkchannelrpc.InstallBackingRequest\x1a%.arkchannelrpc.InstallBackingResponse\x12u\n" + + "\x16InstallRecoveryPackage\x12,.arkchannelrpc.InstallRecoveryPackageRequest\x1a-.arkchannelrpc.InstallRecoveryPackageResponse\x12]\n" + + "\x10FundingFinalized\x12#.arkchannelrpc.FundingStatusRequest\x1a$.arkchannelrpc.FundingStatusResponse\x12Z\n" + + "\rChannelActive\x12#.arkchannelrpc.FundingStatusRequest\x1a$.arkchannelrpc.FundingStatusResponse\x12f\n" + + "\x11ApplyChannelEvent\x12'.arkchannelrpc.ApplyChannelEventRequest\x1a(.arkchannelrpc.ApplyChannelEventResponse\x12u\n" + + "\x16PrepareOutgoingPayment\x12,.arkchannelrpc.PrepareOutgoingPaymentRequest\x1a-.arkchannelrpc.PrepareOutgoingPaymentResponse\x12r\n" + + "\x15CancelOutgoingPayment\x12+.arkchannelrpc.CancelOutgoingPaymentRequest\x1a,.arkchannelrpc.CancelOutgoingPaymentResponse\x12x\n" + + "\x17RegisterIncomingPayment\x12-.arkchannelrpc.RegisterIncomingPaymentRequest\x1a..arkchannelrpc.RegisterIncomingPaymentResponse\x12r\n" + + "\x15CancelIncomingPayment\x12+.arkchannelrpc.CancelIncomingPaymentRequest\x1a,.arkchannelrpc.CancelIncomingPaymentResponseB7Z5github.com/lightninglabs/wavelength/rpc/arkchannelrpcb\x06proto3" + +var file_ark_channel_peer_proto_goTypes = []any{ + (*GetCooperativeCloseTermsRequest)(nil), // 0: arkchannelrpc.GetCooperativeCloseTermsRequest + (*CompleteCooperativeCloseRequest)(nil), // 1: arkchannelrpc.CompleteCooperativeCloseRequest + (*ConfirmCooperativeCloseRequest)(nil), // 2: arkchannelrpc.ConfirmCooperativeCloseRequest + (*PublishCooperativeCloseRequest)(nil), // 3: arkchannelrpc.PublishCooperativeCloseRequest + (*AbortCooperativeCloseRequest)(nil), // 4: arkchannelrpc.AbortCooperativeCloseRequest + (*GetPeerInfoRequest)(nil), // 5: arkchannelrpc.GetPeerInfoRequest + (*RegisterPromotionRequest)(nil), // 6: arkchannelrpc.RegisterPromotionRequest + (*GetFundingChannelRequest)(nil), // 7: arkchannelrpc.GetFundingChannelRequest + (*BindPreparedOORRequest)(nil), // 8: arkchannelrpc.BindPreparedOORRequest + (*SignBackingRequest)(nil), // 9: arkchannelrpc.SignBackingRequest + (*InstallBackingRequest)(nil), // 10: arkchannelrpc.InstallBackingRequest + (*InstallRecoveryPackageRequest)(nil), // 11: arkchannelrpc.InstallRecoveryPackageRequest + (*FundingStatusRequest)(nil), // 12: arkchannelrpc.FundingStatusRequest + (*ApplyChannelEventRequest)(nil), // 13: arkchannelrpc.ApplyChannelEventRequest + (*PrepareOutgoingPaymentRequest)(nil), // 14: arkchannelrpc.PrepareOutgoingPaymentRequest + (*CancelOutgoingPaymentRequest)(nil), // 15: arkchannelrpc.CancelOutgoingPaymentRequest + (*RegisterIncomingPaymentRequest)(nil), // 16: arkchannelrpc.RegisterIncomingPaymentRequest + (*CancelIncomingPaymentRequest)(nil), // 17: arkchannelrpc.CancelIncomingPaymentRequest + (*GetCooperativeCloseTermsResponse)(nil), // 18: arkchannelrpc.GetCooperativeCloseTermsResponse + (*CompleteCooperativeCloseResponse)(nil), // 19: arkchannelrpc.CompleteCooperativeCloseResponse + (*ConfirmCooperativeCloseResponse)(nil), // 20: arkchannelrpc.ConfirmCooperativeCloseResponse + (*PublishCooperativeCloseResponse)(nil), // 21: arkchannelrpc.PublishCooperativeCloseResponse + (*AbortCooperativeCloseResponse)(nil), // 22: arkchannelrpc.AbortCooperativeCloseResponse + (*GetPeerInfoResponse)(nil), // 23: arkchannelrpc.GetPeerInfoResponse + (*RegisterPromotionResponse)(nil), // 24: arkchannelrpc.RegisterPromotionResponse + (*GetFundingChannelResponse)(nil), // 25: arkchannelrpc.GetFundingChannelResponse + (*BindPreparedOORResponse)(nil), // 26: arkchannelrpc.BindPreparedOORResponse + (*SignBackingResponse)(nil), // 27: arkchannelrpc.SignBackingResponse + (*InstallBackingResponse)(nil), // 28: arkchannelrpc.InstallBackingResponse + (*InstallRecoveryPackageResponse)(nil), // 29: arkchannelrpc.InstallRecoveryPackageResponse + (*FundingStatusResponse)(nil), // 30: arkchannelrpc.FundingStatusResponse + (*ApplyChannelEventResponse)(nil), // 31: arkchannelrpc.ApplyChannelEventResponse + (*PrepareOutgoingPaymentResponse)(nil), // 32: arkchannelrpc.PrepareOutgoingPaymentResponse + (*CancelOutgoingPaymentResponse)(nil), // 33: arkchannelrpc.CancelOutgoingPaymentResponse + (*RegisterIncomingPaymentResponse)(nil), // 34: arkchannelrpc.RegisterIncomingPaymentResponse + (*CancelIncomingPaymentResponse)(nil), // 35: arkchannelrpc.CancelIncomingPaymentResponse +} +var file_ark_channel_peer_proto_depIdxs = []int32{ + 0, // 0: arkchannelrpc.ArkChannelPeerService.GetCooperativeCloseTerms:input_type -> arkchannelrpc.GetCooperativeCloseTermsRequest + 1, // 1: arkchannelrpc.ArkChannelPeerService.CompleteCooperativeClose:input_type -> arkchannelrpc.CompleteCooperativeCloseRequest + 2, // 2: arkchannelrpc.ArkChannelPeerService.ConfirmCooperativeClose:input_type -> arkchannelrpc.ConfirmCooperativeCloseRequest + 3, // 3: arkchannelrpc.ArkChannelPeerService.PublishCooperativeClose:input_type -> arkchannelrpc.PublishCooperativeCloseRequest + 4, // 4: arkchannelrpc.ArkChannelPeerService.AbortCooperativeClose:input_type -> arkchannelrpc.AbortCooperativeCloseRequest + 5, // 5: arkchannelrpc.ArkChannelFundingPeerService.GetPeerInfo:input_type -> arkchannelrpc.GetPeerInfoRequest + 6, // 6: arkchannelrpc.ArkChannelFundingPeerService.RegisterPromotion:input_type -> arkchannelrpc.RegisterPromotionRequest + 7, // 7: arkchannelrpc.ArkChannelFundingPeerService.GetFundingChannel:input_type -> arkchannelrpc.GetFundingChannelRequest + 8, // 8: arkchannelrpc.ArkChannelFundingPeerService.BindPreparedOOR:input_type -> arkchannelrpc.BindPreparedOORRequest + 9, // 9: arkchannelrpc.ArkChannelFundingPeerService.SignBacking:input_type -> arkchannelrpc.SignBackingRequest + 10, // 10: arkchannelrpc.ArkChannelFundingPeerService.InstallBacking:input_type -> arkchannelrpc.InstallBackingRequest + 11, // 11: arkchannelrpc.ArkChannelFundingPeerService.InstallRecoveryPackage:input_type -> arkchannelrpc.InstallRecoveryPackageRequest + 12, // 12: arkchannelrpc.ArkChannelFundingPeerService.FundingFinalized:input_type -> arkchannelrpc.FundingStatusRequest + 12, // 13: arkchannelrpc.ArkChannelFundingPeerService.ChannelActive:input_type -> arkchannelrpc.FundingStatusRequest + 13, // 14: arkchannelrpc.ArkChannelFundingPeerService.ApplyChannelEvent:input_type -> arkchannelrpc.ApplyChannelEventRequest + 14, // 15: arkchannelrpc.ArkChannelFundingPeerService.PrepareOutgoingPayment:input_type -> arkchannelrpc.PrepareOutgoingPaymentRequest + 15, // 16: arkchannelrpc.ArkChannelFundingPeerService.CancelOutgoingPayment:input_type -> arkchannelrpc.CancelOutgoingPaymentRequest + 16, // 17: arkchannelrpc.ArkChannelFundingPeerService.RegisterIncomingPayment:input_type -> arkchannelrpc.RegisterIncomingPaymentRequest + 17, // 18: arkchannelrpc.ArkChannelFundingPeerService.CancelIncomingPayment:input_type -> arkchannelrpc.CancelIncomingPaymentRequest + 18, // 19: arkchannelrpc.ArkChannelPeerService.GetCooperativeCloseTerms:output_type -> arkchannelrpc.GetCooperativeCloseTermsResponse + 19, // 20: arkchannelrpc.ArkChannelPeerService.CompleteCooperativeClose:output_type -> arkchannelrpc.CompleteCooperativeCloseResponse + 20, // 21: arkchannelrpc.ArkChannelPeerService.ConfirmCooperativeClose:output_type -> arkchannelrpc.ConfirmCooperativeCloseResponse + 21, // 22: arkchannelrpc.ArkChannelPeerService.PublishCooperativeClose:output_type -> arkchannelrpc.PublishCooperativeCloseResponse + 22, // 23: arkchannelrpc.ArkChannelPeerService.AbortCooperativeClose:output_type -> arkchannelrpc.AbortCooperativeCloseResponse + 23, // 24: arkchannelrpc.ArkChannelFundingPeerService.GetPeerInfo:output_type -> arkchannelrpc.GetPeerInfoResponse + 24, // 25: arkchannelrpc.ArkChannelFundingPeerService.RegisterPromotion:output_type -> arkchannelrpc.RegisterPromotionResponse + 25, // 26: arkchannelrpc.ArkChannelFundingPeerService.GetFundingChannel:output_type -> arkchannelrpc.GetFundingChannelResponse + 26, // 27: arkchannelrpc.ArkChannelFundingPeerService.BindPreparedOOR:output_type -> arkchannelrpc.BindPreparedOORResponse + 27, // 28: arkchannelrpc.ArkChannelFundingPeerService.SignBacking:output_type -> arkchannelrpc.SignBackingResponse + 28, // 29: arkchannelrpc.ArkChannelFundingPeerService.InstallBacking:output_type -> arkchannelrpc.InstallBackingResponse + 29, // 30: arkchannelrpc.ArkChannelFundingPeerService.InstallRecoveryPackage:output_type -> arkchannelrpc.InstallRecoveryPackageResponse + 30, // 31: arkchannelrpc.ArkChannelFundingPeerService.FundingFinalized:output_type -> arkchannelrpc.FundingStatusResponse + 30, // 32: arkchannelrpc.ArkChannelFundingPeerService.ChannelActive:output_type -> arkchannelrpc.FundingStatusResponse + 31, // 33: arkchannelrpc.ArkChannelFundingPeerService.ApplyChannelEvent:output_type -> arkchannelrpc.ApplyChannelEventResponse + 32, // 34: arkchannelrpc.ArkChannelFundingPeerService.PrepareOutgoingPayment:output_type -> arkchannelrpc.PrepareOutgoingPaymentResponse + 33, // 35: arkchannelrpc.ArkChannelFundingPeerService.CancelOutgoingPayment:output_type -> arkchannelrpc.CancelOutgoingPaymentResponse + 34, // 36: arkchannelrpc.ArkChannelFundingPeerService.RegisterIncomingPayment:output_type -> arkchannelrpc.RegisterIncomingPaymentResponse + 35, // 37: arkchannelrpc.ArkChannelFundingPeerService.CancelIncomingPayment:output_type -> arkchannelrpc.CancelIncomingPaymentResponse + 19, // [19:38] is the sub-list for method output_type + 0, // [0:19] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_ark_channel_peer_proto_init() } +func file_ark_channel_peer_proto_init() { + if File_ark_channel_peer_proto != nil { + return + } + file_ark_channel_proto_init() + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_ark_channel_peer_proto_rawDesc), len(file_ark_channel_peer_proto_rawDesc)), + NumEnums: 0, + NumMessages: 0, + NumExtensions: 0, + NumServices: 2, + }, + GoTypes: file_ark_channel_peer_proto_goTypes, + DependencyIndexes: file_ark_channel_peer_proto_depIdxs, + }.Build() + File_ark_channel_peer_proto = out.File + file_ark_channel_peer_proto_goTypes = nil + file_ark_channel_peer_proto_depIdxs = nil +} diff --git a/rpc/arkchannelrpc/ark_channel_peer_mailboxrpc.pb.go b/rpc/arkchannelrpc/ark_channel_peer_mailboxrpc.pb.go new file mode 100644 index 000000000..1c6da60f9 --- /dev/null +++ b/rpc/arkchannelrpc/ark_channel_peer_mailboxrpc.pb.go @@ -0,0 +1,717 @@ +// Code generated by protoc-gen-mailboxrpc. DO NOT EDIT. + +package arkchannelrpc + +import ( + context "context" + fmt "fmt" + rpc "github.com/lightninglabs/wavelength/mailbox/rpc" + proto "google.golang.org/protobuf/proto" +) + +// ArkChannelPeerServiceMailboxClient is a typed mailbox RPC client for ArkChannelPeerService. +type ArkChannelPeerServiceMailboxClient struct { + // C is the underlying RPC-over-mailbox runtime client. + C rpc.RPCClient +} + +// NewArkChannelPeerServiceMailboxClient creates a typed mailbox client. +func NewArkChannelPeerServiceMailboxClient(c rpc.RPCClient) *ArkChannelPeerServiceMailboxClient { + return &ArkChannelPeerServiceMailboxClient{ + C: c, + } +} + +// ArkChannelPeerServiceMailboxServer is the mailbox server interface for ArkChannelPeerService. +type ArkChannelPeerServiceMailboxServer interface { + // GetCooperativeCloseTerms handles GetCooperativeCloseTerms. + GetCooperativeCloseTerms(ctx context.Context, req *GetCooperativeCloseTermsRequest) (*GetCooperativeCloseTermsResponse, error) + // CompleteCooperativeClose handles CompleteCooperativeClose. + CompleteCooperativeClose(ctx context.Context, req *CompleteCooperativeCloseRequest) (*CompleteCooperativeCloseResponse, error) + // ConfirmCooperativeClose handles ConfirmCooperativeClose. + ConfirmCooperativeClose(ctx context.Context, req *ConfirmCooperativeCloseRequest) (*ConfirmCooperativeCloseResponse, error) + // PublishCooperativeClose handles PublishCooperativeClose. + PublishCooperativeClose(ctx context.Context, req *PublishCooperativeCloseRequest) (*PublishCooperativeCloseResponse, error) + // AbortCooperativeClose handles AbortCooperativeClose. + AbortCooperativeClose(ctx context.Context, req *AbortCooperativeCloseRequest) (*AbortCooperativeCloseResponse, error) +} + +// RegisterArkChannelPeerServiceMailboxServer registers handlers for ArkChannelPeerService. +func RegisterArkChannelPeerServiceMailboxServer(r rpc.Router, impl ArkChannelPeerServiceMailboxServer) { + r.Handle("arkchannelrpc.ArkChannelPeerService", "GetCooperativeCloseTerms", func() proto.Message { + return &GetCooperativeCloseTermsRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*GetCooperativeCloseTermsRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.GetCooperativeCloseTerms(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelPeerService", "CompleteCooperativeClose", func() proto.Message { + return &CompleteCooperativeCloseRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*CompleteCooperativeCloseRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.CompleteCooperativeClose(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelPeerService", "ConfirmCooperativeClose", func() proto.Message { + return &ConfirmCooperativeCloseRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*ConfirmCooperativeCloseRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.ConfirmCooperativeClose(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelPeerService", "PublishCooperativeClose", func() proto.Message { + return &PublishCooperativeCloseRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*PublishCooperativeCloseRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.PublishCooperativeClose(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelPeerService", "AbortCooperativeClose", func() proto.Message { + return &AbortCooperativeCloseRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*AbortCooperativeCloseRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.AbortCooperativeClose(ctx, req) + }) +} + +// GetCooperativeCloseTerms calls the GetCooperativeCloseTerms RPC. +func (c *ArkChannelPeerServiceMailboxClient) GetCooperativeCloseTerms(ctx context.Context, req *GetCooperativeCloseTermsRequest, opts ...rpc.RPCOptions) (*GetCooperativeCloseTermsResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelPeerService", + Method: "GetCooperativeCloseTerms", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(GetCooperativeCloseTermsResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// CompleteCooperativeClose calls the CompleteCooperativeClose RPC. +func (c *ArkChannelPeerServiceMailboxClient) CompleteCooperativeClose(ctx context.Context, req *CompleteCooperativeCloseRequest, opts ...rpc.RPCOptions) (*CompleteCooperativeCloseResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelPeerService", + Method: "CompleteCooperativeClose", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(CompleteCooperativeCloseResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// ConfirmCooperativeClose calls the ConfirmCooperativeClose RPC. +func (c *ArkChannelPeerServiceMailboxClient) ConfirmCooperativeClose(ctx context.Context, req *ConfirmCooperativeCloseRequest, opts ...rpc.RPCOptions) (*ConfirmCooperativeCloseResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelPeerService", + Method: "ConfirmCooperativeClose", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(ConfirmCooperativeCloseResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// PublishCooperativeClose calls the PublishCooperativeClose RPC. +func (c *ArkChannelPeerServiceMailboxClient) PublishCooperativeClose(ctx context.Context, req *PublishCooperativeCloseRequest, opts ...rpc.RPCOptions) (*PublishCooperativeCloseResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelPeerService", + Method: "PublishCooperativeClose", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(PublishCooperativeCloseResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// AbortCooperativeClose calls the AbortCooperativeClose RPC. +func (c *ArkChannelPeerServiceMailboxClient) AbortCooperativeClose(ctx context.Context, req *AbortCooperativeCloseRequest, opts ...rpc.RPCOptions) (*AbortCooperativeCloseResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelPeerService", + Method: "AbortCooperativeClose", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(AbortCooperativeCloseResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// ArkChannelFundingPeerServiceMailboxClient is a typed mailbox RPC client for ArkChannelFundingPeerService. +type ArkChannelFundingPeerServiceMailboxClient struct { + // C is the underlying RPC-over-mailbox runtime client. + C rpc.RPCClient +} + +// NewArkChannelFundingPeerServiceMailboxClient creates a typed mailbox client. +func NewArkChannelFundingPeerServiceMailboxClient(c rpc.RPCClient) *ArkChannelFundingPeerServiceMailboxClient { + return &ArkChannelFundingPeerServiceMailboxClient{ + C: c, + } +} + +// ArkChannelFundingPeerServiceMailboxServer is the mailbox server interface for ArkChannelFundingPeerService. +type ArkChannelFundingPeerServiceMailboxServer interface { + // GetPeerInfo handles GetPeerInfo. + GetPeerInfo(ctx context.Context, req *GetPeerInfoRequest) (*GetPeerInfoResponse, error) + // RegisterPromotion handles RegisterPromotion. + RegisterPromotion(ctx context.Context, req *RegisterPromotionRequest) (*RegisterPromotionResponse, error) + // GetFundingChannel handles GetFundingChannel. + GetFundingChannel(ctx context.Context, req *GetFundingChannelRequest) (*GetFundingChannelResponse, error) + // BindPreparedOOR handles BindPreparedOOR. + BindPreparedOOR(ctx context.Context, req *BindPreparedOORRequest) (*BindPreparedOORResponse, error) + // SignBacking handles SignBacking. + SignBacking(ctx context.Context, req *SignBackingRequest) (*SignBackingResponse, error) + // InstallBacking handles InstallBacking. + InstallBacking(ctx context.Context, req *InstallBackingRequest) (*InstallBackingResponse, error) + // InstallRecoveryPackage handles InstallRecoveryPackage. + InstallRecoveryPackage(ctx context.Context, req *InstallRecoveryPackageRequest) (*InstallRecoveryPackageResponse, error) + // FundingFinalized handles FundingFinalized. + FundingFinalized(ctx context.Context, req *FundingStatusRequest) (*FundingStatusResponse, error) + // ChannelActive handles ChannelActive. + ChannelActive(ctx context.Context, req *FundingStatusRequest) (*FundingStatusResponse, error) + // ApplyChannelEvent handles ApplyChannelEvent. + ApplyChannelEvent(ctx context.Context, req *ApplyChannelEventRequest) (*ApplyChannelEventResponse, error) + // PrepareOutgoingPayment handles PrepareOutgoingPayment. + PrepareOutgoingPayment(ctx context.Context, req *PrepareOutgoingPaymentRequest) (*PrepareOutgoingPaymentResponse, error) + // CancelOutgoingPayment handles CancelOutgoingPayment. + CancelOutgoingPayment(ctx context.Context, req *CancelOutgoingPaymentRequest) (*CancelOutgoingPaymentResponse, error) + // RegisterIncomingPayment handles RegisterIncomingPayment. + RegisterIncomingPayment(ctx context.Context, req *RegisterIncomingPaymentRequest) (*RegisterIncomingPaymentResponse, error) + // CancelIncomingPayment handles CancelIncomingPayment. + CancelIncomingPayment(ctx context.Context, req *CancelIncomingPaymentRequest) (*CancelIncomingPaymentResponse, error) +} + +// RegisterArkChannelFundingPeerServiceMailboxServer registers handlers for ArkChannelFundingPeerService. +func RegisterArkChannelFundingPeerServiceMailboxServer(r rpc.Router, impl ArkChannelFundingPeerServiceMailboxServer) { + r.Handle("arkchannelrpc.ArkChannelFundingPeerService", "GetPeerInfo", func() proto.Message { + return &GetPeerInfoRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*GetPeerInfoRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.GetPeerInfo(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelFundingPeerService", "RegisterPromotion", func() proto.Message { + return &RegisterPromotionRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*RegisterPromotionRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.RegisterPromotion(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelFundingPeerService", "GetFundingChannel", func() proto.Message { + return &GetFundingChannelRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*GetFundingChannelRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.GetFundingChannel(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelFundingPeerService", "BindPreparedOOR", func() proto.Message { + return &BindPreparedOORRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*BindPreparedOORRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.BindPreparedOOR(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelFundingPeerService", "SignBacking", func() proto.Message { + return &SignBackingRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*SignBackingRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.SignBacking(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelFundingPeerService", "InstallBacking", func() proto.Message { + return &InstallBackingRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*InstallBackingRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.InstallBacking(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelFundingPeerService", "InstallRecoveryPackage", func() proto.Message { + return &InstallRecoveryPackageRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*InstallRecoveryPackageRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.InstallRecoveryPackage(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelFundingPeerService", "FundingFinalized", func() proto.Message { + return &FundingStatusRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*FundingStatusRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.FundingFinalized(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelFundingPeerService", "ChannelActive", func() proto.Message { + return &FundingStatusRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*FundingStatusRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.ChannelActive(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelFundingPeerService", "ApplyChannelEvent", func() proto.Message { + return &ApplyChannelEventRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*ApplyChannelEventRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.ApplyChannelEvent(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelFundingPeerService", "PrepareOutgoingPayment", func() proto.Message { + return &PrepareOutgoingPaymentRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*PrepareOutgoingPaymentRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.PrepareOutgoingPayment(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelFundingPeerService", "CancelOutgoingPayment", func() proto.Message { + return &CancelOutgoingPaymentRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*CancelOutgoingPaymentRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.CancelOutgoingPayment(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelFundingPeerService", "RegisterIncomingPayment", func() proto.Message { + return &RegisterIncomingPaymentRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*RegisterIncomingPaymentRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.RegisterIncomingPayment(ctx, req) + }) + r.Handle("arkchannelrpc.ArkChannelFundingPeerService", "CancelIncomingPayment", func() proto.Message { + return &CancelIncomingPaymentRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*CancelIncomingPaymentRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.CancelIncomingPayment(ctx, req) + }) +} + +// GetPeerInfo calls the GetPeerInfo RPC. +func (c *ArkChannelFundingPeerServiceMailboxClient) GetPeerInfo(ctx context.Context, req *GetPeerInfoRequest, opts ...rpc.RPCOptions) (*GetPeerInfoResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelFundingPeerService", + Method: "GetPeerInfo", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(GetPeerInfoResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// RegisterPromotion calls the RegisterPromotion RPC. +func (c *ArkChannelFundingPeerServiceMailboxClient) RegisterPromotion(ctx context.Context, req *RegisterPromotionRequest, opts ...rpc.RPCOptions) (*RegisterPromotionResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelFundingPeerService", + Method: "RegisterPromotion", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(RegisterPromotionResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// GetFundingChannel calls the GetFundingChannel RPC. +func (c *ArkChannelFundingPeerServiceMailboxClient) GetFundingChannel(ctx context.Context, req *GetFundingChannelRequest, opts ...rpc.RPCOptions) (*GetFundingChannelResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelFundingPeerService", + Method: "GetFundingChannel", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(GetFundingChannelResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// BindPreparedOOR calls the BindPreparedOOR RPC. +func (c *ArkChannelFundingPeerServiceMailboxClient) BindPreparedOOR(ctx context.Context, req *BindPreparedOORRequest, opts ...rpc.RPCOptions) (*BindPreparedOORResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelFundingPeerService", + Method: "BindPreparedOOR", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(BindPreparedOORResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// SignBacking calls the SignBacking RPC. +func (c *ArkChannelFundingPeerServiceMailboxClient) SignBacking(ctx context.Context, req *SignBackingRequest, opts ...rpc.RPCOptions) (*SignBackingResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelFundingPeerService", + Method: "SignBacking", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(SignBackingResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// InstallBacking calls the InstallBacking RPC. +func (c *ArkChannelFundingPeerServiceMailboxClient) InstallBacking(ctx context.Context, req *InstallBackingRequest, opts ...rpc.RPCOptions) (*InstallBackingResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelFundingPeerService", + Method: "InstallBacking", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(InstallBackingResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// InstallRecoveryPackage calls the InstallRecoveryPackage RPC. +func (c *ArkChannelFundingPeerServiceMailboxClient) InstallRecoveryPackage(ctx context.Context, req *InstallRecoveryPackageRequest, opts ...rpc.RPCOptions) (*InstallRecoveryPackageResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelFundingPeerService", + Method: "InstallRecoveryPackage", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(InstallRecoveryPackageResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// FundingFinalized calls the FundingFinalized RPC. +func (c *ArkChannelFundingPeerServiceMailboxClient) FundingFinalized(ctx context.Context, req *FundingStatusRequest, opts ...rpc.RPCOptions) (*FundingStatusResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelFundingPeerService", + Method: "FundingFinalized", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(FundingStatusResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// ChannelActive calls the ChannelActive RPC. +func (c *ArkChannelFundingPeerServiceMailboxClient) ChannelActive(ctx context.Context, req *FundingStatusRequest, opts ...rpc.RPCOptions) (*FundingStatusResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelFundingPeerService", + Method: "ChannelActive", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(FundingStatusResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// ApplyChannelEvent calls the ApplyChannelEvent RPC. +func (c *ArkChannelFundingPeerServiceMailboxClient) ApplyChannelEvent(ctx context.Context, req *ApplyChannelEventRequest, opts ...rpc.RPCOptions) (*ApplyChannelEventResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelFundingPeerService", + Method: "ApplyChannelEvent", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(ApplyChannelEventResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// PrepareOutgoingPayment calls the PrepareOutgoingPayment RPC. +func (c *ArkChannelFundingPeerServiceMailboxClient) PrepareOutgoingPayment(ctx context.Context, req *PrepareOutgoingPaymentRequest, opts ...rpc.RPCOptions) (*PrepareOutgoingPaymentResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelFundingPeerService", + Method: "PrepareOutgoingPayment", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(PrepareOutgoingPaymentResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// CancelOutgoingPayment calls the CancelOutgoingPayment RPC. +func (c *ArkChannelFundingPeerServiceMailboxClient) CancelOutgoingPayment(ctx context.Context, req *CancelOutgoingPaymentRequest, opts ...rpc.RPCOptions) (*CancelOutgoingPaymentResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelFundingPeerService", + Method: "CancelOutgoingPayment", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(CancelOutgoingPaymentResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// RegisterIncomingPayment calls the RegisterIncomingPayment RPC. +func (c *ArkChannelFundingPeerServiceMailboxClient) RegisterIncomingPayment(ctx context.Context, req *RegisterIncomingPaymentRequest, opts ...rpc.RPCOptions) (*RegisterIncomingPaymentResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelFundingPeerService", + Method: "RegisterIncomingPayment", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(RegisterIncomingPaymentResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + +// CancelIncomingPayment calls the CancelIncomingPayment RPC. +func (c *ArkChannelFundingPeerServiceMailboxClient) CancelIncomingPayment(ctx context.Context, req *CancelIncomingPaymentRequest, opts ...rpc.RPCOptions) (*CancelIncomingPaymentResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "arkchannelrpc.ArkChannelFundingPeerService", + Method: "CancelIncomingPayment", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(CancelIncomingPaymentResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} diff --git a/rpc/arkchannelrpc/transport_test.go b/rpc/arkchannelrpc/transport_test.go new file mode 100644 index 000000000..2d3d82071 --- /dev/null +++ b/rpc/arkchannelrpc/transport_test.go @@ -0,0 +1,101 @@ +package arkchannelrpc + +import ( + "context" + "net" + "testing" + "time" + + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/grpc/test/bufconn" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/types/known/emptypb" +) + +// TestChannelTransportSurface rejects removed demo calls and keeps peer +// controls outside the generated local gRPC service. +func TestChannelTransportSurface(t *testing.T) { + t.Parallel() + require.Equal(t, 1, File_ark_channel_proto.Services().Len()) + require.Equal(t, 2, File_ark_channel_peer_proto.Services().Len()) + require.Nil( + t, + File_ark_channel_proto.Messages().ByName("FundingWireEnvelope"), + ) + for _, enum := range []protoreflect.Name{ + "FundingWireKind", + "FundingWireMethod", + } { + require.Nil(t, File_ark_channel_proto.Enums().ByName(enum)) + } + for _, method := range []string{"SendPayment", "ReceivePayment"} { + require.Nil( + t, + File_ark_channel_proto.Services().Get(0). + Methods().ByName(protoreflect.Name(method)), + ) + } + + funding := File_ark_channel_peer_proto.Services().ByName( + "ArkChannelFundingPeerService", + ) + for _, method := range []protoreflect.Name{ + "RegisterPromotion", "SignBacking", "InstallBacking", + "InstallRecoveryPackage", "ApplyChannelEvent", + } { + require.NotNil(t, funding.Methods().ByName(method)) + } + for _, method := range []string{ + "CreateInvoice", + "PayInvoice", + "RegisterReceiveIntent", + "FailReceiveIntent", + } { + require.Nil( + t, + funding.Methods().ByName(protoreflect.Name(method)), + ) + } + + listener := bufconn.Listen(1024 * 1024) + server := grpc.NewServer() + RegisterArkChannelServiceServer( + server, &UnimplementedArkChannelServiceServer{}, + ) + go func() { + _ = server.Serve(listener) + }() + t.Cleanup(server.Stop) + conn, err := grpc.NewClient( + "passthrough:///channel-transport-test", + grpc.WithContextDialer(func(ctx context.Context, _ string) ( + net.Conn, error) { + + return listener.DialContext(ctx) + }), + grpc.WithTransportCredentials( + insecure.NewCredentials(), + ), + ) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, conn.Close()) }) + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + for _, method := range []string{ + "/arkchannelrpc.ArkChannelService/SendPayment", + "/arkchannelrpc.ArkChannelService/ReceivePayment", + "/arkchannelrpc.ArkChannelFundingPeerService/CreateInvoice", + "/arkchannelrpc.ArkChannelFundingPeerService/PayInvoice", + "/arkchannelrpc.ArkChannelFundingPeerService/GetPeerInfo", + "/arkchannelrpc.ArkChannelPeerService/GetCooperativeCloseTerms", + } { + err := conn.Invoke( + ctx, method, &emptypb.Empty{}, &emptypb.Empty{}, + ) + require.Equal(t, codes.Unimplemented, status.Code(err), method) + } +} From e2d5d3e134ce4086e5bfaf5a220526bcee601dfa Mon Sep 17 00:00:00 2001 From: sputn1ck Date: Wed, 18 Nov 2026 18:44:26 +0100 Subject: [PATCH 3/7] arkchannel: Bind backing and cooperative payouts to channel terms Pin the source, signing parties and replacement allocation before allowing either peer to advance a funding or close operation. --- arkchannel/backing.go | 314 ++++++++++++ arkchannel/cooperative_close.go | 865 ++++++++++++++++++++++++++++++++ arkchannel/recovery.go | 190 +++++++ arkchannel/source_lifetime.go | 59 +++ arkchannel/types.go | 540 ++++++++++++++++++++ 5 files changed, 1968 insertions(+) create mode 100644 arkchannel/backing.go create mode 100644 arkchannel/cooperative_close.go create mode 100644 arkchannel/recovery.go create mode 100644 arkchannel/source_lifetime.go create mode 100644 arkchannel/types.go diff --git a/arkchannel/backing.go b/arkchannel/backing.go new file mode 100644 index 000000000..7eec83a95 --- /dev/null +++ b/arkchannel/backing.go @@ -0,0 +1,314 @@ +package arkchannel + +import ( + "bytes" + "fmt" + + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "github.com/btcsuite/btcd/psbt/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/lib/arkscript" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/keychain" + "github.com/lightningnetwork/lnd/lnwire" +) + +// BackingTemplate is the unsigned VTXO-to-channel transaction returned by +// lnd's external-funding flow, plus the exact Ark spend path that authorizes +// it. The transaction ID is stable because witness signatures are segregated. +type BackingTemplate struct { + packet *psbt.Packet + previousOut *wire.TxOut + spendPath *arkscript.SpendPath + channelPoint wire.OutPoint +} + +// NewBackingTemplate binds lnd's negotiated funding output to the one +// channel-policy VTXO created by a prepared OOR transfer. +func NewBackingTemplate(packet *psbt.Packet, terms Terms, + source VTXOBinding) (*BackingTemplate, error) { + + if packet == nil || packet.UnsignedTx == nil { + return nil, fmt.Errorf("lnd funding PSBT is required") + } + if err := terms.Validate(); err != nil { + return nil, err + } + if err := source.Validate(terms); err != nil { + return nil, err + } + if len(packet.UnsignedTx.TxIn) != 0 || len(packet.Inputs) != 0 { + return nil, fmt.Errorf("lnd funding PSBT must not contain " + + "inputs") + } + if len(packet.UnsignedTx.TxOut) != 1 || len(packet.Outputs) != 1 { + return nil, fmt.Errorf("lnd funding PSBT must contain " + + "exactly one channel output") + } + if packet.UnsignedTx.TxOut[0].Value != int64(terms.Capacity) { + return nil, fmt.Errorf("lnd funding output value %d does not "+ + "match capacity %d", packet.UnsignedTx.TxOut[0].Value, + terms.Capacity) + } + reservedSCID := lnwire.NewShortChanIDFromInt(terms.ReservedSCID) + if reservedSCID.TxPosition != 0 { + return nil, fmt.Errorf("reserved SCID output %d does not "+ + "match the single lnd funding output", + reservedSCID.TxPosition) + } + if source.Amount <= terms.Capacity { + return nil, fmt.Errorf("channel VTXO must reserve a positive " + + "backing transaction fee") + } + + policy, err := channelPolicy(terms.VTXO) + if err != nil { + return nil, err + } + spendPath, err := policy.ChannelSpendPath() + if err != nil { + return nil, fmt.Errorf("derive channel materialization "+ + "path: %w", err) + } + if err := spendPath.VerifyBindsToPkScript(source.PkScript); err != nil { + return nil, fmt.Errorf("validate channel materialization "+ + "path: %w", err) + } + + tx := packet.UnsignedTx + tx.Version = 2 + tx.LockTime = spendPath.RequiredLockTime + tx.AddTxIn(&wire.TxIn{ + PreviousOutPoint: source.OutPoint, + Sequence: spendPath.RequiredSequence, + }) + previousOut := &wire.TxOut{ + Value: int64(source.Amount), + PkScript: bytes.Clone(source.PkScript), + } + packet.Inputs = append(packet.Inputs, psbt.PInput{ + WitnessUtxo: previousOut, + }) + if err := spendPath.AttachTapLeafScript(&packet.Inputs[0]); err != nil { + return nil, fmt.Errorf("attach channel spend path: %w", err) + } + if err := packet.SanityCheck(); err != nil { + return nil, fmt.Errorf("validate channel backing PSBT: %w", err) + } + + return &BackingTemplate{ + packet: packet, + previousOut: previousOut, + spendPath: spendPath, + channelPoint: wire.OutPoint{ + Hash: tx.TxHash(), + }, + }, nil +} + +// Packet returns the populated PSBT that lnd must verify before its funding +// intent is finalized. The caller must not mutate it after signatures begin. +func (t *BackingTemplate) Packet() *psbt.Packet { + return t.packet +} + +// Transaction returns a copy of the unsigned backing transaction. +func (t *BackingTemplate) Transaction() *wire.MsgTx { + return t.packet.UnsignedTx.Copy() +} + +// ChannelPoint returns the stable channel point before witness signatures are +// attached. +func (t *BackingTemplate) ChannelPoint() wire.OutPoint { + return t.channelPoint +} + +// ValidateFundingOutput lets either endpoint compare the template with the +// exact output derived from its own lnd funding reservation before signing. +func (t *BackingTemplate) ValidateFundingOutput(expected *wire.TxOut) error { + if expected == nil { + return fmt.Errorf("expected lnd funding output is required") + } + actual := t.packet.UnsignedTx.TxOut[t.channelPoint.Index] + if actual.Value != expected.Value || + !bytes.Equal(actual.PkScript, expected.PkScript) { + return fmt.Errorf("backing transaction does not fund the " + + "local lnd reservation") + } + + return nil +} + +// SignDescriptor returns the exact tapscript descriptor for one channel +// endpoint after checking that the supplied key belongs to that role. +func (t *BackingTemplate) SignDescriptor(terms Terms, party Party, + keyDesc keychain.KeyDescriptor) (*input.SignDescriptor, error) { + + if keyDesc.PubKey == nil { + return nil, fmt.Errorf("channel backing signing key is " + + "required") + } + var expected [33]byte + switch party { + case PartyClient: + expected = terms.VTXO.ClientChannelKey + + case PartyHub: + expected = terms.VTXO.HubChannelKey + + default: + return nil, fmt.Errorf("unknown channel backing party %d", + party) + } + expectedKey, err := parseChannelKey("channel backing", expected) + if err != nil { + return nil, err + } + if !bytes.Equal( + schnorr.SerializePubKey(keyDesc.PubKey), + schnorr.SerializePubKey(expectedKey), + ) { + return nil, fmt.Errorf("signing key does not match %s "+ + "channel key", party) + } + + prevFetcher := txscript.NewCannedPrevOutputFetcher( + t.previousOut.PkScript, t.previousOut.Value, + ) + sigHashes := txscript.NewTxSigHashes( + t.packet.UnsignedTx, prevFetcher, + ) + + return t.spendPath.BuildSignDescriptor( + keyDesc, t.previousOut, sigHashes, prevFetcher, 0, + ), nil +} + +// Complete attaches both endpoint signatures, executes the channel VTXO +// tapscript locally, and returns the fully signed durable backing record. +func (t *BackingTemplate) Complete(terms Terms, source VTXOBinding, + clientSig, hubSig input.Signature) (Backing, error) { + + if clientSig == nil || hubSig == nil { + return Backing{}, fmt.Errorf("both channel backing " + + "signatures are required") + } + witness, err := t.spendPath.Witness( + arkscript.MaybeAppendSighash( + hubSig, txscript.SigHashDefault, + ), + arkscript.MaybeAppendSighash( + clientSig, txscript.SigHashDefault, + ), + ) + if err != nil { + return Backing{}, err + } + tx := t.packet.UnsignedTx.Copy() + tx.TxIn[0].Witness = witness + + var raw bytes.Buffer + if err := tx.Serialize(&raw); err != nil { + return Backing{}, fmt.Errorf("serialize channel backing: %w", + err) + } + backing := Backing{ + Transaction: raw.Bytes(), + ChannelPoint: t.channelPoint, + } + if err := backing.Validate(terms, source); err != nil { + return Backing{}, err + } + + return backing, nil +} + +// verifyBackingWitness executes the canonical channel spend path against the +// exact source output. Reconstructing the policy from semantic terms prevents a +// peer or persisted artifact from substituting witness script material. +func verifyBackingWitness(tx *wire.MsgTx, terms Terms, + source VTXOBinding) error { + + policy, err := channelPolicy(terms.VTXO) + if err != nil { + return err + } + spendPath, err := policy.ChannelSpendPath() + if err != nil { + return fmt.Errorf("derive channel materialization path: %w", + err) + } + if err := spendPath.VerifyBindsToPkScript(source.PkScript); err != nil { + return fmt.Errorf("validate channel materialization path: %w", + err) + } + + previousOut := &wire.TxOut{ + Value: int64(source.Amount), + PkScript: bytes.Clone(source.PkScript), + } + prevFetcher := txscript.NewCannedPrevOutputFetcher( + previousOut.PkScript, previousOut.Value, + ) + sigHashes := txscript.NewTxSigHashes(tx, prevFetcher) + engine, err := txscript.NewEngine( + previousOut.PkScript, tx, 0, txscript.StandardVerifyFlags, nil, + sigHashes, previousOut.Value, prevFetcher, + ) + if err != nil { + return fmt.Errorf("construct channel backing verifier: %w", err) + } + if err := engine.Execute(); err != nil { + return fmt.Errorf("verify channel backing signatures: %w", err) + } + + return nil +} + +// channelPolicy reconstructs the channel-policy tree from durable semantic +// terms rather than trusting caller-supplied scripts. +func channelPolicy(terms VTXOTerms) (*arkscript.ChannelVTXOPolicy, error) { + clientArkKey, err := parseChannelKey("client Ark", terms.ClientArkKey) + if err != nil { + return nil, err + } + hubArkKey, err := parseChannelKey("hub Ark", terms.HubArkKey) + if err != nil { + return nil, err + } + operatorKey, err := parseChannelKey( + "Ark operator", terms.ArkOperatorKey, + ) + if err != nil { + return nil, err + } + clientChannelKey, err := parseChannelKey( + "client channel", terms.ClientChannelKey, + ) + if err != nil { + return nil, err + } + hubChannelKey, err := parseChannelKey( + "hub channel", terms.HubChannelKey, + ) + if err != nil { + return nil, err + } + funderKey, err := parseChannelKey("funder", terms.FunderKey) + if err != nil { + return nil, err + } + + return arkscript.NewChannelVTXOPolicy(arkscript.ChannelVTXOParams{ + ClientArkKey: clientArkKey, + HubArkKey: hubArkKey, + ArkOperatorKey: operatorKey, + ClientChannelKey: clientChannelKey, + HubChannelKey: hubChannelKey, + FunderKey: funderKey, + ChannelDelay: terms.ChannelDelay, + FunderDelay: terms.FunderDelay, + MinExitDelay: terms.MinExitDelay, + }) +} diff --git a/arkchannel/cooperative_close.go b/arkchannel/cooperative_close.go new file mode 100644 index 000000000..746310d66 --- /dev/null +++ b/arkchannel/cooperative_close.go @@ -0,0 +1,865 @@ +package arkchannel + +import ( + "bytes" + "fmt" + "slices" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/psbt/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/lib/arkscript" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" + "github.com/lightninglabs/wavelength/lib/tx/psbtutil" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/keychain" + "github.com/lightningnetwork/lnd/tlv" +) + +// CooperativeCloseRequest fixes the ordinary replacement VTXO owners before +// either channel endpoint is quiesced. A compressed owner key retains the +// source policy for legacy requests. After rotation both delivery fields +// carry canonical standard VTXO templates, including the new session policy. +type CooperativeCloseRequest struct { + Initiator Party + ClientDeliveryScript []byte + HubDeliveryScript []byte +} + +// Clone returns a request without aliases to owner keys. +func (r CooperativeCloseRequest) Clone() CooperativeCloseRequest { + r.ClientDeliveryScript = slices.Clone(r.ClientDeliveryScript) + r.HubDeliveryScript = slices.Clone(r.HubDeliveryScript) + + return r +} + +// Validate rejects a close request whose replacement VTXOs cannot be bound to +// the two expected owners. +func (r CooperativeCloseRequest) Validate() error { + if r.Initiator != PartyClient { + return fmt.Errorf("cooperative close must be client initiated") + } + client, err := decodeCloseDelivery( + "client", r.ClientDeliveryScript, + ) + if err != nil { + return err + } + hub, err := decodeCloseDelivery("hub", r.HubDeliveryScript) + if err != nil { + return err + } + if client.OwnerKey.IsEqual(hub.OwnerKey) { + return fmt.Errorf("cooperative close owners must differ") + } + if (client.OperatorKey == nil) != (hub.OperatorKey == nil) || + client.ExitDelay != hub.ExitDelay || + (client.OperatorKey != nil && + !client.OperatorKey.IsEqual(hub.OperatorKey)) { + return fmt.Errorf("cooperative close delivery policies differ") + } + + return nil +} + +// checkpointPolicy resolves the session terms fixed by both destinations. +// Only legacy owner-only requests inherit the source's original policy. +func (r CooperativeCloseRequest) checkpointPolicy(terms Terms) ( + arkscript.CheckpointPolicy, error) { + + params, err := decodeCloseDelivery("client", r.ClientDeliveryScript) + if err != nil { + return arkscript.CheckpointPolicy{}, err + } + if params.OperatorKey != nil { + return arkscript.CheckpointPolicy{ + OperatorKey: params.OperatorKey, + CSVDelay: params.ExitDelay, + }, nil + } + operator, err := parseChannelKey( + "Ark operator", terms.VTXO.ArkOperatorKey, + ) + + return arkscript.CheckpointPolicy{ + OperatorKey: operator, CSVDelay: terms.VTXO.MinExitDelay, + }, err +} + +// CooperativeCloseProposal is the exact unsigned OOR checkpoint and the +// full-capacity role balance allocation used for its replacement VTXO +// amounts. ClientBalance and HubBalance must already sum exactly to +// Terms.Capacity; core does not infer or redistribute a missing balance. +type CooperativeCloseProposal struct { + Transaction []byte + CommitmentHeight uint64 + ClientBalance btcutil.Amount + HubBalance btcutil.Amount + ClientOutput btcutil.Amount + HubOutput btcutil.Amount +} + +// Clone returns a proposal without an alias to its checkpoint PSBT. +func (p CooperativeCloseProposal) Clone() CooperativeCloseProposal { + p.Transaction = slices.Clone(p.Transaction) + + return p +} + +// Validate reconstructs the canonical OOR package from immutable channel +// facts and requires byte-identical checkpoint signing material. +func (p CooperativeCloseProposal) Validate(terms Terms, source VTXOBinding, + request CooperativeCloseRequest) error { + + expected, _, err := buildCooperativeCloseProposal( + terms, source, request, p.ClientBalance, p.HubBalance, + p.CommitmentHeight, + ) + if err != nil { + return err + } + if p.CommitmentHeight != expected.CommitmentHeight || + p.ClientBalance != expected.ClientBalance || + p.HubBalance != expected.HubBalance || + p.ClientOutput != expected.ClientOutput || + p.HubOutput != expected.HubOutput || + !bytes.Equal(p.Transaction, expected.Transaction) { + return fmt.Errorf("cooperative close proposal is not canonical") + } + + return nil +} + +// CooperativeClose is the hub-authorized OOR close artifact. Transaction +// contains the hub signatures for both the checkpoint and final allocation; +// TxID is the deterministic OOR Ark transaction/session ID. +type CooperativeClose struct { + Proposal CooperativeCloseProposal + Transaction []byte + TxID chainhash.Hash +} + +// AuthorizationReceipt binds a client's receipt to both hub signatures. The +// public OOR txid alone does not prove receipt of the signed package. +func (c CooperativeClose) AuthorizationReceipt() chainhash.Hash { + return chainhash.HashH(c.Transaction) +} + +// Clone returns a close artifact without aliases to signature or PSBT bytes. +func (c CooperativeClose) Clone() CooperativeClose { + c.Proposal = c.Proposal.Clone() + c.Transaction = slices.Clone(c.Transaction) + + return c +} + +// Validate proves the proposal is canonical, its session ID is deterministic, +// and the hub authorized both the checkpoint and the final payout allocation. +func (c CooperativeClose) Validate(terms Terms, source VTXOBinding, + request CooperativeCloseRequest) error { + + if err := c.Proposal.Validate(terms, source, request); err != nil { + return err + } + template, err := NewCooperativeCloseTemplate( + terms, source, request, c.Proposal.ClientBalance, + c.Proposal.HubBalance, c.Proposal.CommitmentHeight, + ) + if err != nil { + return err + } + if c.TxID != template.sessionID { + return fmt.Errorf("cooperative close OOR session ID does not " + + "match") + } + checkpointSig, arkSig, err := c.Signatures() + if err != nil { + return err + } + if err := template.VerifySignature( + terms, PartyHub, checkpointSig, + ); err != nil { + return err + } + + return template.VerifyArkSignature(terms, PartyHub, arkSig) +} + +// Signatures decodes both durable authorizations. A legacy checkpoint-only +// signature cannot prove that the hub agreed to the final payout. +func (c CooperativeClose) Signatures() (*schnorr.Signature, *schnorr.Signature, + error) { + + if len(c.Transaction) > 1024 { + return nil, nil, fmt.Errorf("close authorization exceeds " + + "size limit") + } + var checkpointRaw, arkRaw []byte + stream, err := tlv.NewStream( + tlv.MakePrimitiveRecord(1, &checkpointRaw), + tlv.MakePrimitiveRecord(3, &arkRaw), + ) + if err != nil { + return nil, nil, err + } + if err := stream.Decode(bytes.NewReader(c.Transaction)); err != nil { + return nil, nil, fmt.Errorf("decode close authorization: %w", + err) + } + checkpointSig, err := schnorr.ParseSignature(checkpointRaw) + if err != nil { + return nil, nil, fmt.Errorf("parse checkpoint "+ + "authorization: %w", err) + } + arkSig, err := schnorr.ParseSignature(arkRaw) + if err != nil { + return nil, nil, fmt.Errorf("parse payout authorization: %w", + err) + } + + return checkpointSig, arkSig, nil +} + +// ReplacementOutPoint derives the exact ordinary VTXO assigned to one close +// participant. Reconstructing the canonical Ark transaction avoids assuming +// recipient order, which is changed by BIP69 output sorting. +func (c CooperativeClose) ReplacementOutPoint(terms Terms, source VTXOBinding, + request CooperativeCloseRequest, party Party) (wire.OutPoint, error) { + + if err := c.Validate(terms, source, request); err != nil { + return wire.OutPoint{}, err + } + + var ( + owner []byte + amount btcutil.Amount + ) + switch party { + case PartyClient: + owner = request.ClientDeliveryScript + amount = c.Proposal.ClientOutput + + case PartyHub: + owner = request.HubDeliveryScript + amount = c.Proposal.HubOutput + + default: + return wire.OutPoint{}, fmt.Errorf("unknown cooperative close "+ + "party %d", party) + } + if amount <= 0 { + return wire.OutPoint{}, fmt.Errorf("%s cooperative close has "+ + "no replacement output", party) + } + + policy, err := request.checkpointPolicy(terms) + if err != nil { + return wire.OutPoint{}, err + } + target, err := cooperativeCloseRecipient( + owner, policy.OperatorKey, policy.CSVDelay, amount, + ) + if err != nil { + return wire.OutPoint{}, err + } + template, err := NewCooperativeCloseTemplate( + terms, source, request, c.Proposal.ClientBalance, + c.Proposal.HubBalance, c.Proposal.CommitmentHeight, + ) + if err != nil { + return wire.OutPoint{}, err + } + outpoint, err := oortx.RecipientOutPoint( + c.TxID, template.recipients, target, + ) + if err != nil { + return wire.OutPoint{}, fmt.Errorf("derive %s cooperative "+ + "close replacement: %w", party, err) + } + + return outpoint, nil +} + +// CooperativeCloseOORSpec contains the deterministic ordinary OOR actor input +// data that is safe to hand across the core channel package boundary. +type CooperativeCloseOORSpec struct { + CheckpointPolicy arkscript.CheckpointPolicy + SpendPath []byte + Recipients []oortx.RecipientOutput + + // OwnerLeafScript retains every source owner in the checkpoint spend. + OwnerLeafScript []byte + + // OwnerLeafPolicy encodes that exact owner set for durable OOR replay. + OwnerLeafPolicy []byte +} + +// CooperativeCloseTemplate owns the canonical OOR proposal and the immediate +// three-party spend path while the hub signature is collected. +type CooperativeCloseTemplate struct { + proposal CooperativeCloseProposal + sessionID chainhash.Hash + previousOut *wire.TxOut + checkpoint *psbt.Packet + ark *psbt.Packet + ownerPolicy []byte + spendPath *arkscript.SpendPath + policy arkscript.CheckpointPolicy + recipients []oortx.RecipientOutput +} + +// NewCooperativeCloseTemplate builds an OOR transfer from full-capacity role +// balances supplied by the runtime at the same clean commitment height. +func NewCooperativeCloseTemplate(terms Terms, source VTXOBinding, + request CooperativeCloseRequest, + clientBalance, hubBalance btcutil.Amount, commitmentHeight uint64) ( + *CooperativeCloseTemplate, error) { + + proposal, artifacts, err := buildCooperativeCloseProposal( + terms, source, request, clientBalance, hubBalance, + commitmentHeight, + ) + if err != nil { + return nil, err + } + + return &CooperativeCloseTemplate{ + proposal: proposal, sessionID: artifacts.sessionID, + previousOut: artifacts.previousOut, + checkpoint: artifacts.checkpoint, + ark: artifacts.ark, + ownerPolicy: artifacts.ownerPolicy, + spendPath: artifacts.spendPath, + policy: artifacts.policy, + recipients: artifacts.recipients, + }, nil +} + +// Proposal returns an isolated copy of the unsigned OOR close proposal. +func (t *CooperativeCloseTemplate) Proposal() CooperativeCloseProposal { + return t.proposal.Clone() +} + +// OORSpec returns isolated deterministic inputs for the ordinary OOR actor. +func (t *CooperativeCloseTemplate) OORSpec() (CooperativeCloseOORSpec, error) { + spendPath, err := t.spendPath.Encode() + if err != nil { + return CooperativeCloseOORSpec{}, err + } + + return CooperativeCloseOORSpec{ + CheckpointPolicy: t.policy, + SpendPath: spendPath, + Recipients: cloneCooperativeCloseRecipients(t.recipients), + OwnerLeafScript: slices.Clone( + t.ark.Inputs[0].TaprootLeafScript[0].Script, + ), + OwnerLeafPolicy: slices.Clone(t.ownerPolicy), + }, nil +} + +// ArkTransaction returns the exact payout transaction the hub must authorize. +func (t *CooperativeCloseTemplate) ArkTransaction() *wire.MsgTx { + return t.ark.UnsignedTx.Copy() +} + +// ArkSignDescriptor binds the signer's channel role to the final allocation. +func (t *CooperativeCloseTemplate) ArkSignDescriptor(terms Terms, party Party, + keyDesc keychain.KeyDescriptor) (*input.SignDescriptor, error) { + + desc, err := t.SignDescriptor(terms, party, keyDesc) + if err != nil { + return nil, err + } + output := t.ark.Inputs[0].WitnessUtxo + leaf := t.ark.Inputs[0].TaprootLeafScript[0] + desc.Output = output + desc.WitnessScript = slices.Clone(leaf.Script) + desc.ControlBlock = slices.Clone(leaf.ControlBlock) + desc.PrevOutputFetcher = txscript.NewCannedPrevOutputFetcher( + output.PkScript, output.Value, + ) + desc.SigHashes = txscript.NewTxSigHashes( + t.ark.UnsignedTx, desc.PrevOutputFetcher, + ) + + return desc, nil +} + +// VerifyArkSignature rejects authorization of another transaction or payout. +func (t *CooperativeCloseTemplate) VerifyArkSignature(terms Terms, party Party, + sig input.Signature) error { + + key := terms.VTXO.HubArkKey + if party == PartyClient { + key = terms.VTXO.ClientArkKey + } + pubKey, err := parseChannelKey("payout", key) + if err != nil { + return err + } + desc, err := t.ArkSignDescriptor(terms, party, keychain.KeyDescriptor{ + PubKey: pubKey, + }) + if err != nil { + return err + } + if sig == nil { + return fmt.Errorf("payout authorization is required") + } + hash, err := txscript.CalcTapscriptSignaturehash( + desc.SigHashes, desc.HashType, t.ark.UnsignedTx, + desc.InputIndex, desc.PrevOutputFetcher, + txscript.NewBaseTapLeaf(desc.WitnessScript), + ) + if err != nil { + return err + } + if !sig.Verify(hash, pubKey) { + return fmt.Errorf("invalid %s payout authorization", party) + } + + return nil +} + +// SignDescriptor returns the exact checkpoint descriptor after checking that +// the signer owns the requested endpoint role in the 3-of-3 policy leaf. +func (t *CooperativeCloseTemplate) SignDescriptor(terms Terms, party Party, + keyDesc keychain.KeyDescriptor) (*input.SignDescriptor, error) { + + var expected [33]byte + switch party { + case PartyClient: + expected = terms.VTXO.ClientArkKey + + case PartyHub: + expected = terms.VTXO.HubArkKey + + default: + return nil, fmt.Errorf("unknown cooperative close party %d", + party) + } + + return t.signDescriptor(expected, keyDesc) +} + +// VerifySignature proves one participant signed the canonical checkpoint. +func (t *CooperativeCloseTemplate) VerifySignature(terms Terms, party Party, + sig input.Signature) error { + + if sig == nil { + return fmt.Errorf("%s cooperative close signature is required", + party) + } + var expected [33]byte + switch party { + case PartyClient: + expected = terms.VTXO.ClientArkKey + + case PartyHub: + expected = terms.VTXO.HubArkKey + + default: + return fmt.Errorf("unknown cooperative close party %d", party) + } + pubKey, err := parseChannelKey("cooperative close", expected) + if err != nil { + return err + } + desc, err := t.signDescriptor( + expected, keychain.KeyDescriptor{ + PubKey: pubKey, + }, + ) + if err != nil { + return err + } + leaf := txscript.NewBaseTapLeaf(desc.WitnessScript) + sigHash, err := txscript.CalcTapscriptSignaturehash( + desc.SigHashes, desc.HashType, t.checkpoint.UnsignedTx, + desc.InputIndex, desc.PrevOutputFetcher, leaf, + ) + if err != nil { + return fmt.Errorf("derive %s cooperative close sighash: %w", + party, err) + } + if !sig.Verify(sigHash, pubKey) { + return fmt.Errorf("invalid %s cooperative close signature", + party) + } + + return nil +} + +// Complete verifies and records the hub's checkpoint and final payout +// signatures. Client and Ark operator signatures remain absent until OOR +// submission, where the operator-first custody rule is enforced. +func (t *CooperativeCloseTemplate) Complete(terms Terms, source VTXOBinding, + request CooperativeCloseRequest, hubSig, hubArkSig input.Signature) ( + CooperativeClose, error) { + + if err := t.VerifySignature(terms, PartyHub, hubSig); err != nil { + return CooperativeClose{}, err + } + if err := t.VerifyArkSignature(terms, PartyHub, hubArkSig); err != nil { + return CooperativeClose{}, err + } + checkpointRaw, arkRaw := hubSig.Serialize(), hubArkSig.Serialize() + stream, err := tlv.NewStream( + tlv.MakePrimitiveRecord(1, &checkpointRaw), + tlv.MakePrimitiveRecord(3, &arkRaw), + ) + if err != nil { + return CooperativeClose{}, err + } + var authorization bytes.Buffer + if err := stream.Encode(&authorization); err != nil { + return CooperativeClose{}, err + } + settlement := CooperativeClose{ + Proposal: t.proposal.Clone(), + Transaction: authorization.Bytes(), + TxID: t.sessionID, + } + if err := settlement.Validate(terms, source, request); err != nil { + return CooperativeClose{}, err + } + + return settlement, nil +} + +// signDescriptor binds one expected key to the canonical checkpoint input. +func (t *CooperativeCloseTemplate) signDescriptor(expected [33]byte, + keyDesc keychain.KeyDescriptor) (*input.SignDescriptor, error) { + + if keyDesc.PubKey == nil { + return nil, fmt.Errorf("cooperative close signing key is " + + "required") + } + expectedKey, err := parseChannelKey("cooperative close", expected) + if err != nil { + return nil, err + } + if !keyDesc.PubKey.IsEqual(expectedKey) { + return nil, fmt.Errorf("cooperative close signing key does " + + "not match policy role") + } + prevFetcher := txscript.NewCannedPrevOutputFetcher( + t.previousOut.PkScript, t.previousOut.Value, + ) + sigHashes := txscript.NewTxSigHashes( + t.checkpoint.UnsignedTx, prevFetcher, + ) + + return t.spendPath.BuildSignDescriptor( + keyDesc, t.previousOut, sigHashes, prevFetcher, 0, + ), nil +} + +type cooperativeCloseArtifacts struct { + sessionID chainhash.Hash + previousOut *wire.TxOut + checkpoint *psbt.Packet + ark *psbt.Packet + ownerPolicy []byte + spendPath *arkscript.SpendPath + policy arkscript.CheckpointPolicy + recipients []oortx.RecipientOutput +} + +// buildCooperativeCloseProposal derives OOR outputs only from immutable +// channel facts and a full-capacity role balance allocation. +func buildCooperativeCloseProposal(terms Terms, source VTXOBinding, + request CooperativeCloseRequest, + clientBalance, hubBalance btcutil.Amount, commitmentHeight uint64) ( + CooperativeCloseProposal, cooperativeCloseArtifacts, error) { + + if err := terms.Validate(); err != nil { + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + if err := source.Validate(terms); err != nil { + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + if err := request.Validate(); err != nil { + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + if clientBalance < 0 || hubBalance < 0 || + clientBalance+hubBalance != terms.Capacity { + return CooperativeCloseProposal{}, cooperativeCloseArtifacts{}, + fmt.Errorf("cooperative close balances %d + %d do not "+ + "match capacity %d", clientBalance, hubBalance, + terms.Capacity) + } + reserve := source.Amount - terms.Capacity + if reserve <= 0 { + return CooperativeCloseProposal{}, cooperativeCloseArtifacts{}, + fmt.Errorf("channel VTXO has no backing reserve") + } + // Promotion is client-funded. The unused backing reserve returns + // to the client; it was never part of the Lightning capacity. + clientOutput := clientBalance + reserve + hubOutput := hubBalance + + checkpointPolicy, err := request.checkpointPolicy(terms) + if err != nil { + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + clientKey, err := parseChannelKey( + "client Ark", terms.VTXO.ClientArkKey, + ) + if err != nil { + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + channelPolicy, err := channelPolicy(terms.VTXO) + if err != nil { + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + spendPath, err := channelPolicy.CooperativeSpendPath() + if err != nil { + return CooperativeCloseProposal{}, cooperativeCloseArtifacts{}, + fmt.Errorf("derive cooperative close path: %w", err) + } + if err := spendPath.VerifyBindsToPkScript(source.PkScript); err != nil { + return CooperativeCloseProposal{}, cooperativeCloseArtifacts{}, + fmt.Errorf("validate cooperative close path: %w", err) + } + + hubKey, err := parseChannelKey("hub Ark", terms.VTXO.HubArkKey) + if err != nil { + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + // The checkpoint has three independent signers even when its + // operator is no longer the operator on the input spend path. + if len(request.ClientDeliveryScript) != btcec.PubKeyBytesLenCompressed { + key := schnorr.SerializePubKey(checkpointPolicy.OperatorKey) + if bytes.Equal(key, schnorr.SerializePubKey(clientKey)) || + bytes.Equal(key, schnorr.SerializePubKey(hubKey)) { + + err := fmt.Errorf("checkpoint operator duplicates a " + + "channel owner") + + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + } + ownerLeaf := arkscript.LeafTemplate{ + Node: &arkscript.Multisig{ + Keys: []*btcec.PublicKey{ + clientKey, + hubKey, + checkpointPolicy.OperatorKey, + }, + }, + } + ownerScript, err := ownerLeaf.Script() + if err != nil { + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + ownerPolicy, err := ownerLeaf.Encode() + if err != nil { + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + previousOut := &wire.TxOut{ + Value: int64(source.Amount), PkScript: slices.Clone( + source.PkScript, + ), + } + checkpoint, err := oortx.BuildCheckpointPSBT( + checkpointPolicy, oortx.CheckpointInput{ + SpentVTXO: oortx.SpentVTXORef{ + Outpoint: source.OutPoint, Output: previousOut, + }, + OwnerLeafScript: ownerScript, + OwnerLeafPolicy: ownerPolicy, + }, + ) + if err != nil { + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + checkpoint.PSBT.UnsignedTx.LockTime = spendPath.RequiredLockTime + checkpoint.PSBT.UnsignedTx.TxIn[0].Sequence = spendPath.RequiredSequence + + recipients := make([]oortx.RecipientOutput, 0, 2) + if clientOutput > 0 { + recipient, err := cooperativeCloseRecipient( + request.ClientDeliveryScript, + checkpointPolicy.OperatorKey, checkpointPolicy.CSVDelay, + clientOutput, + ) + if err != nil { + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + recipients = append(recipients, recipient) + } + if hubOutput > 0 { + recipient, err := cooperativeCloseRecipient( + request.HubDeliveryScript, checkpointPolicy.OperatorKey, + checkpointPolicy.CSVDelay, hubOutput, + ) + if err != nil { + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + recipients = append(recipients, recipient) + } + if len(recipients) == 0 { + return CooperativeCloseProposal{}, cooperativeCloseArtifacts{}, + fmt.Errorf("cooperative close has no replacement VTXO") + } + checkpointOut, err := checkpoint.ToCheckpointOutput() + if err != nil { + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + arkPSBT, err := oortx.BuildArkPSBT( + []oortx.CheckpointOutput{checkpointOut}, recipients, + ) + if err != nil { + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + arkPSBT.UnsignedTx.LockTime = spendPath.RequiredLockTime + arkPSBT.UnsignedTx.TxIn[0].Sequence = spendPath.RequiredSequence + ownerSpend, err := oortx.BuildTaprootTapLeafScript( + checkpoint.TapTreeEncoded, ownerScript, + ) + if err != nil { + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + arkPSBT.Inputs[0].TaprootLeafScript = []*psbt.TaprootTapLeafScript{ + ownerSpend, + } + checkpointRaw, err := psbtutil.Serialize(checkpoint.PSBT) + if err != nil { + return CooperativeCloseProposal{}, + cooperativeCloseArtifacts{}, err + } + + return CooperativeCloseProposal{ + Transaction: checkpointRaw, + CommitmentHeight: commitmentHeight, + ClientBalance: clientBalance, + HubBalance: hubBalance, + ClientOutput: clientOutput, + HubOutput: hubOutput, + }, cooperativeCloseArtifacts{ + sessionID: arkPSBT.UnsignedTx.TxHash(), + previousOut: previousOut, + checkpoint: checkpoint.PSBT, + ark: arkPSBT, + ownerPolicy: ownerPolicy, + spendPath: spendPath, + policy: checkpointPolicy, + recipients: recipients, + }, nil +} + +// cooperativeCloseRecipient constructs one ordinary Ark VTXO output. +func cooperativeCloseRecipient(rawOwnerKey []byte, operatorKey *btcec.PublicKey, + exitDelay uint32, + amount btcutil.Amount) (oortx.RecipientOutput, error) { + + ownerKey, err := CooperativeCloseDeliveryOwner(rawOwnerKey) + if err != nil { + return oortx.RecipientOutput{}, err + } + policy, err := arkscript.NewVTXOPolicy( + ownerKey, operatorKey, exitDelay, + ) + if err != nil { + return oortx.RecipientOutput{}, err + } + policyTemplate, err := policy.Template.Encode() + if err != nil { + return oortx.RecipientOutput{}, err + } + pkScript, err := policy.Template.PkScript() + if err != nil { + return oortx.RecipientOutput{}, err + } + + return oortx.RecipientOutput{ + PkScript: pkScript, Value: amount, + VTXOPolicyTemplate: policyTemplate, + }, nil +} + +// CooperativeCloseDeliveryOwner identifies the payout owner independently +// of later key rotations when replaying an already signed close. +func CooperativeCloseDeliveryOwner(raw []byte) (*btcec.PublicKey, error) { + params, err := decodeCloseDelivery("replacement", raw) + if err != nil { + return nil, err + } + + return params.OwnerKey, nil +} + +// decodeCloseDelivery accepts a legacy owner or an exact canonical standard +// VTXO policy. No other spending paths may accompany the quoted owner. +func decodeCloseDelivery(role string, + raw []byte) (*arkscript.StandardVTXOParams, error) { + + if len(raw) == btcec.PubKeyBytesLenCompressed { + key, err := btcec.ParsePubKey(raw) + if err != nil { + return nil, fmt.Errorf("parse %s close owner: %w", role, + err) + } + + return &arkscript.StandardVTXOParams{OwnerKey: key}, nil + } + template, err := arkscript.DecodePolicyTemplate(raw) + if err != nil { + return nil, fmt.Errorf("decode %s close delivery: %w", role, + err) + } + params, err := arkscript.DecodeStandardVTXOParams(template) + if err != nil { + return nil, err + } + canonical, err := arkscript.EncodeStandardVTXOTemplate( + params.OwnerKey, params.OperatorKey, params.ExitDelay, + ) + if err != nil { + return nil, err + } + if !bytes.Equal(canonical, raw) { + return nil, fmt.Errorf("noncanonical %s close delivery", role) + } + + return params, nil +} + +// cloneCooperativeCloseRecipients returns recipients without mutable aliases. +func cloneCooperativeCloseRecipients( + recipients []oortx.RecipientOutput) []oortx.RecipientOutput { + + cloned := make([]oortx.RecipientOutput, len(recipients)) + for i := range recipients { + cloned[i] = recipients[i] + cloned[i].PkScript = slices.Clone(recipients[i].PkScript) + cloned[i].VTXOPolicyTemplate = slices.Clone( + recipients[i].VTXOPolicyTemplate, + ) + } + + return cloned +} diff --git a/arkchannel/recovery.go b/arkchannel/recovery.go new file mode 100644 index 000000000..ce5f6d44e --- /dev/null +++ b/arkchannel/recovery.go @@ -0,0 +1,190 @@ +package arkchannel + +import ( + "bytes" + "fmt" + "slices" + + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" +) + +// RecoveryPackage is the complete endpoint-neutral data needed to watch and +// unroll a channel-policy VTXO. It deliberately contains no private key or +// wallet ownership marker. +type RecoveryPackage struct { + Descriptor RecoveryDescriptor + Packages []RecoveryOORPackage +} + +// RecoveryDescriptor carries the round ancestry inherited by the +// channel-policy VTXO. +type RecoveryDescriptor struct { + Ancestry []RecoveryAncestry + RoundID string + CommitmentTxID chainhash.Hash + BatchExpiry int32 + ChainDepth int + CreatedHeight int32 + ConstructionVersion int32 +} + +// RecoveryAncestry is one serialized commitment-tree path in the source +// descriptor. +type RecoveryAncestry struct { + TreePath []byte + CommitmentTxID chainhash.Hash + InputIndices []uint32 + TreeDepth uint32 + CommitmentHeight int32 +} + +// RecoveryOORPackage is one finalized Ark/checkpoint package in farthest +// ancestor to target order. +type RecoveryOORPackage struct { + SessionID chainhash.Hash + Direction int32 + ArkPSBT []byte + Checkpoints [][]byte +} + +// OORRecoverySource identifies one exact finalized output whose sender-owned +// OOR artifacts must be exported for channel recovery. +type OORRecoverySource struct { + OutPoint wire.OutPoint + Amount btcutil.Amount + PkScript []byte +} + +// Clone returns an isolated OOR recovery source. +func (s OORRecoverySource) Clone() OORRecoverySource { + s.PkScript = slices.Clone(s.PkScript) + + return s +} + +// Validate rejects an incomplete OOR recovery source. +func (s OORRecoverySource) Validate() error { + if s.OutPoint.Hash == (chainhash.Hash{}) { + return fmt.Errorf("OOR recovery outpoint is required") + } + if s.Amount <= 0 { + return fmt.Errorf("OOR recovery amount must be positive") + } + if len(s.PkScript) == 0 { + return fmt.Errorf("OOR recovery script is required") + } + + return nil +} + +// Clone returns an isolated recovery package. +func (p RecoveryPackage) Clone() RecoveryPackage { + ancestry := p.Descriptor.Ancestry + p.Descriptor.Ancestry = make( + []RecoveryAncestry, len(ancestry), + ) + for i := range ancestry { + entry := ancestry[i] + entry.TreePath = slices.Clone(entry.TreePath) + entry.InputIndices = slices.Clone(entry.InputIndices) + p.Descriptor.Ancestry[i] = entry + } + packages := p.Packages + p.Packages = make([]RecoveryOORPackage, len(packages)) + for i := range packages { + entry := packages[i] + entry.ArkPSBT = slices.Clone(entry.ArkPSBT) + checkpoints := entry.Checkpoints + entry.Checkpoints = make([][]byte, len(checkpoints)) + for j := range checkpoints { + entry.Checkpoints[j] = slices.Clone( + checkpoints[j], + ) + } + p.Packages[i] = entry + } + + return p +} + +// Validate checks the package shape and binds its target package to source. +// Database and transaction codecs perform the deeper tree and PSBT checks. +func (p RecoveryPackage) Validate(source VTXOBinding) error { + return p.validate(source.OORSessionID) +} + +// ValidateOORSource checks the package shape and binds its target package to +// one exact finalized OOR output. +func (p RecoveryPackage) ValidateOORSource(source OORRecoverySource) error { + if err := source.Validate(); err != nil { + return err + } + + return p.validate(source.OutPoint.Hash) +} + +// validate checks the package shape and binds its target package to one OOR +// session without depending on the source policy type. +func (p RecoveryPackage) validate(targetSessionID chainhash.Hash) error { + desc := p.Descriptor + if desc.RoundID == "" || desc.CommitmentTxID == (chainhash.Hash{}) || + desc.BatchExpiry <= 0 || desc.CreatedHeight <= 0 || + desc.ChainDepth <= 0 { + return fmt.Errorf("channel recovery descriptor is incomplete") + } + if len(desc.Ancestry) == 0 { + return fmt.Errorf("channel recovery ancestry is empty") + } + for i := range desc.Ancestry { + entry := desc.Ancestry[i] + if len(entry.TreePath) == 0 || + entry.CommitmentTxID == (chainhash.Hash{}) { + return fmt.Errorf("channel recovery ancestry %d is "+ + "incomplete", i) + } + } + if len(p.Packages) == 0 { + return fmt.Errorf("channel recovery OOR packages are empty") + } + targetFound := false + seen := make(map[chainhash.Hash][]byte, len(p.Packages)) + for i := range p.Packages { + entry := p.Packages[i] + if entry.SessionID == (chainhash.Hash{}) || + len(entry.ArkPSBT) == 0 || len(entry.Checkpoints) == 0 { + return fmt.Errorf("channel recovery OOR package %d is "+ + "incomplete", i) + } + if entry.Direction != 0 && entry.Direction != 1 { + return fmt.Errorf("channel recovery OOR package %d "+ + "has invalid direction %d", i, entry.Direction) + } + for j := range entry.Checkpoints { + if len(entry.Checkpoints[j]) == 0 { + return fmt.Errorf("channel recovery "+ + "checkpoint %d/%d is empty", i, j) + } + } + if prior, ok := seen[entry.SessionID]; ok { + if !bytes.Equal(prior, entry.ArkPSBT) { + return fmt.Errorf("channel recovery package "+ + "%s is duplicated with another payload", + entry.SessionID) + } + + continue + } + seen[entry.SessionID] = entry.ArkPSBT + if entry.SessionID == targetSessionID { + targetFound = true + } + } + if !targetFound { + return fmt.Errorf("channel recovery is missing target OOR " + + "package") + } + + return nil +} diff --git a/arkchannel/source_lifetime.go b/arkchannel/source_lifetime.go new file mode 100644 index 000000000..4505317b8 --- /dev/null +++ b/arkchannel/source_lifetime.go @@ -0,0 +1,59 @@ +package arkchannel + +import ( + "errors" + "fmt" +) + +// ErrSourceInadmissible means the selected inputs cannot safely fund this +// channel. An unavailable store or chain backend is not such a decision. +var ErrSourceInadmissible = errors.New("channel funding source inadmissible") + +// SourceExpirySafetyMargin reserves forty blocks beyond the materialization +// allowance before the earliest source batch can be swept by the operator. +const SourceExpirySafetyMargin = 40 + +// SourceMaterializationHeight returns the last safe height to start automatic +// materialization. New channel sources must be admitted strictly before this +// height. Missing expiry, zero allowance, and unrepresentable deadlines fail +// closed rather than permitting a source with an unknown recovery window. +func SourceMaterializationHeight(batchExpiry int32, + allowance uint32) (int32, error) { + + if batchExpiry <= 0 { + return 0, fmt.Errorf("source batch expiry must be positive") + } + if allowance == 0 { + return 0, fmt.Errorf("source materialization allowance must " + + "be positive") + } + + // Widen before adding so a uint32 allowance cannot wrap the reserve. + reserve := uint64(allowance) + SourceExpirySafetyMargin + if reserve >= uint64(batchExpiry) { + return 0, fmt.Errorf("source batch expiry %d cannot reserve "+ + "%d blocks for materialization", batchExpiry, reserve) + } + + return batchExpiry - int32(reserve), nil +} + +// ValidateSourceLifetime requires a known current height strictly before the +// source's materialization deadline. Equality is already too late to admit new +// channel funding, even though recovery of an existing channel must continue. +func ValidateSourceLifetime(batchExpiry, height int32, allowance uint32) error { + deadline, err := SourceMaterializationHeight(batchExpiry, allowance) + if err != nil { + return fmt.Errorf("%w: %w", ErrSourceInadmissible, err) + } + if height < 0 { + return fmt.Errorf("source current height must not be negative") + } + if height >= deadline { + return fmt.Errorf("%w: source lifetime exhausted at height "+ + "%d: materialization deadline %d (batch expiry %d)", + ErrSourceInadmissible, height, deadline, batchExpiry) + } + + return nil +} diff --git a/arkchannel/types.go b/arkchannel/types.go new file mode 100644 index 000000000..a9d3f06cc --- /dev/null +++ b/arkchannel/types.go @@ -0,0 +1,540 @@ +package arkchannel + +import ( + "bytes" + "fmt" + "slices" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/lib/arkscript" + "github.com/lightningnetwork/lnd/lnwire" +) + +// DefaultBackingFee is the fixed fee reserved above channel capacity for the +// deterministic VTXO-to-channel funding transaction. +const DefaultBackingFee btcutil.Amount = 1_000 + +// ID is the stable identifier shared by both sides of an Ark channel. +type ID [32]byte + +// Kind identifies how the VTXO backing a channel is obtained. +type Kind uint8 + +// KindPromotion moves an existing client-owned VTXO into a channel-policy +// VTXO through an OOR transfer. Value 2 is retired and must not be reused. +const KindPromotion Kind = 1 + +// String returns the durable name of a channel kind. +func (k Kind) String() string { + switch k { + case KindPromotion: + return "promotion" + + default: + return "unknown" + } +} + +// FundingInitiator returns the endpoint that starts lnd's channel-opening +// state machine and pays the Lightning commitment fees. +func (t Terms) FundingInitiator() Party { + return t.Funder +} + +// InitialPushAmount returns the amount the lnd initiator pushes to its peer. +// All opening liquidity belongs to the Ark funder. +func (t Terms) InitialPushAmount() btcutil.Amount { + return 0 +} + +// Party identifies one endpoint of the private Lightning channel. +type Party uint8 + +const ( + // PartyClient is the Wavelength endpoint. + PartyClient Party = iota + 1 + + // PartyHub is the swapdk-server endpoint. + PartyHub +) + +// String returns the durable name of a channel party. +func (p Party) String() string { + switch p { + case PartyClient: + return "client" + + case PartyHub: + return "hub" + + default: + return "unknown" + } +} + +// Phase is the Ark coordination phase, not the Lightning channel state. +type Phase uint8 + +const ( + // PhaseRequested means immutable channel terms are registered. + PhaseRequested Phase = iota + 1 + + // PhaseNegotiating means the exact VTXO is bound and lnd funding is in + // progress. + PhaseNegotiating + + // PhaseBackingReady means the signed backing and both lnd finalization + // acknowledgements are durable, so the prepared OOR transfer can + // commit. + PhaseBackingReady + + // PhaseActivating means lnd should observe the virtual channel point. + PhaseActivating + + // PhaseActive means lnd reports the ordinary channel active. + PhaseActive + + // PhaseMaterializing means the Ark ancestry and backing transaction are + // being published. + PhaseMaterializing + + // PhaseOnChain means the backing transaction was published. + PhaseOnChain + + // PhaseClosed means lnd completed the channel lifecycle. + PhaseClosed + + // PhaseCancelling means the prepared OOR transfer is being aborted + // before lnd's pending funding reservation is removed. + PhaseCancelling + + // PhaseFailed means negotiation failed before the no-failure boundary. + PhaseFailed + + // PhaseCoopClosing means both endpoints must quiesce lnd and agree on + // one clean commitment state before authorizing an ordinary OOR close. + PhaseCoopClosing + + // PhaseCoopCloseSigned means both endpoints durably stored the hub's + // authorization for the exact 3-of-3 OOR close. The historical name is + // retained because phase values are persisted. + PhaseCoopCloseSigned + + // PhaseCoopClosePublished means the ordinary OOR close finalized and + // the local lnd database must archive the channel. The historical name + // is retained because phase values are persisted. + PhaseCoopClosePublished +) + +// String returns the durable name of a coordination phase. +func (p Phase) String() string { + switch p { + case PhaseRequested: + return "requested" + + case PhaseNegotiating: + return "negotiating" + + case PhaseBackingReady: + return "backing_ready" + + case PhaseActivating: + return "activating" + + case PhaseActive: + return "active" + + case PhaseMaterializing: + return "materializing" + + case PhaseOnChain: + return "on_chain" + + case PhaseClosed: + return "closed" + + case PhaseCancelling: + return "cancelling" + + case PhaseFailed: + return "failed" + + case PhaseCoopClosing: + return "coop_closing" + + case PhaseCoopCloseSigned: + return "coop_close_authorized" + + case PhaseCoopClosePublished: + return "coop_close_oor_finalized" + + default: + return "unknown" + } +} + +// IsTerminal reports whether Ark coordination has no further work. +func (p Phase) IsTerminal() bool { + return p == PhaseClosed || p == PhaseFailed +} + +// VTXOTerms identify every key role and relative delay in the channel VTXO. +// Persisting semantics instead of derived script bytes gives both peers one +// canonical policy representation to validate. +type VTXOTerms struct { + ClientArkKey [33]byte + HubArkKey [33]byte + ArkOperatorKey [33]byte + ClientChannelKey [33]byte + HubChannelKey [33]byte + FunderKey [33]byte + ChannelDelay uint32 + FunderDelay uint32 + MinExitDelay uint32 +} + +// Artifacts derives and validates the canonical channel policy and P2TR +// script from semantic terms. +func (t VTXOTerms) Artifacts() ([]byte, []byte, error) { + clientArkKey, err := parseChannelKey("client Ark", t.ClientArkKey) + if err != nil { + return nil, nil, err + } + hubArkKey, err := parseChannelKey("hub Ark", t.HubArkKey) + if err != nil { + return nil, nil, err + } + operatorKey, err := parseChannelKey("Ark operator", t.ArkOperatorKey) + if err != nil { + return nil, nil, err + } + clientChannelKey, err := parseChannelKey( + "client channel", t.ClientChannelKey, + ) + if err != nil { + return nil, nil, err + } + hubChannelKey, err := parseChannelKey( + "hub channel", t.HubChannelKey, + ) + if err != nil { + return nil, nil, err + } + funderKey, err := parseChannelKey("funder", t.FunderKey) + if err != nil { + return nil, nil, err + } + + policy, pkScript, err := arkscript.EncodeChannelVTXOArtifacts( + arkscript.ChannelVTXOParams{ + ClientArkKey: clientArkKey, + HubArkKey: hubArkKey, + ArkOperatorKey: operatorKey, + ClientChannelKey: clientChannelKey, + HubChannelKey: hubChannelKey, + FunderKey: funderKey, + ChannelDelay: t.ChannelDelay, + FunderDelay: t.FunderDelay, + MinExitDelay: t.MinExitDelay, + }, + ) + if err != nil { + return nil, nil, fmt.Errorf("derive channel VTXO: %w", err) + } + + return policy, pkScript, nil +} + +// Terms are immutable facts shared by client and hub. +type Terms struct { + ID ID + Kind Kind + Funder Party + PendingChannelID [32]byte + ReservedSCID uint64 + Capacity btcutil.Amount + ClientNodeKey [33]byte + HubNodeKey [33]byte + VTXO VTXOTerms +} + +// Clone returns an isolated copy of immutable terms. +func (t Terms) Clone() Terms { + return t +} + +// Validate checks the balance and identity invariants shared by both sides. +func (t Terms) Validate() error { + if t.ID == (ID{}) { + return fmt.Errorf("channel ID is required") + } + if t.PendingChannelID == ([32]byte{}) { + return fmt.Errorf("pending channel ID is required") + } + if t.Capacity <= 0 { + return fmt.Errorf("channel capacity must be positive") + } + reservedSCID := lnwire.NewShortChanIDFromInt(t.ReservedSCID) + if reservedSCID.BlockHeight == 0 { + return fmt.Errorf("channel requires a reserved virtual SCID") + } + if reservedSCID.TxPosition != 0 { + return fmt.Errorf("channel funding output position must be " + + "zero") + } + if _, _, err := t.VTXO.Artifacts(); err != nil { + return err + } + if err := validateNodeKey("client", t.ClientNodeKey); err != nil { + return err + } + if err := validateNodeKey("hub", t.HubNodeKey); err != nil { + return err + } + if bytes.Equal(t.ClientNodeKey[:], t.HubNodeKey[:]) { + return fmt.Errorf("client and hub node keys must differ") + } + + if t.Kind != KindPromotion { + return fmt.Errorf("unsupported channel kind %d", t.Kind) + } + if t.Funder != PartyClient { + return fmt.Errorf("promotion must be client funded") + } + + return nil +} + +// VTXOBinding identifies the exact validated Ark output used as backing. +type VTXOBinding struct { + OORSessionID [32]byte + OutPoint wire.OutPoint + Amount btcutil.Amount + ArkTransaction []byte + PolicyTemplate []byte + PkScript []byte +} + +// Clone returns a binding without aliases to mutable byte slices. +func (b VTXOBinding) Clone() VTXOBinding { + b.ArkTransaction = slices.Clone(b.ArkTransaction) + b.PolicyTemplate = slices.Clone(b.PolicyTemplate) + b.PkScript = slices.Clone(b.PkScript) + + return b +} + +// Validate checks a binding against immutable channel terms. +func (b VTXOBinding) Validate(terms Terms) error { + if b.OutPoint.Hash == (chainhash.Hash{}) { + return fmt.Errorf("VTXO outpoint is required") + } + if b.OORSessionID == ([32]byte{}) { + return fmt.Errorf("OOR session ID is required") + } + if len(b.ArkTransaction) == 0 { + return fmt.Errorf("prepared Ark transaction is required") + } + tx := wire.NewMsgTx(2) + reader := bytes.NewReader(b.ArkTransaction) + if err := tx.Deserialize(reader); err != nil { + return fmt.Errorf("decode prepared Ark transaction: %w", err) + } + if reader.Len() != 0 { + return fmt.Errorf("prepared Ark transaction has %d "+ + "trailing bytes", reader.Len()) + } + txid := tx.TxHash() + if txid != chainhash.Hash(b.OORSessionID) || + b.OutPoint.Hash != txid { + return fmt.Errorf("VTXO outpoint does not belong to prepared " + + "OOR session") + } + if int(b.OutPoint.Index) >= len(tx.TxOut) { + return fmt.Errorf("VTXO output %d is out of range", + b.OutPoint.Index) + } + output := tx.TxOut[b.OutPoint.Index] + if output.Value != int64(b.Amount) || + !bytes.Equal(output.PkScript, b.PkScript) { + return fmt.Errorf("prepared Ark transaction output does not " + + "match VTXO binding") + } + if b.Amount < terms.Capacity { + return fmt.Errorf("VTXO amount %d is below channel capacity %d", + b.Amount, terms.Capacity) + } + policy, pkScript, err := terms.VTXO.Artifacts() + if err != nil { + return err + } + if !bytes.Equal(b.PolicyTemplate, policy) { + return fmt.Errorf("VTXO policy does not match channel terms") + } + if !bytes.Equal(b.PkScript, pkScript) { + return fmt.Errorf("VTXO script does not match channel terms") + } + + return nil +} + +// Backing identifies the fully signed VTXO-to-channel transaction. +type Backing struct { + Transaction []byte + ChannelPoint wire.OutPoint +} + +// Clone returns a backing record without aliases to transaction bytes. +func (b Backing) Clone() Backing { + b.Transaction = slices.Clone(b.Transaction) + + return b +} + +// Validate proves the signed transaction spends only the bound VTXO, executes +// the reconstructed channel spend path, and creates the expected-capacity lnd +// channel point. The funding output script is local lnd state and is not +// derivable from channel terms, so each endpoint must separately call +// BackingTemplate.ValidateFundingOutput before finalizing its reservation. +func (b Backing) Validate(terms Terms, source VTXOBinding) error { + if len(b.Transaction) == 0 { + return fmt.Errorf("signed backing transaction is required") + } + if err := source.Validate(terms); err != nil { + return err + } + + tx := wire.NewMsgTx(2) + reader := bytes.NewReader(b.Transaction) + if err := tx.Deserialize(reader); err != nil { + return fmt.Errorf("decode backing transaction: %w", err) + } + if reader.Len() != 0 { + return fmt.Errorf("backing transaction has %d trailing bytes", + reader.Len()) + } + if len(tx.TxIn) != 1 { + return fmt.Errorf("backing transaction must have one input") + } + if tx.TxIn[0].PreviousOutPoint != source.OutPoint { + return fmt.Errorf("backing transaction does not spend bound " + + "VTXO") + } + if len(tx.TxIn[0].Witness) == 0 { + return fmt.Errorf("backing transaction is not fully signed") + } + if b.ChannelPoint.Hash != tx.TxHash() { + return fmt.Errorf("channel point transaction ID does not match") + } + if int(b.ChannelPoint.Index) >= len(tx.TxOut) { + return fmt.Errorf("channel point output %d is out of range", + b.ChannelPoint.Index) + } + if tx.TxOut[b.ChannelPoint.Index].Value != int64(terms.Capacity) { + return fmt.Errorf("channel point value %d does not match "+ + "capacity %d", tx.TxOut[b.ChannelPoint.Index].Value, + terms.Capacity) + } + reservedSCID := lnwire.NewShortChanIDFromInt(terms.ReservedSCID) + if reservedSCID.TxPosition != uint16(b.ChannelPoint.Index) { + return fmt.Errorf("reserved SCID output %d does not match "+ + "channel point output %d", reservedSCID.TxPosition, + b.ChannelPoint.Index) + } + if err := verifyBackingWitness(tx, terms, source); err != nil { + return err + } + + return nil +} + +// Snapshot is the complete Ark-owned durable state for one channel. +type Snapshot struct { + Terms Terms + Phase Phase + OORPreparationStarted bool + Source *VTXOBinding + Backing *Backing + ClientFinalized bool + HubFinalized bool + OORFinalized bool + OORAborted bool + ClientRecoveryReady bool + HubRecoveryReady bool + SourceConflict *SourceConflict + BackingPublished bool + CooperativeCloseRequest *CooperativeCloseRequest + CooperativeClose *CooperativeClose + Failure string +} + +// Clone returns a snapshot without aliases to mutable fields. +func (s Snapshot) Clone() Snapshot { + s.Terms = s.Terms.Clone() + if s.Source != nil { + source := s.Source.Clone() + s.Source = &source + } + if s.Backing != nil { + backing := s.Backing.Clone() + s.Backing = &backing + } + if s.SourceConflict != nil { + conflict := *s.SourceConflict + s.SourceConflict = &conflict + } + if s.CooperativeCloseRequest != nil { + request := s.CooperativeCloseRequest.Clone() + s.CooperativeCloseRequest = &request + } + if s.CooperativeClose != nil { + settlement := s.CooperativeClose.Clone() + s.CooperativeClose = &settlement + } + + return s +} + +// SourceConflict records the first confirmed spend of any on-path ancestor +// watched for a channel-policy VTXO. The channel FSM retains this evidence so +// materialization and force close resume after a process restart. +type SourceConflict struct { + OutPoint wire.OutPoint + SpendingTxID chainhash.Hash +} + +// ReadyToCommitOOR reports whether both lnd endpoints and the signed backing +// are durable, allowing the prepared OOR transfer to cross its commit gate. +func (s Snapshot) ReadyToCommitOOR() bool { + return s.Source != nil && s.Backing != nil && s.ClientFinalized && + s.HubFinalized && s.Phase == PhaseBackingReady && + !s.OORFinalized && !s.OORAborted +} + +// RecoveryReady reports whether both endpoints independently installed the +// recovery package needed before virtual channel activation. +func (s Snapshot) RecoveryReady() bool { + return s.ClientRecoveryReady && s.HubRecoveryReady +} + +// validateNodeKey checks a compressed secp256k1 node key. +func validateNodeKey(name string, raw [33]byte) error { + if _, err := btcec.ParsePubKey(raw[:]); err != nil { + return fmt.Errorf("invalid %s node key: %w", name, err) + } + + return nil +} + +// parseChannelKey validates and parses one compressed policy key. +func parseChannelKey(name string, raw [33]byte) (*btcec.PublicKey, error) { + key, err := btcec.ParsePubKey(raw[:]) + if err != nil { + return nil, fmt.Errorf("invalid %s key: %w", name, err) + } + + return key, nil +} From 7b257f28e624e57a58dd1ba9cbdc10414aff9ad0 Mon Sep 17 00:00:00 2001 From: sputn1ck Date: Wed, 18 Nov 2026 18:48:40 +0100 Subject: [PATCH 4/7] arkchannel: Persist channel progress before dispatching effects Gate activation, closure and expiry on durable evidence. Resume the next action from that evidence after a process restart. --- arkchannel/backing_test.go | 185 +++ arkchannel/cooperative_close_test.go | 433 +++++++ arkchannel/coordinator.go | 359 ++++++ arkchannel/events.go | 303 +++++ arkchannel/funding_authorization.go | 141 +++ arkchannel/native_executor.go | 307 +++++ arkchannel/native_executor_test.go | 336 ++++++ arkchannel/progress.go | 41 + arkchannel/progress_test.go | 84 ++ arkchannel/recovery_test.go | 52 + arkchannel/service.go | 506 ++++++++ arkchannel/service_test.go | 543 +++++++++ arkchannel/source_expiry_test.go | 161 +++ arkchannel/source_lifetime_test.go | 156 +++ arkchannel/state.go | 1361 ++++++++++++++++++++++ arkchannel/state_test.go | 1604 ++++++++++++++++++++++++++ 16 files changed, 6572 insertions(+) create mode 100644 arkchannel/backing_test.go create mode 100644 arkchannel/cooperative_close_test.go create mode 100644 arkchannel/coordinator.go create mode 100644 arkchannel/events.go create mode 100644 arkchannel/funding_authorization.go create mode 100644 arkchannel/native_executor.go create mode 100644 arkchannel/native_executor_test.go create mode 100644 arkchannel/progress.go create mode 100644 arkchannel/progress_test.go create mode 100644 arkchannel/recovery_test.go create mode 100644 arkchannel/service.go create mode 100644 arkchannel/service_test.go create mode 100644 arkchannel/source_expiry_test.go create mode 100644 arkchannel/source_lifetime_test.go create mode 100644 arkchannel/state.go create mode 100644 arkchannel/state_test.go diff --git a/arkchannel/backing_test.go b/arkchannel/backing_test.go new file mode 100644 index 000000000..debfff226 --- /dev/null +++ b/arkchannel/backing_test.go @@ -0,0 +1,185 @@ +package arkchannel + +import ( + "bytes" + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/psbt/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/keychain" + "github.com/stretchr/testify/require" +) + +// TestBackingTemplateCompletesChannelSpend proves the backing transaction is +// a valid spend of the exact prepared OOR output into lnd's funding output. +func TestBackingTemplateCompletesChannelSpend(t *testing.T) { + t.Parallel() + + terms, source, clientKey, hubKey := testBackingTerms(t) + fundingOutput := &wire.TxOut{ + Value: int64(terms.Capacity), + PkScript: append( + []byte{txscript.OP_1, 32}, bytes.Repeat( + []byte{2}, 32, + )..., + ), + } + packet, err := psbt.New( + nil, []*wire.TxOut{fundingOutput}, 2, 0, nil, + ) + require.NoError(t, err) + + template, err := NewBackingTemplate(packet, terms, source) + require.NoError(t, err) + require.Equal( + t, source.OutPoint, + template.Transaction().TxIn[0].PreviousOutPoint, + ) + require.Equal(t, fundingOutput, + template.Transaction().TxOut[0]) + require.Equal( + t, template.Transaction().TxHash(), + template.ChannelPoint().Hash, + ) + require.NoError(t, template.ValidateFundingOutput(fundingOutput)) + + clientSig := signBacking(t, template, terms, PartyClient, clientKey) + hubSig := signBacking(t, template, terms, PartyHub, hubKey) + backing, err := template.Complete( + terms, source, clientSig, hubSig, + ) + require.NoError(t, err) + require.NoError(t, backing.Validate(terms, source)) + require.Equal(t, template.ChannelPoint(), backing.ChannelPoint) + + // A non-empty witness is not sufficient. Every accepted or restored + // backing must authenticate both channel-policy signers. + corrupt := backing.Clone() + tx := mustDecodeTransaction(t, corrupt.Transaction) + tx.TxIn[0].Witness[0][0] ^= 1 + corrupt.Transaction = serializeTx(t, tx) + require.ErrorContains( + t, corrupt.Validate(terms, source), + "verify channel backing signatures", + ) +} + +// TestBackingTemplateRejectsDifferentFundingOutput proves a peer cannot be +// induced to sign a backing transaction for a different lnd reservation. +func TestBackingTemplateRejectsDifferentFundingOutput(t *testing.T) { + t.Parallel() + + terms, source, _, _ := testBackingTerms(t) + fundingOutput := &wire.TxOut{ + Value: int64(terms.Capacity), + PkScript: append( + []byte{txscript.OP_1, 32}, bytes.Repeat( + []byte{3}, 32, + )..., + ), + } + packet, err := psbt.New( + nil, []*wire.TxOut{fundingOutput}, 2, 0, nil, + ) + require.NoError(t, err) + template, err := NewBackingTemplate(packet, terms, source) + require.NoError(t, err) + + differentScript := &wire.TxOut{ + Value: fundingOutput.Value, + PkScript: bytes.Clone(fundingOutput.PkScript), + } + differentScript.PkScript[len(differentScript.PkScript)-1] ^= 1 + require.ErrorContains( + t, template.ValidateFundingOutput(differentScript), + "does not fund the local lnd reservation", + ) + + differentAmount := &wire.TxOut{ + Value: fundingOutput.Value, + PkScript: bytes.Clone(fundingOutput.PkScript), + } + differentAmount.Value-- + require.ErrorContains( + t, template.ValidateFundingOutput(differentAmount), + "does not fund the local lnd reservation", + ) +} + +// TestBackingTemplateRejectsWrongChannelKey proves role signatures cannot be +// substituted with an unrelated Ark or Lightning key. +func TestBackingTemplateRejectsWrongChannelKey(t *testing.T) { + t.Parallel() + + terms, source, _, _ := testBackingTerms(t) + channelScript := append( + []byte{txscript.OP_1, 32}, make([]byte, 32)..., + ) + packet, err := psbt.New(nil, []*wire.TxOut{{ + Value: int64(terms.Capacity), + PkScript: channelScript, + }}, 2, 0, nil) + require.NoError(t, err) + template, err := NewBackingTemplate(packet, terms, source) + require.NoError(t, err) + + wrongKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + _, err = template.SignDescriptor( + terms, PartyClient, keychain.KeyDescriptor{ + PubKey: wrongKey.PubKey(), + }, + ) + require.ErrorContains(t, err, "does not match client channel key") +} + +// testBackingTerms creates channel terms whose materialization keys are +// available to this test. +func testBackingTerms(t *testing.T) (Terms, VTXOBinding, *btcec.PrivateKey, + *btcec.PrivateKey) { + + t.Helper() + + terms := testTerms(t, KindPromotion) + clientKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + hubKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + terms.VTXO.ClientChannelKey = compressedKey(clientKey) + terms.VTXO.HubChannelKey = compressedKey(hubKey) + + return terms, testBinding(terms), clientKey, hubKey +} + +// compressedKey converts a private key to the durable channel key encoding. +func compressedKey(key *btcec.PrivateKey) [33]byte { + var serialized [33]byte + copy(serialized[:], key.PubKey().SerializeCompressed()) + + return serialized +} + +// signBacking signs one endpoint's tapscript branch with lnd's signer API. +func signBacking(t *testing.T, template *BackingTemplate, terms Terms, + party Party, key *btcec.PrivateKey) input.Signature { + + t.Helper() + + desc, err := template.SignDescriptor( + terms, party, keychain.KeyDescriptor{ + PubKey: key.PubKey(), + }, + ) + require.NoError(t, err) + sig, err := input.NewMockSigner( + []*btcec.PrivateKey{key}, nil, + ).SignOutputRaw( + template.Packet().UnsignedTx, desc, + ) + require.NoError(t, err) + + return sig +} diff --git a/arkchannel/cooperative_close_test.go b/arkchannel/cooperative_close_test.go new file mode 100644 index 000000000..2e34a17d6 --- /dev/null +++ b/arkchannel/cooperative_close_test.go @@ -0,0 +1,433 @@ +package arkchannel + +import ( + "bytes" + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/lib/arkscript" + "github.com/lightninglabs/wavelength/lib/tx/psbtutil" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/keychain" + "github.com/stretchr/testify/require" +) + +// TestCooperativeCloseDeliveryPolicyAgreement requires both quoted destinations +// to bind the same session, including when one wallet is still on old terms. +func TestCooperativeCloseDeliveryPolicyAgreement(t *testing.T) { + t.Parallel() + terms, _, request, _, _, prior := testCooperativeCloseFixture( + t, KindPromotion, 5_000, + ) + next, err := btcec.NewPrivateKey() + require.NoError(t, err) + client, err := CooperativeCloseDeliveryOwner( + request.ClientDeliveryScript, + ) + require.NoError(t, err) + hub, err := CooperativeCloseDeliveryOwner(request.HubDeliveryScript) + require.NoError(t, err) + delay := terms.VTXO.MinExitDelay + encode := arkscript.EncodeStandardVTXOTemplate + request.ClientDeliveryScript, err = encode( + client, next.PubKey(), delay, + ) + require.NoError(t, err) + require.ErrorContains(t, request.Validate(), "policies differ") + for _, tc := range []struct { + key *btcec.PublicKey + delay uint32 + match bool + }{ + { + prior.PubKey(), + delay, + false, + }, + { + next.PubKey(), + delay + 1, + false, + }, + { + next.PubKey(), + delay, + true, + }, + } { + request.HubDeliveryScript, err = encode( + hub, tc.key, tc.delay, + ) + require.NoError(t, err) + if tc.match { + require.NoError(t, request.Validate()) + } else { + require.ErrorContains( + t, request.Validate(), + "policies differ", + ) + } + } +} + +// TestCooperativeCloseBuildsThreePartyOOR proves the no-delay 3-of-3 policy +// authorizes an ordinary OOR transfer that preserves full-capacity role +// balances and never spends the unpublished channel point. +func TestCooperativeCloseBuildsThreePartyOOR(t *testing.T) { + t.Parallel() + + terms, source, request, clientKey, hubKey, _ := + testCooperativeCloseFixture(t, KindPromotion, 5_000) + const ( + clientBalance = btcutil.Amount(63_000) + hubBalance = btcutil.Amount(37_000) + ) + template, err := NewCooperativeCloseTemplate( + terms, source, request, clientBalance, hubBalance, 7, + ) + require.NoError(t, err) + proposal := template.Proposal() + require.NoError(t, proposal.Validate(terms, source, request)) + require.Equal( + t, terms.Capacity, proposal.ClientBalance+proposal.HubBalance, + ) + require.Equal( + t, source.Amount, proposal.ClientOutput+proposal.HubOutput, + ) + require.Equal(t, clientBalance+5_000, proposal.ClientOutput) + require.Equal(t, hubBalance, proposal.HubOutput) + + checkpoint, err := psbtutil.Parse(proposal.Transaction) + require.NoError(t, err) + require.Equal( + t, source.OutPoint, + checkpoint.UnsignedTx.TxIn[0].PreviousOutPoint, + ) + require.NotEqual( + t, testBacking(t, terms, source).ChannelPoint, + checkpoint.UnsignedTx.TxIn[0].PreviousOutPoint, + ) + require.Equal( + t, wire.MaxTxInSequenceNum, + checkpoint.UnsignedTx.TxIn[0].Sequence, + ) + + clientSig := signCooperativeClose( + t, template, terms, PartyClient, clientKey, + ) + require.NoError( + t, template.VerifySignature(terms, PartyClient, clientSig), + ) + hubSig := signCooperativeClose( + t, template, terms, PartyHub, hubKey, + ) + require.NoError(t, template.VerifySignature(terms, PartyHub, hubSig)) + require.ErrorContains( + t, template.VerifySignature(terms, PartyClient, hubSig), + "invalid client cooperative close signature", + ) + + hubArkSig := signCooperativeCloseArk(t, template, terms, hubKey) + settlement, err := template.Complete( + terms, source, request, hubSig, hubArkSig, + ) + require.NoError(t, err) + require.NoError(t, settlement.Validate(terms, source, request)) + checkpointSig, payoutSig, err := settlement.Signatures() + require.NoError(t, err) + require.Equal(t, hubSig.Serialize(), checkpointSig.Serialize()) + require.Equal(t, hubArkSig.Serialize(), payoutSig.Serialize()) + require.NotEqual(t, source.OutPoint.Hash, settlement.TxID) + clientOutpoint, err := settlement.ReplacementOutPoint( + terms, source, request, PartyClient, + ) + require.NoError(t, err) + hubOutpoint, err := settlement.ReplacementOutPoint( + terms, source, request, PartyHub, + ) + require.NoError(t, err) + require.Equal(t, settlement.TxID, clientOutpoint.Hash) + require.Equal(t, settlement.TxID, hubOutpoint.Hash) + require.NotEqual(t, clientOutpoint, hubOutpoint) + _, err = settlement.ReplacementOutPoint( + terms, source, request, Party(99), + ) + require.ErrorContains(t, err, "unknown cooperative close party") + + spec, err := template.OORSpec() + require.NoError(t, err) + require.Len(t, spec.Recipients, 2) + path, err := arkscript.DecodeSpendPath(spec.SpendPath) + require.NoError(t, err) + require.Equal(t, wire.MaxTxInSequenceNum, path.RequiredSequence) +} + +// TestCooperativeCloseAuthorizationBindsFinalPayout proves a checkpoint +// authorization cannot be reused to redirect the hub's agreed allocation. +func TestCooperativeCloseAuthorizationBindsFinalPayout(t *testing.T) { + t.Parallel() + + terms, source, request, _, hubKey, _ := testCooperativeCloseFixture( + t, KindPromotion, 5_000, + ) + template, err := NewCooperativeCloseTemplate( + terms, source, request, 60_000, 40_000, 7, + ) + require.NoError(t, err) + checkpointSig := signCooperativeClose( + t, template, terms, PartyHub, hubKey, + ) + arkSig := signCooperativeCloseArk(t, template, terms, hubKey) + settlement, err := template.Complete( + terms, source, request, checkpointSig, arkSig, + ) + require.NoError(t, err) + redirected, err := NewCooperativeCloseTemplate( + terms, source, request, terms.Capacity, 0, 7, + ) + require.NoError(t, err) + // The checkpoint alone still verifies: it does not commit recipients. + require.NoError( + t, redirected.VerifySignature(terms, PartyHub, checkpointSig), + ) + require.Error(t, redirected.VerifyArkSignature(terms, PartyHub, arkSig)) + settlement.Proposal = redirected.Proposal() + settlement.TxID = redirected.ArkTransaction().TxHash() + require.ErrorContains( + t, settlement.Validate(terms, source, request), + "payout authorization", + ) + + // Reject old checkpoint-only artifacts rather than silently treating + // missing payout authorization as consent to spend. + settlement.Proposal = template.Proposal() + settlement.TxID = template.ArkTransaction().TxHash() + settlement.Transaction = checkpointSig.Serialize() + require.Error(t, settlement.Validate(terms, source, request)) +} + +// TestCooperativeCloseReturnsReserveToClientFunder verifies the backing reserve +// never changes the full-capacity role allocation and follows the funder. +func TestCooperativeCloseReturnsReserveToClientFunder(t *testing.T) { + t.Parallel() + + terms, source, request, _, _, _ := testCooperativeCloseFixture( + t, KindPromotion, 4_000, + ) + template, err := NewCooperativeCloseTemplate( + terms, source, request, 25_000, 75_000, 11, + ) + require.NoError(t, err) + proposal := template.Proposal() + require.EqualValues(t, 29_000, proposal.ClientOutput) + require.Equal(t, btcutil.Amount(75_000), proposal.HubOutput) +} + +// TestCooperativeCloseRequiresFullCapacityRoleBalances proves core neither +// infers nor assigns a balance shortfall supplied by the runtime. +func TestCooperativeCloseRequiresFullCapacityRoleBalances(t *testing.T) { + t.Parallel() + + terms, source, request, _, _, _ := testCooperativeCloseFixture( + t, KindPromotion, 2_000, + ) + _, err := NewCooperativeCloseTemplate( + terms, source, request, 39_000, 60_000, 4, + ) + require.ErrorContains(t, err, "do not match capacity") +} + +// TestCooperativeCloseRejectsUnsafeSettlement verifies peers cannot alter a +// replacement amount or omit the backing reserve. +func TestCooperativeCloseRejectsUnsafeSettlement(t *testing.T) { + t.Parallel() + + terms, source, request, _, _, _ := testCooperativeCloseFixture( + t, KindPromotion, 2_000, + ) + template, err := NewCooperativeCloseTemplate( + terms, source, request, 40_000, 60_000, 4, + ) + require.NoError(t, err) + changed := template.Proposal() + changed.ClientOutput++ + require.ErrorContains( + t, changed.Validate(terms, source, request), + "not canonical", + ) + + smallTemplate, err := NewCooperativeCloseTemplate( + terms, source, request, terms.Capacity-1, 1, 4, + ) + require.NoError(t, err) + smallProposal := smallTemplate.Proposal() + require.EqualValues(t, 1, smallProposal.HubOutput) + require.Equal( + t, source.Amount, + smallProposal.ClientOutput+smallProposal.HubOutput, + ) + + tooSmall := resizeCooperativeCloseSource(t, source, terms.Capacity) + _, err = NewCooperativeCloseTemplate( + terms, tooSmall, request, 40_000, 60_000, 4, + ) + require.ErrorContains(t, err, "no backing reserve") +} + +// TestCooperativeCloseRejectsWrongPolicyKey verifies role checking happens +// before a signature request reaches the wallet signer. +func TestCooperativeCloseRejectsWrongPolicyKey(t *testing.T) { + t.Parallel() + + terms, source, request, _, _, _ := testCooperativeCloseFixture( + t, KindPromotion, 2_000, + ) + template, err := NewCooperativeCloseTemplate( + terms, source, request, 50_000, 50_000, 1, + ) + require.NoError(t, err) + wrongKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + _, err = template.SignDescriptor( + terms, PartyClient, keychain.KeyDescriptor{ + PubKey: wrongKey.PubKey(), + }, + ) + require.ErrorContains(t, err, "does not match policy role") +} + +// testCooperativeCloseFixture creates terms and source with all immediate +// cooperative policy keys available to the test. +func testCooperativeCloseFixture(t *testing.T, kind Kind, + reserve btcutil.Amount) (Terms, VTXOBinding, CooperativeCloseRequest, + *btcec.PrivateKey, *btcec.PrivateKey, *btcec.PrivateKey) { + + t.Helper() + terms := testTerms(t, kind) + clientKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + hubKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + operatorKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + terms.VTXO.ClientArkKey = compressedKey(clientKey) + terms.VTXO.HubArkKey = compressedKey(hubKey) + terms.VTXO.ArkOperatorKey = compressedKey(operatorKey) + source := resizeCooperativeCloseSource( + t, testBinding(terms), terms.Capacity+reserve, + ) + request := CooperativeCloseRequest{ + Initiator: PartyClient, + ClientDeliveryScript: testCooperativeOwnerKey(1), + HubDeliveryScript: testCooperativeOwnerKey(2), + } + + return terms, source, request, clientKey, hubKey, operatorKey +} + +// resizeCooperativeCloseSource changes the prepared output amount and keeps its +// transaction ID and outpoint binding canonical. +func resizeCooperativeCloseSource(t *testing.T, source VTXOBinding, + amount btcutil.Amount) VTXOBinding { + + t.Helper() + tx := mustDecodeTransaction(t, source.ArkTransaction) + tx.TxOut[source.OutPoint.Index].Value = int64(amount) + var raw bytes.Buffer + require.NoError(t, tx.Serialize(&raw)) + txid := tx.TxHash() + source.OORSessionID = [32]byte(txid) + source.OutPoint.Hash = txid + source.Amount = amount + source.ArkTransaction = raw.Bytes() + + return source +} + +// testCooperativeOwnerKey returns a deterministic compressed account key. +func testCooperativeOwnerKey(tag byte) []byte { + _, key := btcec.PrivKeyFromBytes(bytes.Repeat([]byte{tag}, 32)) + + return key.SerializeCompressed() +} + +// signCooperativeClose signs one endpoint role with its Ark policy key. +func signCooperativeClose(t *testing.T, template *CooperativeCloseTemplate, + terms Terms, party Party, key *btcec.PrivateKey) input.Signature { + + t.Helper() + desc, err := template.SignDescriptor( + terms, party, keychain.KeyDescriptor{ + PubKey: key.PubKey(), + }, + ) + require.NoError(t, err) + sig, err := input.NewMockSigner( + []*btcec.PrivateKey{key}, nil, + ).SignOutputRaw( + mustDecodeCheckpoint(t, template.Proposal().Transaction), desc, + ) + require.NoError(t, err) + + return sig +} + +// completeTestCooperativeClose records the hub's 3-of-3 OOR authorization. +// The unused keys remain in the helper signature because state tests share the +// full policy fixture. +func completeTestCooperativeClose(t *testing.T, + template *CooperativeCloseTemplate, terms Terms, source VTXOBinding, + request CooperativeCloseRequest, _, hubKey, + _ *btcec.PrivateKey) CooperativeClose { + + t.Helper() + hubSig := signCooperativeClose( + t, template, terms, PartyHub, hubKey, + ) + settlement, err := template.Complete( + terms, source, request, hubSig, + signCooperativeCloseArk(t, template, terms, hubKey), + ) + require.NoError(t, err) + + return settlement +} + +// signCooperativeCloseArk authorizes the exact payout transaction. +func signCooperativeCloseArk(t *testing.T, template *CooperativeCloseTemplate, + terms Terms, key *btcec.PrivateKey) input.Signature { + + t.Helper() + desc, err := template.ArkSignDescriptor( + terms, PartyHub, keychain.KeyDescriptor{ + PubKey: key.PubKey(), + }, + ) + require.NoError(t, err) + sig, err := input.NewMockSigner( + []*btcec.PrivateKey{key}, nil, + ).SignOutputRaw(template.ArkTransaction(), desc) + require.NoError(t, err) + + return sig +} + +// mustDecodeTransaction decodes a raw transaction fixture. +func mustDecodeTransaction(t *testing.T, raw []byte) *wire.MsgTx { + t.Helper() + tx := wire.NewMsgTx(2) + require.NoError(t, tx.Deserialize(bytes.NewReader(raw))) + + return tx +} + +// mustDecodeCheckpoint returns an unsigned checkpoint transaction. +func mustDecodeCheckpoint(t *testing.T, raw []byte) *wire.MsgTx { + t.Helper() + packet, err := psbtutil.Parse(raw) + require.NoError(t, err) + + return packet.UnsignedTx +} diff --git a/arkchannel/coordinator.go b/arkchannel/coordinator.go new file mode 100644 index 000000000..3fc2afb57 --- /dev/null +++ b/arkchannel/coordinator.go @@ -0,0 +1,359 @@ +package arkchannel + +import ( + "context" + "errors" + "fmt" + "sync" + "time" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" +) + +var ( + // ErrNotFound indicates that a channel ID is not registered. + ErrNotFound = errors.New("ark channel not found") + + // ErrConflict indicates that another worker advanced the channel first. + ErrConflict = errors.New("ark channel revision conflict") + + // ErrOORPreparationAmbiguous means the prepared-transfer request may + // have reached its durable actor even though the caller did not receive + // the resulting binding. The channel must remain recoverable until a + // keyed lookup either reconstructs and aborts that transfer or + // preparation succeeds. + ErrOORPreparationAmbiguous = errors.New("ark channel OOR preparation " + + "outcome is ambiguous") +) + +const maxCASAttempts = 8 + +// Record wraps a snapshot with its compare-and-swap revision. +type Record struct { + Snapshot Snapshot + Revision uint64 + CreatedAt time.Time + UpdatedAt time.Time + PrePONRStartedAt time.Time + + // AuthorizedBackingTxID is local signing evidence, not a peer fact. + AuthorizedBackingTxID *chainhash.Hash + + // FundingSignature is the local signature released for that exact txid. + FundingSignature []byte +} + +// PendingWork pairs a durable record with its replayable side effect. +type PendingWork struct { + Record Record + Action Action +} + +// Store persists one canonical Ark coordination record per channel. +type Store interface { + Create(context.Context, Snapshot) (Record, error) + + Get(context.Context, ID) (Record, error) + + GetByPendingChannelID(context.Context, [32]byte) (Record, error) + + GetByChannelPoint(context.Context, wire.OutPoint) (Record, error) + + ListNonTerminal(context.Context) ([]Record, error) + + CompareAndSwap(context.Context, ID, uint64, Snapshot) (Record, error) +} + +// RecordObserver projects already-durable channel facts into ancillary state. +// Observers must fail safe internally because they cannot veto an FSM commit. +type RecordObserver interface { + ObserveArkChannel(context.Context, Record) +} + +// Coordinator persists transitions before returning replayable side effects. +type Coordinator struct { + store Store + observers []RecordObserver + + changesMu sync.Mutex + changes map[ID]map[chan struct{}]struct{} +} + +// NewCoordinator constructs a durable Ark-channel coordinator. +func NewCoordinator(store Store, + observers ...RecordObserver) (*Coordinator, error) { + + if store == nil { + return nil, fmt.Errorf("channel store is required") + } + for _, observer := range observers { + if observer == nil { + return nil, fmt.Errorf("channel record observer is " + + "required") + } + } + + return &Coordinator{store: store, observers: observers}, nil +} + +// Request registers immutable terms idempotently. +func (c *Coordinator) Request(ctx context.Context, terms Terms) (Record, + error) { + + state, err := NewState(terms) + if err != nil { + return Record{}, err + } + existing, err := c.store.GetByPendingChannelID( + ctx, terms.PendingChannelID, + ) + switch { + case err == nil: + if existing.Snapshot.Terms.ID != terms.ID { + return Record{}, fmt.Errorf("pending channel ID " + + "already belongs to another Ark channel") + } + if err := sameTerms( + existing.Snapshot.Terms, terms, + ); err != nil { + return Record{}, err + } + + return existing, nil + + case !errors.Is(err, ErrNotFound): + return Record{}, err + } + + record, err := c.store.Create(ctx, state.Snapshot()) + if err == nil { + c.observe(ctx, record) + c.notifyChannelChanged(terms.ID) + + return record, nil + } + if !errors.Is(err, ErrConflict) { + return Record{}, err + } + + existing, getErr := c.store.Get(ctx, terms.ID) + if getErr != nil { + return Record{}, getErr + } + if err := sameTerms(existing.Snapshot.Terms, terms); err != nil { + return Record{}, err + } + + return existing, nil +} + +// Get loads one durable channel record. +func (c *Coordinator) Get(ctx context.Context, id ID) (Record, error) { + return c.store.Get(ctx, id) +} + +// ListNonTerminal loads channels that still need recovery or observation, +// including closed cooperative channels with a source-defense obligation. +func (c *Coordinator) ListNonTerminal(ctx context.Context) ([]Record, error) { + return c.store.ListNonTerminal(ctx) +} + +// FindByPendingChannelID resolves a live channel intent for lnd's inbound +// funding acceptor. Pending channel IDs are immutable and may identify only +// one non-terminal Ark workflow. +func (c *Coordinator) FindByPendingChannelID(ctx context.Context, + pendingID [32]byte) (Record, error) { + + return c.store.GetByPendingChannelID(ctx, pendingID) +} + +// FindByChannelPoint resolves the durable backing record observed by lnd's +// pending-channel lifecycle. +func (c *Coordinator) FindByChannelPoint(ctx context.Context, + channelPoint wire.OutPoint) (Record, error) { + + return c.store.GetByChannelPoint(ctx, channelPoint) +} + +// Apply durably applies one event and then returns any side effect to execute. +func (c *Coordinator) Apply(ctx context.Context, id ID, event Event) (Record, + []Action, error) { + + for range maxCASAttempts { + record, err := c.store.Get(ctx, id) + if err != nil { + return Record{}, nil, err + } + + state, err := RestoreState(record.Snapshot) + if err != nil { + return Record{}, nil, err + } + transition, err := state.ProcessEvent( + ctx, event, &Environment{ + ChannelID: id, + }, + ) + if err != nil { + return Record{}, nil, err + } + + nextState, ok := transition.NextState.(State) + if !ok { + return Record{}, nil, fmt.Errorf("unexpected next "+ + "state %T", transition.NextState) + } + next := nextState.Snapshot() + if snapshotsEqual(record.Snapshot, next) { + c.observe(ctx, record) + + return record, emittedActions(transition), nil + } + + updated, err := c.store.CompareAndSwap( + ctx, id, record.Revision, next, + ) + if errors.Is(err, ErrConflict) { + continue + } + if err != nil { + return Record{}, nil, err + } + c.observe(ctx, updated) + c.notifyChannelChanged(id) + + return updated, emittedActions(transition), nil + } + + return Record{}, nil, fmt.Errorf("advance channel %x: %w", id[:4], + ErrConflict) +} + +// observe notifies best-effort projections only after the channel row commits. +func (c *Coordinator) observe(ctx context.Context, record Record) { + for _, observer := range c.observers { + observer.ObserveArkChannel(ctx, record) + } +} + +// Resume returns the idempotent action implied by already-durable state. +func (c *Coordinator) Resume(ctx context.Context, id ID) (Record, []Action, + error) { + + record, err := c.store.Get(ctx, id) + if err != nil { + return Record{}, nil, err + } + action, err := PendingAction(record.Snapshot) + if err != nil { + return Record{}, nil, err + } + if action == nil { + return record, nil, nil + } + + return record, []Action{action}, nil +} + +// ResumeAll loads resumable records and returns their replayable work. +func (c *Coordinator) ResumeAll(ctx context.Context) ([]PendingWork, error) { + records, err := c.store.ListNonTerminal(ctx) + if err != nil { + return nil, err + } + + work := make([]PendingWork, 0, len(records)) + for _, record := range records { + action, err := PendingAction(record.Snapshot) + if err != nil { + return nil, err + } + if action == nil { + continue + } + + work = append(work, PendingWork{ + Record: record, + Action: action, + }) + } + + return work, nil +} + +// emittedActions extracts the transition outbox after its state is durable. +func emittedActions(transition *StateTransition) []Action { + if transition.NewEvents.IsNone() { + return nil + } + + emitted := transition.NewEvents.UnsafeFromSome() + + return emitted.Outbox +} + +// sameTerms rejects reuse of an ID for different immutable terms. +func sameTerms(a, b Terms) error { + if a != b { + return fmt.Errorf("channel ID already has different terms") + } + + return nil +} + +// snapshotsEqual detects idempotent events without writing a new revision. +func snapshotsEqual(a, b Snapshot) bool { + if err := sameTerms(a.Terms, b.Terms); err != nil { + return false + } + if a.Phase != b.Phase || + a.OORPreparationStarted != b.OORPreparationStarted || + a.ClientFinalized != b.ClientFinalized || + a.HubFinalized != b.HubFinalized || + a.OORFinalized != b.OORFinalized || + a.OORAborted != b.OORAborted || + a.ClientRecoveryReady != b.ClientRecoveryReady || + a.HubRecoveryReady != b.HubRecoveryReady || + a.BackingPublished != b.BackingPublished || + a.Failure != b.Failure { + return false + } + if (a.Source == nil) != (b.Source == nil) || + (a.Backing == nil) != (b.Backing == nil) { + return false + } + if a.Source != nil && !bindingsEqual(*a.Source, *b.Source) { + return false + } + if a.Backing != nil && !backingsEqual(*a.Backing, *b.Backing) { + return false + } + if (a.SourceConflict == nil) != (b.SourceConflict == nil) { + return false + } + if a.SourceConflict != nil && + (a.SourceConflict.OutPoint != b.SourceConflict.OutPoint || + a.SourceConflict.SpendingTxID != + b.SourceConflict.SpendingTxID) { + return false + } + if (a.CooperativeCloseRequest == nil) != + (b.CooperativeCloseRequest == nil) || + (a.CooperativeClose == nil) != (b.CooperativeClose == nil) { + return false + } + if a.CooperativeCloseRequest != nil && + !cooperativeCloseRequestsEqual( + *a.CooperativeCloseRequest, *b.CooperativeCloseRequest, + ) { + return false + } + if a.CooperativeClose != nil && !cooperativeClosesEqual( + *a.CooperativeClose, *b.CooperativeClose, + ) { + return false + } + + return true +} diff --git a/arkchannel/events.go b/arkchannel/events.go new file mode 100644 index 000000000..09f6916e9 --- /dev/null +++ b/arkchannel/events.go @@ -0,0 +1,303 @@ +package arkchannel + +import ( + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" +) + +// Event is a closed set of durable Ark-channel facts. +type Event interface { + eventSealed() +} + +// OORPreparationStarted records that the funder may now reserve wallet VTXOs +// for this channel. Persisting this fact before selection makes an interrupted +// preparation discoverable after a restart. +type OORPreparationStarted struct{} + +func (*OORPreparationStarted) eventSealed() {} + +// ExpirePrePONR abandons an armed channel only while its OOR commit action +// cannot have started. Replaying a stale expiry after the commit gate is a +// durable no-op rather than a generic failure. +type ExpirePrePONR struct { + Reason string +} + +func (*ExpirePrePONR) eventSealed() {} + +// BindVTXO records the exact output of a durable prepared OOR transfer. +type BindVTXO struct { + Binding VTXOBinding +} + +func (*BindVTXO) eventSealed() {} + +// FundingFinalized records that one endpoint's native lnd funding manager has +// persisted both initial commitments. +type FundingFinalized struct { + Party Party +} + +func (*FundingFinalized) eventSealed() {} + +// BackingSigned records the fully signed VTXO-to-channel transaction. +type BackingSigned struct { + Backing Backing +} + +func (*BackingSigned) eventSealed() {} + +// FundingCanceled records that lnd removed the abandoned pending channel. +type FundingCanceled struct{} + +func (*FundingCanceled) eventSealed() {} + +// OORFinalized records that the prepared OOR transfer completed at the Ark +// operator and the channel-policy VTXO now exists. +type OORFinalized struct { + SessionID [32]byte +} + +func (*OORFinalized) eventSealed() {} + +// RecoveryPackageInstalled records that one endpoint installed and watches the +// complete source ancestry and OOR package chain. +type RecoveryPackageInstalled struct { + Party Party +} + +func (*RecoveryPackageInstalled) eventSealed() {} + +// OORAborted records a definitive pre-PONR OOR failure. It proves the source +// reservation is safe to release and permits the pending lnd channel to be +// canceled. +type OORAborted struct { + SessionID [32]byte + Reason string +} + +func (*OORAborted) eventSealed() {} + +// ChannelActive records that native lnd activated the expected channel point. +type ChannelActive struct { + ChannelPointHash chainhash.Hash + ChannelPointIndex uint32 +} + +func (*ChannelActive) eventSealed() {} + +// Materialize requests publication of the VTXO ancestry and backing. It may +// supersede a cooperative close only before both endpoints acknowledge the +// close artifact; after that point only exact backing chain evidence may do so. +type Materialize struct{} + +func (*Materialize) eventSealed() {} + +// SourceExpiring records that authenticated source lifetime has reached the +// local recovery deadline. Unlike an ordinary close request, it also protects +// a finalized source whose peer has not finished activation. +type SourceExpiring struct{} + +func (*SourceExpiring) eventSealed() {} + +// CooperativeCloseObserved records local confirmation of the exact authorized +// payout. Once expiry starts a competing exit, an off-chain receipt alone may +// not retire the native breach and commitment watchers. +type CooperativeCloseObserved struct { + TxID chainhash.Hash +} + +func (*CooperativeCloseObserved) eventSealed() {} + +// SourceSpent records confirmed chain evidence that one of the channel +// source's on-path ancestors was spent. +type SourceSpent struct { + OutPoint wire.OutPoint + SpendingTxID chainhash.Hash +} + +func (*SourceSpent) eventSealed() {} + +// BackingPublished records publication of the expected backing transaction. +type BackingPublished struct { + TxID chainhash.Hash +} + +func (*BackingPublished) eventSealed() {} + +// BackingObserved records independent chain evidence for the expected backing +// transaction. It lets lnd resolution supersede an unfinished off-chain close +// without accepting a peer's claim as proof of publication. +type BackingObserved struct { + TxID chainhash.Hash +} + +func (*BackingObserved) eventSealed() {} + +// ChannelClosed records completion of lnd's channel lifecycle. +type ChannelClosed struct{} + +func (*ChannelClosed) eventSealed() {} + +// RequestCooperativeClose fixes the replacement VTXO owners before either lnd +// endpoint stops accepting new HTLCs. +type RequestCooperativeClose struct { + Request CooperativeCloseRequest +} + +func (*RequestCooperativeClose) eventSealed() {} + +// CooperativeCloseSigned records the exact locally validated hub authorization. +type CooperativeCloseSigned struct { + Close CooperativeClose +} + +func (*CooperativeCloseSigned) eventSealed() {} + +// CooperativeCloseReady records the client's durable receipt of the exact +// authorization, the last barrier before OOR submission can start. +type CooperativeCloseReady struct { + Receipt chainhash.Hash +} + +func (*CooperativeCloseReady) eventSealed() {} + +// CooperativeClosePublished records finalization of the exact ordinary OOR +// close. The historical type name is retained for durable compatibility. +type CooperativeClosePublished struct { + TxID chainhash.Hash +} + +func (*CooperativeClosePublished) eventSealed() {} + +// CooperativeCloseFinalized records that one endpoint archived its lnd +// channel after the OOR close finalized. +type CooperativeCloseFinalized struct{} + +func (*CooperativeCloseFinalized) eventSealed() {} + +// CooperativeCloseAborted returns a pre-signature close attempt to the active +// phase and permits both lnd links to resume traffic. +type CooperativeCloseAborted struct{} + +func (*CooperativeCloseAborted) eventSealed() {} + +// Fail abandons negotiation before the OOR commit action becomes replayable. +type Fail struct { + Reason string +} + +func (*Fail) eventSealed() {} + +// Action is side effect requested after its producing state is durable. +type Action interface { + actionSealed() +} + +// NegotiateFunding asks native lnd to negotiate against the bound VTXO. +type NegotiateFunding struct { + Terms Terms + Source VTXOBinding +} + +func (*NegotiateFunding) actionSealed() {} + +// CommitOOR releases signing and transport for the prepared transfer only +// after both lnd endpoints have durably stored their initial commitments. +type CommitOOR struct { + Terms Terms + Source VTXOBinding +} + +func (*CommitOOR) actionSealed() {} + +// PrepareRecovery installs the finalized source package at both endpoints +// before either native lnd channel may activate. +type PrepareRecovery struct { + Terms Terms + Source VTXOBinding +} + +func (*PrepareRecovery) actionSealed() {} + +// AbortOOR releases the source VTXO reservation before canceling native lnd +// funding. +type AbortOOR struct { + Terms Terms + Source VTXOBinding + Reason string +} + +func (*AbortOOR) actionSealed() {} + +// ActivateChannel asks the virtual notifier to confirm the backing to lnd. +type ActivateChannel struct { + Terms Terms + Backing Backing +} + +func (*ActivateChannel) actionSealed() {} + +// CancelFunding asks the native funding adapter to remove an abandoned lnd +// reservation before the Ark workflow becomes terminal. +type CancelFunding struct { + Terms Terms + Source VTXOBinding + Backing *Backing + Reason string +} + +func (*CancelFunding) actionSealed() {} + +// PublishChannel first hands the channel to lnd's on-chain lifecycle, then +// publishes ancestry before the backing from either recovery-ready endpoint. +type PublishChannel struct { + Terms Terms + Source VTXOBinding + Backing Backing +} + +func (*PublishChannel) actionSealed() {} + +// ForceCloseChannel asks native lnd to publish its latest commitment after +// the backing transaction is on chain. +type ForceCloseChannel struct { + Backing Backing +} + +func (*ForceCloseChannel) actionSealed() {} + +// NegotiateCooperativeClose quiesces both lnd endpoints and records the hub's +// signature for an immediate 3-of-3 OOR checkpoint spend. +type NegotiateCooperativeClose struct { + Terms Terms + Source VTXOBinding + Backing Backing + Request CooperativeCloseRequest +} + +func (*NegotiateCooperativeClose) actionSealed() {} + +// PublishCooperativeClose asks the client-owned ordinary OOR actor to settle +// the authorized 3-of-3 close. The historical action name is retained for +// durable compatibility. +type PublishCooperativeClose struct { + Terms Terms + Source VTXOBinding + Close CooperativeClose +} + +func (*PublishCooperativeClose) actionSealed() {} + +// FinalizeCooperativeClose archives the local lnd channel after the direct +// settlement confirmed. +type FinalizeCooperativeClose struct { + Terms Terms + Source VTXOBinding + Backing Backing + Request CooperativeCloseRequest + Close CooperativeClose +} + +func (*FinalizeCooperativeClose) actionSealed() {} diff --git a/arkchannel/funding_authorization.go b/arkchannel/funding_authorization.go new file mode 100644 index 000000000..010d0a27b --- /dev/null +++ b/arkchannel/funding_authorization.go @@ -0,0 +1,141 @@ +package arkchannel + +import ( + "bytes" + "context" + "errors" + "fmt" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" +) + +// FundingAuthorizationStore claims the first backing at a validated intent +// revision. Ordinary FSM updates must never overwrite this local evidence. +type FundingAuthorizationStore interface { + BindFundingTxID(context.Context, Terms, uint64, chainhash.Hash) error + + RecordFundingSignature(context.Context, Terms, uint64, chainhash.Hash, + []byte) error +} + +// SignAuthorizedBacking releases only a committed signature. If concurrent +// signers chose different valid nonces, all callers receive the durable winner. +func (s *Service) SignAuthorizedBacking(ctx context.Context, terms Terms, + txid chainhash.Hash, sign func() ([]byte, error)) ([]byte, error) { + + store, ok := s.coordinator.store.(FundingAuthorizationStore) + if !ok { + return nil, fmt.Errorf("funding authorization store is " + + "required") + } + var candidate []byte + for range maxCASAttempts { + record, err := s.GetChannel(ctx, terms.ID) + if err != nil { + return nil, err + } + if record.Snapshot.Phase != PhaseNegotiating || + record.Snapshot.Terms != terms || + record.AuthorizedBackingTxID == nil || + *record.AuthorizedBackingTxID != txid { + return nil, fmt.Errorf("backing is not authorized " + + "for signing") + } + if record.FundingSignature != nil { + return record.FundingSignature, nil + } + if candidate == nil { + candidate, err = sign() + if err != nil { + return nil, err + } + } + err = store.RecordFundingSignature( + ctx, terms, record.Revision, txid, candidate, + ) + if errors.Is(err, ErrConflict) { + continue + } + if err != nil { + return nil, err + } + + return candidate, nil + } + + return nil, ErrConflict +} + +// AuthorizeFundingBacking checks the canonical unsigned backing. A nil +// verifyReservation means installation: it can consume but never create a +// signing authorization. A matching durable claim survives loss of the lnd +// wallet's in-memory reservation. +func (s *Service) AuthorizeFundingBacking(ctx context.Context, terms Terms, + source VTXOBinding, point wire.OutPoint, + verifyReservation func() error) error { + + if point.Index != 0 || point.Hash == (chainhash.Hash{}) { + return fmt.Errorf("invalid funding authorization point") + } + for range maxCASAttempts { + record, err := s.GetChannel(ctx, terms.ID) + if err != nil { + return err + } + snap := record.Snapshot + if snap.Terms != terms || snap.Source == nil || + !bindingsEqual(*snap.Source, source) || + !bytes.Equal( + snap.Source.ArkTransaction, + source.ArkTransaction, + ) { + return fmt.Errorf("funding authorization does not " + + "match channel intent") + } + if snap.Backing != nil && snap.Backing.ChannelPoint != point { + return fmt.Errorf("funding backing does not match " + + "channel FSM") + } + if snap.Phase != PhaseNegotiating { + return fmt.Errorf("cannot authorize funding in %s", + snap.Phase) + } + if bound := record.AuthorizedBackingTxID; bound != nil { + if *bound != point.Hash { + return fmt.Errorf("funding reservation " + + "already authorizes a different " + + "backing") + } + if verifyReservation == nil && + record.FundingSignature == nil { + return fmt.Errorf("funding authorization has " + + "no released signature") + } + + return nil + } + if verifyReservation == nil { + return fmt.Errorf("funding backing has no signing " + + "authorization") + } + if err := verifyReservation(); err != nil { + return err + } + store, ok := s.coordinator.store.(FundingAuthorizationStore) + if !ok { + return fmt.Errorf("funding authorization store is " + + "required") + } + err = store.BindFundingTxID( + ctx, terms, record.Revision, point.Hash, + ) + if errors.Is(err, ErrConflict) { + continue + } + + return err + } + + return ErrConflict +} diff --git a/arkchannel/native_executor.go b/arkchannel/native_executor.go new file mode 100644 index 000000000..644d2c2c9 --- /dev/null +++ b/arkchannel/native_executor.go @@ -0,0 +1,307 @@ +package arkchannel + +import ( + "context" + "errors" + "fmt" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" +) + +// ActionExecutor performs one idempotent side effect after the channel FSM +// has durably committed the action that requested it. +type ActionExecutor interface { + Execute(context.Context, ID, Action) error +} + +// VirtualFundingActivator exposes lnd's synthetic funding confirmation. +type VirtualFundingActivator interface { + ConfirmBacking(chainhash.Hash) error +} + +// FundingCanceler releases a native reservation on either endpoint. Only +// the client also coordinates the peer's cancellation before recording its own. +type FundingCanceler interface { + CancelChannel(context.Context, ID, Terms, VTXOBinding, *Backing, + string) error +} + +// FundingNegotiator runs lnd's native external-funding exchange over the +// application peer transport and records completion through Service.Apply. +type FundingNegotiator interface { + FundingCanceler + + NegotiateChannel(context.Context, ID, Terms, VTXOBinding) error + + PrepareChannelRecovery(context.Context, ID, Terms, VTXOBinding) error +} + +// OORTransferController commits or aborts the prepared transfer that creates +// the exact channel-policy VTXO. +type OORTransferController interface { + ValidatePreparedOOR(context.Context, Terms, VTXOBinding) error + + CommitPreparedOOR(context.Context, ID, Terms, VTXOBinding) error + + AbortPreparedOOR(context.Context, ID, Terms, VTXOBinding, string) error +} + +// ValidatePreparedOOR proves that a binding names an output in the exact +// prepared OOR package before it can enter the durable channel FSM. +func (e *NativeExecutor) ValidatePreparedOOR(ctx context.Context, terms Terms, + source VTXOBinding) error { + + if err := source.Validate(terms); err != nil { + return err + } + if terms.Funder != e.localParty { + return nil + } + if e.oor == nil { + return fmt.Errorf("local OOR transfer controller is " + + "unavailable") + } + + return e.oor.ValidatePreparedOOR(ctx, terms, source) +} + +// ChannelEventSink records trusted local subsystem completion back into the +// durable channel state machine. +type ChannelEventSink interface { + ApplyLocalEvent(context.Context, ID, Event) (Record, error) +} + +// ChannelEventSinkBinder wires an executor to its owning service after both +// have been constructed. +type ChannelEventSinkBinder interface { + BindChannelEventSink(ChannelEventSink) error +} + +// ChannelMaterializer publishes the Ark ancestry before the signed backing. +type ChannelMaterializer interface { + MaterializeChannel(context.Context, ID, Terms, VTXOBinding, + Backing) error +} + +// ChannelOnchainHandoff verifies lnd's standard watcher, arbitrator, and +// resolver lifecycle is armed before backing publication is allowed. +type ChannelOnchainHandoff interface { + HandoffChannel(wire.OutPoint) error +} + +// ChannelForceCloser ensures native lnd publishes its latest commitment after +// the Ark channel FSM has proved that the backing is on chain. +type ChannelForceCloser interface { + EnsureForceCloseChannel(wire.OutPoint) error +} + +// ChannelCooperativeCloser coordinates clean lnd state, a 3-of-3 OOR close, +// and local lnd archival across paired endpoints. +type ChannelCooperativeCloser interface { + NegotiateCooperativeClose(context.Context, ID, Terms, VTXOBinding, + Backing, CooperativeCloseRequest) error + + PublishCooperativeClose(context.Context, ID, Terms, VTXOBinding, + CooperativeClose) error + + FinalizeCooperativeClose(context.Context, ID, Terms, Backing, + VTXOBinding, CooperativeCloseRequest, CooperativeClose) error +} + +// NativeExecutor routes durable Ark actions into native lnd and the unroller. +type NativeExecutor struct { + localParty Party + funding VirtualFundingActivator + canceler FundingCanceler + negotiator FundingNegotiator + oor OORTransferController + materializer ChannelMaterializer + handoff ChannelOnchainHandoff + forceCloser ChannelForceCloser + closer ChannelCooperativeCloser +} + +// NewNativeExecutor constructs the thin native subsystem adapter. +func NewNativeExecutor(localParty Party, funding VirtualFundingActivator, + canceler FundingCanceler, oor OORTransferController, + materializer ChannelMaterializer, handoff ChannelOnchainHandoff, + forceCloser ChannelForceCloser, + closer ChannelCooperativeCloser) (*NativeExecutor, error) { + + if localParty != PartyClient && localParty != PartyHub { + return nil, fmt.Errorf("local channel party is required") + } + if funding == nil { + return nil, fmt.Errorf("virtual funding activator is required") + } + if canceler == nil { + return nil, fmt.Errorf("funding canceler is required") + } + var negotiator FundingNegotiator + if localParty == PartyClient { + var ok bool + negotiator, ok = canceler.(FundingNegotiator) + if !ok { + return nil, fmt.Errorf("client funding negotiator is " + + "required") + } + } + if closer == nil { + return nil, fmt.Errorf("channel cooperative closer is required") + } + if handoff == nil { + return nil, fmt.Errorf("channel on-chain handoff is required") + } + if forceCloser == nil { + return nil, fmt.Errorf("channel force closer is required") + } + + return &NativeExecutor{ + localParty: localParty, + funding: funding, + canceler: canceler, + negotiator: negotiator, + oor: oor, + materializer: materializer, + handoff: handoff, + forceCloser: forceCloser, + closer: closer, + }, nil +} + +// Execute dispatches one already-durable action without interpreting lnd +// channel or payment state. +func (e *NativeExecutor) Execute(ctx context.Context, id ID, + action Action) error { + + switch action := action.(type) { + case *NegotiateFunding: + if e.negotiator == nil { + return nil + } + + return e.negotiator.NegotiateChannel( + ctx, id, action.Terms, action.Source, + ) + + case *CommitOOR: + if action.Terms.Funder != e.localParty { + return nil + } + if e.oor == nil { + return fmt.Errorf("local OOR transfer controller is " + + "unavailable") + } + + return e.oor.CommitPreparedOOR( + ctx, id, action.Terms, action.Source, + ) + + case *PrepareRecovery: + if e.negotiator == nil { + return nil + } + + return e.negotiator.PrepareChannelRecovery( + ctx, id, action.Terms, action.Source, + ) + + case *AbortOOR: + if action.Terms.Funder != e.localParty { + return nil + } + if e.oor == nil { + return fmt.Errorf("local OOR transfer controller is " + + "unavailable") + } + + return e.oor.AbortPreparedOOR( + ctx, id, action.Terms, action.Source, action.Reason, + ) + + case *ActivateChannel: + return e.funding.ConfirmBacking( + action.Backing.ChannelPoint.Hash, + ) + + case *CancelFunding: + return e.canceler.CancelChannel( + ctx, id, action.Terms, action.Source, action.Backing, + action.Reason, + ) + + case *PublishChannel: + // Expiry may win before the synthetic funding notification. + // Restore native ownership with adds disabled by the durable + // handoff phase; no peer acknowledgement is needed to publish + // the signed exit. + if err := e.funding.ConfirmBacking( + action.Backing.ChannelPoint.Hash, + ); err != nil { + return err + } + if err := e.handoff.HandoffChannel( + action.Backing.ChannelPoint, + ); err != nil { + return err + } + if e.materializer == nil { + return fmt.Errorf("channel materializer is unavailable") + } + + return e.materializer.MaterializeChannel( + ctx, id, action.Terms, action.Source, action.Backing, + ) + + case *ForceCloseChannel: + return e.forceCloser.EnsureForceCloseChannel( + action.Backing.ChannelPoint, + ) + + case *NegotiateCooperativeClose: + return e.closer.NegotiateCooperativeClose( + ctx, id, action.Terms, action.Source, action.Backing, + action.Request, + ) + + case *PublishCooperativeClose: + return e.closer.PublishCooperativeClose( + ctx, id, action.Terms, action.Source, action.Close, + ) + + case *FinalizeCooperativeClose: + return e.closer.FinalizeCooperativeClose( + ctx, id, action.Terms, action.Backing, action.Source, + action.Request, action.Close, + ) + + default: + return fmt.Errorf("unknown Ark channel action %T", action) + } +} + +// BindChannelEventSink connects native funding and OOR terminal observations +// to the same durable channel service. +func (e *NativeExecutor) BindChannelEventSink(sink ChannelEventSink) error { + var bindErrors []error + for _, component := range []any{ + e.canceler, e.oor, e.materializer, e.closer, + } { + if component == nil { + continue + } + binder, ok := component.(ChannelEventSinkBinder) + if !ok { + continue + } + if err := binder.BindChannelEventSink(sink); err != nil { + bindErrors = append(bindErrors, err) + } + } + + return errors.Join(bindErrors...) +} + +var _ ActionExecutor = (*NativeExecutor)(nil) +var _ ChannelEventSinkBinder = (*NativeExecutor)(nil) diff --git a/arkchannel/native_executor_test.go b/arkchannel/native_executor_test.go new file mode 100644 index 000000000..5b92a43ec --- /dev/null +++ b/arkchannel/native_executor_test.go @@ -0,0 +1,336 @@ +package arkchannel + +import ( + "context" + "testing" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/stretchr/testify/require" +) + +// nativeExecutorHarness implements each thin native boundary. +type nativeExecutorHarness struct { + confirmed chainhash.Hash + negotiatedID ID + committedID ID + abortedID ID + cancelledID ID + publishedID ID + recoveryID ID + handedOff wire.OutPoint + forceClosed wire.OutPoint + closeID ID + boundSinks int + validations int +} + +// HandoffChannel records transfer to lnd's on-chain lifecycle. +func (h *nativeExecutorHarness) HandoffChannel( + channelPoint wire.OutPoint) error { + + h.handedOff = channelPoint + + return nil +} + +// BindChannelEventSink records each subsystem binding. +func (h *nativeExecutorHarness) BindChannelEventSink(ChannelEventSink) error { + h.boundSinks++ + + return nil +} + +// ValidatePreparedOOR records successful validation by the OOR owner. +func (h *nativeExecutorHarness) ValidatePreparedOOR(_ context.Context, _ Terms, + _ VTXOBinding) error { + + h.validations++ + + return nil +} + +// CommitPreparedOOR records release of the prepared transfer. +func (h *nativeExecutorHarness) CommitPreparedOOR(_ context.Context, id ID, + _ Terms, _ VTXOBinding) error { + + h.committedID = id + + return nil +} + +// AbortPreparedOOR records release of the prepared source reservation. +func (h *nativeExecutorHarness) AbortPreparedOOR(_ context.Context, id ID, + _ Terms, _ VTXOBinding, _ string) error { + + h.abortedID = id + + return nil +} + +// CancelChannel records native funding cleanup. +func (h *nativeExecutorHarness) CancelChannel(_ context.Context, id ID, _ Terms, + _ VTXOBinding, _ *Backing, _ string) error { + + h.cancelledID = id + + return nil +} + +// ConfirmBacking records lnd virtual activation. +func (h *nativeExecutorHarness) ConfirmBacking(txID chainhash.Hash) error { + h.confirmed = txID + + return nil +} + +// NegotiateChannel records the native funding dispatch. +func (h *nativeExecutorHarness) NegotiateChannel(_ context.Context, id ID, + _ Terms, _ VTXOBinding) error { + + h.negotiatedID = id + + return nil +} + +// PrepareChannelRecovery records installation of the source package. +func (h *nativeExecutorHarness) PrepareChannelRecovery(_ context.Context, id ID, + _ Terms, _ VTXOBinding) error { + + h.recoveryID = id + + return nil +} + +// EnsureForceCloseChannel records commitment publication through lnd. +func (h *nativeExecutorHarness) EnsureForceCloseChannel( + channelPoint wire.OutPoint) error { + + h.forceClosed = channelPoint + + return nil +} + +// MaterializeChannel records the unroller dispatch. +func (h *nativeExecutorHarness) MaterializeChannel(_ context.Context, id ID, + _ Terms, _ VTXOBinding, _ Backing) error { + + h.publishedID = id + + return nil +} + +// NegotiateCooperativeClose records direct close negotiation. +func (h *nativeExecutorHarness) NegotiateCooperativeClose(_ context.Context, + id ID, _ Terms, _ VTXOBinding, _ Backing, + _ CooperativeCloseRequest) error { + + h.closeID = id + + return nil +} + +// PublishCooperativeClose records direct close publication. +func (h *nativeExecutorHarness) PublishCooperativeClose(_ context.Context, + id ID, _ Terms, _ VTXOBinding, _ CooperativeClose) error { + + h.closeID = id + + return nil +} + +// FinalizeCooperativeClose records lnd archival. +func (h *nativeExecutorHarness) FinalizeCooperativeClose(_ context.Context, + id ID, _ Terms, _ Backing, _ VTXOBinding, _ CooperativeCloseRequest, + _ CooperativeClose) error { + + h.closeID = id + + return nil +} + +// TestNativeExecutorRoutesOnlySubsystemBoundaries verifies the adapter has no +// channel state of its own. +func TestNativeExecutorRoutesOnlySubsystemBoundaries(t *testing.T) { + t.Parallel() + + harness := &nativeExecutorHarness{} + executor, err := NewNativeExecutor( + PartyClient, harness, harness, harness, harness, harness, + harness, harness, + ) + require.NoError(t, err) + require.NoError(t, executor.BindChannelEventSink(harnessSink{})) + require.Equal(t, 4, harness.boundSinks) + terms := testTerms(t, KindPromotion) + source := testBinding(terms) + backing := testBacking(t, terms, source) + + require.NoError( + t, + executor.Execute( + t.Context(), terms.ID, &NegotiateFunding{ + Terms: terms, + Source: source, + }, + ), + ) + require.Equal(t, terms.ID, harness.negotiatedID) + + require.NoError( + t, + executor.Execute( + t.Context(), terms.ID, &CommitOOR{ + Terms: terms, + Source: source, + }, + ), + ) + require.Equal(t, terms.ID, harness.committedID) + + require.NoError( + t, + executor.Execute( + t.Context(), terms.ID, &AbortOOR{ + Terms: terms, + Source: source, + Reason: "peer rejected funding", + }, + ), + ) + require.Equal(t, terms.ID, harness.abortedID) + + require.NoError( + t, + executor.Execute( + t.Context(), terms.ID, &CancelFunding{ + Terms: terms, + Backing: &backing, + }, + ), + ) + require.Equal(t, terms.ID, harness.cancelledID) + + require.NoError( + t, + executor.Execute( + t.Context(), terms.ID, &ActivateChannel{ + Terms: terms, + Backing: backing, + }, + ), + ) + require.Equal(t, backing.ChannelPoint.Hash, harness.confirmed) + + require.NoError( + t, + executor.Execute( + t.Context(), terms.ID, &PublishChannel{ + Terms: terms, + Source: source, + Backing: backing, + }, + ), + ) + require.Equal(t, terms.ID, harness.publishedID) + require.Equal(t, backing.ChannelPoint, harness.handedOff) +} + +// TestNativeExecutorFencesOORActionsToFunder proves the responder cannot commit +// or abort the funder's OOR actor session, while either recovery-ready endpoint +// can publish the shared source package after activation. +func TestNativeExecutorFencesOORActionsToFunder(t *testing.T) { + t.Parallel() + + harness := &nativeExecutorHarness{} + executor, err := NewNativeExecutor( + PartyHub, harness, harness, harness, harness, harness, harness, + harness, + ) + require.NoError(t, err) + terms := testTerms(t, KindPromotion) + source := testBinding(terms) + require.NoError( + t, + executor.ValidatePreparedOOR( + t.Context(), terms, source, + ), + ) + require.Zero(t, harness.validations) + + for _, action := range []Action{ + &NegotiateFunding{ + Terms: terms, + Source: source, + }, + &PrepareRecovery{ + Terms: terms, + Source: source, + }, + } { + require.NoError( + t, + executor.Execute( + t.Context(), terms.ID, action, + ), + ) + } + require.Zero(t, harness.negotiatedID) + require.Zero(t, harness.recoveryID) + + require.NoError( + t, + executor.Execute( + t.Context(), terms.ID, &CommitOOR{ + Terms: terms, + Source: source, + }, + ), + ) + require.NoError( + t, + executor.Execute( + t.Context(), terms.ID, &AbortOOR{ + Terms: terms, + Source: source, + Reason: "test abort", + }, + ), + ) + require.Equal(t, ID{}, harness.committedID) + require.Equal(t, ID{}, harness.abortedID) + + backing := testBacking(t, terms, source) + require.NoError( + t, + executor.Execute( + t.Context(), terms.ID, &PublishChannel{ + Terms: terms, + Source: source, + Backing: backing, + }, + ), + ) + require.Equal(t, backing.ChannelPoint, harness.handedOff) + require.Equal(t, terms.ID, harness.publishedID) +} + +// harnessSink accepts callback events for executor wiring tests. +type harnessSink struct{} + +// ApplyLocalEvent accepts one trusted local callback event. +func (harnessSink) ApplyLocalEvent(context.Context, ID, Event) (Record, error) { + return Record{}, nil +} + +var ( + _ VirtualFundingActivator = (*nativeExecutorHarness)(nil) + _ FundingNegotiator = (*nativeExecutorHarness)(nil) + _ OORTransferController = (*nativeExecutorHarness)(nil) + _ ChannelMaterializer = (*nativeExecutorHarness)(nil) + _ ChannelOnchainHandoff = (*nativeExecutorHarness)(nil) + _ ChannelForceCloser = (*nativeExecutorHarness)(nil) + _ ChannelCooperativeCloser = (*nativeExecutorHarness)(nil) + _ ChannelEventSinkBinder = (*nativeExecutorHarness)(nil) + _ ChannelEventSink = harnessSink{} +) diff --git a/arkchannel/progress.go b/arkchannel/progress.go new file mode 100644 index 000000000..de08e89ee --- /dev/null +++ b/arkchannel/progress.go @@ -0,0 +1,41 @@ +package arkchannel + +// subscribeChannelChanges provides a coalesced wake-up after durable progress. +// Subscribe before reading the record, and always reload it on wake-up. The +// signal is only a latency optimization; callers still need a replay timer. +func (c *Coordinator) subscribeChannelChanges(id ID) (<-chan struct{}, func()) { + changed := make(chan struct{}, 1) + c.changesMu.Lock() + if c.changes == nil { + c.changes = make(map[ID]map[chan struct{}]struct{}) + } + if c.changes[id] == nil { + c.changes[id] = make(map[chan struct{}]struct{}) + } + c.changes[id][changed] = struct{}{} + c.changesMu.Unlock() + + return changed, func() { + c.changesMu.Lock() + defer c.changesMu.Unlock() + + delete(c.changes[id], changed) + if len(c.changes[id]) == 0 { + delete(c.changes, id) + } + } +} + +// notifyChannelChanged never blocks a durable transition or creates work for +// an unchanged record. Slow listeners need only one signal to reload state. +func (c *Coordinator) notifyChannelChanged(id ID) { + c.changesMu.Lock() + defer c.changesMu.Unlock() + + for changed := range c.changes[id] { + select { + case changed <- struct{}{}: + default: + } + } +} diff --git a/arkchannel/progress_test.go b/arkchannel/progress_test.go new file mode 100644 index 000000000..90df1837b --- /dev/null +++ b/arkchannel/progress_test.go @@ -0,0 +1,84 @@ +package arkchannel + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// TestChannelChanges reports only committed progress for the subscribed ID, +// coalesces bursts, and releases listeners without owning a worker lifecycle. +func TestChannelChanges(t *testing.T) { + t.Parallel() + + coordinator, err := NewCoordinator(newMemoryStore()) + require.NoError(t, err) + terms := testTerms(t, KindPromotion) + changed, stop := coordinator.subscribeChannelChanges(terms.ID) + defer stop() + second, stopSecond := coordinator.subscribeChannelChanges(terms.ID) + defer stopSecond() + other, stopOther := coordinator.subscribeChannelChanges(ID{99}) + defer stopOther() + + _, err = coordinator.Request(t.Context(), terms) + require.NoError(t, err) + require.Len(t, changed, 1) + require.Len(t, second, 1) + require.Empty(t, other) + + binding := &BindVTXO{Binding: testBinding(terms)} + _, _, err = coordinator.Apply(t.Context(), terms.ID, binding) + require.NoError(t, err) + require.Len(t, changed, 1, "progress must coalesce") + <-changed + <-second + + _, _, err = coordinator.Apply(t.Context(), terms.ID, binding) + require.NoError(t, err) + require.Empty(t, changed, "idempotent replay is not progress") + require.Empty(t, second) + + _, _, err = coordinator.Apply(t.Context(), terms.ID, &ChannelActive{}) + require.Error(t, err) + require.Empty(t, changed, "a rejected event cannot wake a replay") + + stop() + stop() + _, _, err = coordinator.Apply( + t.Context(), terms.ID, &BackingSigned{ + Backing: testBacking(t, terms, binding.Binding), + }, + ) + require.NoError(t, err) + require.Empty(t, changed) + require.Len(t, second, 1) + require.Empty(t, other) + stopSecond() + stopOther() + require.Empty(t, coordinator.changes) +} + +// TestChannelChangesConcurrentUnsubscribe joins notification with listener +// removal without closing a channel that a committing writer can still use. +func TestChannelChangesConcurrentUnsubscribe(t *testing.T) { + t.Parallel() + + coordinator, err := NewCoordinator(newMemoryStore()) + require.NoError(t, err) + id := ID{1} + done := make(chan struct{}) + go func() { + defer close(done) + for range 1_000 { + coordinator.notifyChannelChanged(id) + } + }() + for range 1_000 { + _, stop := coordinator.subscribeChannelChanges(id) + stop() + stop() + } + <-done + require.Empty(t, coordinator.changes) +} diff --git a/arkchannel/recovery_test.go b/arkchannel/recovery_test.go new file mode 100644 index 000000000..19f166ce6 --- /dev/null +++ b/arkchannel/recovery_test.go @@ -0,0 +1,52 @@ +package arkchannel + +import ( + "testing" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/stretchr/testify/require" +) + +// TestRecoveryPackageClone preserves every value while isolating all mutable +// transport slices from the original package. +func TestRecoveryPackageClone(t *testing.T) { + original := RecoveryPackage{ + Descriptor: RecoveryDescriptor{ + Ancestry: []RecoveryAncestry{{ + TreePath: []byte{ + 1, + }, CommitmentTxID: chainhash.Hash{ + 2, + }, + InputIndices: []uint32{ + 3, + }, + }}, + }, + Packages: []RecoveryOORPackage{{ + SessionID: chainhash.Hash{ + 4, + }, ArkPSBT: []byte{ + 5, + }, + Checkpoints: [][]byte{ + { + 6, + }, + }, + }}, + } + + clone := original.Clone() + require.Equal(t, original, clone) + clone.Descriptor.Ancestry[0].TreePath[0] = 7 + clone.Descriptor.Ancestry[0].InputIndices[0] = 8 + clone.Packages[0].ArkPSBT[0] = 9 + clone.Packages[0].Checkpoints[0][0] = 10 + require.Equal(t, byte(1), original.Descriptor.Ancestry[0].TreePath[0]) + require.Equal( + t, uint32(3), original.Descriptor.Ancestry[0].InputIndices[0], + ) + require.Equal(t, byte(5), original.Packages[0].ArkPSBT[0]) + require.Equal(t, byte(6), original.Packages[0].Checkpoints[0][0]) +} diff --git a/arkchannel/service.go b/arkchannel/service.go new file mode 100644 index 000000000..90e3e52ec --- /dev/null +++ b/arkchannel/service.go @@ -0,0 +1,506 @@ +package arkchannel + +import ( + "context" + "fmt" + + "github.com/btcsuite/btcd/wire/v2" +) + +// FundingFinalizationSource reports whether lnd durably stores both initial +// commitments for an exact channel point. +type FundingFinalizationSource interface { + FundingFinalized(context.Context, Terms, Backing) (bool, error) +} + +// Service coordinates channel promotion and lifecycle events. Native lnd +// remains behind the ActionExecutor. +type Service struct { + localParty Party + coordinator *Coordinator + executor ActionExecutor +} + +// eventOrigin identifies whether a fact came from this endpoint or its +// authenticated channel peer. +type eventOrigin uint8 + +const ( + eventOriginLocal eventOrigin = iota + 1 + eventOriginPeer +) + +// ResumeFailure identifies one channel whose already-durable action could not +// be replayed during process startup. +type ResumeFailure struct { + ChannelID ID + Err error +} + +// ResumeFailures reports isolated per-channel replay failures after every +// resumable channel has been attempted. +type ResumeFailures struct { + Failures []ResumeFailure +} + +// Error summarizes the channels that could not resume. +func (e *ResumeFailures) Error() string { + if e == nil || len(e.Failures) == 0 { + return "Ark channel resume failed" + } + if len(e.Failures) == 1 { + failure := e.Failures[0] + + return fmt.Sprintf("resume Ark channel %x: %v", + failure.ChannelID[:4], failure.Err) + } + + return fmt.Sprintf("%d Ark channels failed to resume", len(e.Failures)) +} + +// Unwrap exposes each underlying action failure to errors.Is and errors.As. +func (e *ResumeFailures) Unwrap() []error { + if e == nil { + return nil + } + + errs := make([]error, 0, len(e.Failures)) + for _, failure := range e.Failures { + errs = append(errs, failure.Err) + } + + return errs +} + +// NewService constructs an Ark channel coordination service. +func NewService(localParty Party, coordinator *Coordinator, + executor ActionExecutor) (*Service, error) { + + if localParty != PartyClient && localParty != PartyHub { + return nil, fmt.Errorf("local channel party is required") + } + if coordinator == nil { + return nil, fmt.Errorf("channel coordinator is required") + } + if executor == nil { + return nil, fmt.Errorf("channel action executor is required") + } + + service := &Service{ + localParty: localParty, + coordinator: coordinator, + executor: executor, + } + if binder, ok := executor.(ChannelEventSinkBinder); ok { + if err := binder.BindChannelEventSink(service); err != nil { + return nil, err + } + } + + return service, nil +} + +// RegisterPromotion durably records an existing-VTXO channel before either +// endpoint starts native lnd funding. +func (s *Service) RegisterPromotion(ctx context.Context, terms Terms) (Record, + error) { + + return s.coordinator.Request(ctx, terms) +} + +// StartOORPreparation durably arms wallet selection before the funder asks the +// OOR actor to construct the channel-policy output. +func (s *Service) StartOORPreparation(ctx context.Context, id ID) (Record, + error) { + + return s.ApplyLocalEvent(ctx, id, &OORPreparationStarted{}) +} + +// RecordPreparedOOR validates and durably attaches the exact prepared OOR +// output without executing the resulting native funding action. +func (s *Service) RecordPreparedOOR(ctx context.Context, id ID, + binding VTXOBinding) (Record, error) { + + validator, ok := s.executor.(interface { + ValidatePreparedOOR(context.Context, Terms, VTXOBinding) error + }) + if !ok { + return Record{}, fmt.Errorf("channel executor cannot " + + "validate prepared OOR transfers") + } + record, err := s.coordinator.Get(ctx, id) + if err != nil { + return Record{}, err + } + if err := validator.ValidatePreparedOOR( + ctx, record.Snapshot.Terms, binding, + ); err != nil { + return Record{}, fmt.Errorf("validate prepared OOR: %w", err) + } + + record, err = s.recordEvent(ctx, id, &BindVTXO{ + Binding: binding, + }, eventOriginLocal) + + return record, err +} + +// BindPreparedOOR records the exact prepared output before resuming native +// funding. A crash between these calls leaves the funding action replayable. +func (s *Service) BindPreparedOOR(ctx context.Context, id ID, + binding VTXOBinding) (Record, error) { + + if _, err := s.RecordPreparedOOR(ctx, id, binding); err != nil { + return Record{}, err + } + + return s.ResumeChannelAction(ctx, id) +} + +// PromoteVTXO registers and negotiates a channel backed by a prepared OOR +// transfer from an existing client-funded VTXO. +func (s *Service) PromoteVTXO(ctx context.Context, terms Terms, + binding VTXOBinding) (Record, error) { + + if _, err := s.RegisterPromotion(ctx, terms); err != nil { + return Record{}, err + } + if _, err := s.BindPreparedOOR(ctx, terms.ID, binding); err != nil { + return Record{}, err + } + + return s.coordinator.Get(ctx, terms.ID) +} + +// ApplyLocalEvent records a trusted local callback before executing any +// resulting action. +func (s *Service) ApplyLocalEvent(ctx context.Context, id ID, event Event) ( + Record, error) { + + return s.applyEvent(ctx, id, event, eventOriginLocal) +} + +// ApplyPeerEvent records a fact received from the authenticated channel peer +// before executing any resulting action. +func (s *Service) ApplyPeerEvent(ctx context.Context, id ID, event Event) ( + Record, error) { + + return s.applyEvent(ctx, id, event, eventOriginPeer) +} + +// applyEvent validates event authority, persists the fact, and executes the +// action derived from the resulting durable state. +func (s *Service) applyEvent(ctx context.Context, id ID, event Event, + origin eventOrigin) (Record, error) { + + if err := s.authorizeEvent(ctx, id, event, origin); err != nil { + return Record{}, err + } + + record, actions, err := s.coordinator.Apply(ctx, id, event) + if err != nil { + return Record{}, err + } + if err := s.execute(ctx, id, actions); err != nil { + return Record{}, err + } + if len(actions) > 0 { + return s.coordinator.Get(ctx, id) + } + + return record, nil +} + +// RecordLocalEvent persists a local fact without executing its resulting +// action. Paired endpoint protocols use this as a durable barrier. +func (s *Service) RecordLocalEvent(ctx context.Context, id ID, event Event) ( + Record, error) { + + return s.recordEvent(ctx, id, event, eventOriginLocal) +} + +// RecordPeerEvent persists an authenticated peer fact without executing its +// resulting action. Paired protocols use this only after binding the mailbox +// identity to the channel peer. +func (s *Service) RecordPeerEvent(ctx context.Context, id ID, event Event) ( + Record, error) { + + return s.recordEvent(ctx, id, event, eventOriginPeer) +} + +// recordEvent validates event authority and stores the fact without executing +// the resulting action. +func (s *Service) recordEvent(ctx context.Context, id ID, event Event, + origin eventOrigin) (Record, error) { + + if err := s.authorizeEvent(ctx, id, event, origin); err != nil { + return Record{}, err + } + + record, _, err := s.coordinator.Apply(ctx, id, event) + + return record, err +} + +// ResumeChannelAction executes the action implied by one already durable +// channel record. +func (s *Service) ResumeChannelAction(ctx context.Context, id ID) (Record, + error) { + + record, actions, err := s.coordinator.Resume(ctx, id) + if err != nil { + return Record{}, err + } + if err := s.execute(ctx, id, actions); err != nil { + return Record{}, err + } + if len(actions) == 0 { + return record, nil + } + + return s.coordinator.Get(ctx, id) +} + +// RequestCooperativeClose starts a 3-of-3 OOR spend of an active channel-policy +// VTXO without materializing the unpublished lnd channel point. +func (s *Service) RequestCooperativeClose(ctx context.Context, id ID, + request CooperativeCloseRequest) (Record, error) { + + return s.ApplyLocalEvent( + ctx, id, &RequestCooperativeClose{ + Request: request, + }, + ) +} + +// GetChannel returns the latest durable channel record without executing its +// pending action. Cross-endpoint coordinators use this after a paired barrier +// to avoid returning a stale pre-action acknowledgement. +func (s *Service) GetChannel(ctx context.Context, id ID) (Record, error) { + return s.coordinator.Get(ctx, id) +} + +// SubscribeChannelChanges wakes a caller after this channel's durable local +// progress. Subscribe before GetChannel and release the subscription on exit. +// Signals coalesce and do not replace authoritative reads or fallback replay. +func (s *Service) SubscribeChannelChanges(id ID) (<-chan struct{}, func()) { + return s.coordinator.subscribeChannelChanges(id) +} + +// ListChannels returns every channel with a remaining runtime or recovery +// obligation owned by this endpoint. +func (s *Service) ListChannels(ctx context.Context) ([]Record, error) { + return s.coordinator.ListNonTerminal(ctx) +} + +// Materialize enters the durable on-chain handoff and resumes that exact +// action on retry if a prior process stopped after persisting the transition. +func (s *Service) Materialize(ctx context.Context, id ID) (Record, error) { + record, err := s.coordinator.Get(ctx, id) + if err != nil { + return Record{}, err + } + if record.Snapshot.Phase == PhaseMaterializing { + return s.ResumeChannelAction(ctx, id) + } + + return s.ApplyLocalEvent(ctx, id, &Materialize{}) +} + +// ObserveFundingFinalized records lnd's existing pending-open notification by +// its durable channel point. A missed notification can be recovered through +// ReconcileFunding. +func (s *Service) ObserveFundingFinalized(ctx context.Context, + channelPoint wire.OutPoint) (Record, error) { + + record, err := s.coordinator.FindByChannelPoint(ctx, channelPoint) + if err != nil { + return Record{}, err + } + + return s.ApplyLocalEvent( + ctx, record.Snapshot.Terms.ID, &FundingFinalized{ + Party: s.localParty, + }, + ) +} + +// ReconcileFunding repairs missed pending-open notifications from lnd's +// authoritative channel database. +func (s *Service) ReconcileFunding(ctx context.Context, + source FundingFinalizationSource) error { + + if source == nil { + return fmt.Errorf("funding finalization source is required") + } + records, err := s.coordinator.ListNonTerminal(ctx) + if err != nil { + return err + } + for _, record := range records { + snapshot := record.Snapshot + if snapshot.Backing == nil || + partyFinalized(snapshot, s.localParty) || + snapshot.Phase == PhaseCancelling || + snapshot.Phase == PhaseFailed { + + continue + } + finalized, err := source.FundingFinalized( + ctx, snapshot.Terms, *snapshot.Backing, + ) + if err != nil { + return err + } + if !finalized { + continue + } + if _, err := s.ApplyLocalEvent( + ctx, snapshot.Terms.ID, &FundingFinalized{ + Party: s.localParty, + }, + ); err != nil { + return err + } + } + + return nil +} + +// authorizeEvent enforces which authenticated side owns every event class. +// Cryptographically complete artifacts still need an origin because the +// origin controls when a local side effect becomes replayable. +func (s *Service) authorizeEvent(ctx context.Context, id ID, event Event, + origin eventOrigin) error { + + if event == nil { + return fmt.Errorf("channel event is required") + } + record, err := s.coordinator.Get(ctx, id) + if err != nil { + return err + } + terms := record.Snapshot.Terms + + switch event := event.(type) { + case *OORPreparationStarted, *BindVTXO, *BackingSigned, + *OORFinalized, *OORAborted: + return s.requireOriginParty(origin, terms.Funder, event) + + case *FundingFinalized: + return s.requireOriginParty(origin, event.Party, event) + + case *RecoveryPackageInstalled: + return s.requireOriginParty(origin, event.Party, event) + + case *CooperativeClosePublished: + if origin == eventOriginLocal { + signed := record.Snapshot.CooperativeClose + if s.localParty == PartyHub && (signed == nil || + signed.Proposal.HubOutput <= 0) { + return fmt.Errorf("no hub payout to observe") + } + + return nil + } + + return s.requireOriginParty(origin, PartyClient, event) + + case *RequestCooperativeClose, *CooperativeCloseReady, + *CooperativeCloseAborted: + return s.requireOriginParty(origin, PartyClient, event) + + case *ExpirePrePONR, *FundingCanceled, *ChannelActive, *Materialize, + *SourceExpiring, *CooperativeCloseSigned, + *CooperativeCloseFinalized, *CooperativeCloseObserved, + *SourceSpent, *BackingPublished, *BackingObserved, + *ChannelClosed, *Fail: + + if origin != eventOriginLocal { + return fmt.Errorf("%T requires local subsystem "+ + "evidence", event) + } + + return nil + + default: + return fmt.Errorf("unknown channel event %T", event) + } +} + +// requireOriginParty verifies that an event came from the side whose evidence +// it claims to carry. +func (s *Service) requireOriginParty(origin eventOrigin, expected Party, + event Event) error { + + actual := s.localParty + if origin == eventOriginPeer { + actual = otherParty(s.localParty) + } + if actual != expected { + return fmt.Errorf("%T from %s cannot assert %s evidence", event, + actual, expected) + } + + return nil +} + +// otherParty returns the only authenticated counterparty for one endpoint. +func otherParty(local Party) Party { + if local == PartyClient { + return PartyHub + } + + return PartyClient +} + +// partyFinalized reports the local acknowledgement stored in one snapshot. +func partyFinalized(snapshot Snapshot, party Party) bool { + switch party { + case PartyClient: + return snapshot.ClientFinalized + + case PartyHub: + return snapshot.HubFinalized + + default: + return false + } +} + +// Resume replays side effects implied by all resumable durable records. +func (s *Service) Resume(ctx context.Context) error { + work, err := s.coordinator.ResumeAll(ctx) + if err != nil { + return err + } + failures := make([]ResumeFailure, 0) + for _, item := range work { + id := item.Record.Snapshot.Terms.ID + if err := s.executor.Execute(ctx, id, item.Action); err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + failures = append(failures, ResumeFailure{ + ChannelID: id, + Err: err, + }) + } + } + if len(failures) > 0 { + return &ResumeFailures{Failures: failures} + } + + return nil +} + +// execute performs already-durable actions in order. +func (s *Service) execute(ctx context.Context, id ID, actions []Action) error { + for _, action := range actions { + if err := s.executor.Execute(ctx, id, action); err != nil { + return err + } + } + + return nil +} diff --git a/arkchannel/service_test.go b/arkchannel/service_test.go new file mode 100644 index 000000000..784be7ec1 --- /dev/null +++ b/arkchannel/service_test.go @@ -0,0 +1,543 @@ +package arkchannel + +import ( + "context" + "fmt" + "testing" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/stretchr/testify/require" +) + +// serviceExecutor completes native callbacks through the public Service API. +type serviceExecutor struct { + t *testing.T + service *Service + localParty Party + counts map[string]int + failPublish int +} + +type staticFundingFinalizationSource struct { + finalized bool +} + +type noOpActionExecutor struct{} + +type recordingResumeExecutor struct { + failID ID + calls []ID +} + +// ValidatePreparedOOR accepts fixtures already covered by state validation. +func (*noOpActionExecutor) ValidatePreparedOOR(context.Context, Terms, + VTXOBinding) error { + + return nil +} + +// Execute accepts already-durable actions without completing callbacks. +func (*noOpActionExecutor) Execute(context.Context, ID, Action) error { + return nil +} + +// Execute records every replay and fails only the selected channel. +func (e *recordingResumeExecutor) Execute(_ context.Context, id ID, + _ Action) error { + + e.calls = append(e.calls, id) + if id == e.failID { + return fmt.Errorf("injected channel failure") + } + + return nil +} + +// ValidatePreparedOOR accepts fixtures already covered by state validation. +func (*serviceExecutor) ValidatePreparedOOR(context.Context, Terms, + VTXOBinding) error { + + return nil +} + +// applyPartyEvent routes one simulated endpoint callback through the matching +// local or authenticated-peer service boundary. +func (e *serviceExecutor) applyPartyEvent(ctx context.Context, id ID, + party Party, event Event) (Record, error) { + + if party == e.localParty { + return e.service.ApplyLocalEvent(ctx, id, event) + } + + return e.service.ApplyPeerEvent(ctx, id, event) +} + +// FundingFinalized returns one fixed lnd database observation. +func (s *staticFundingFinalizationSource) FundingFinalized(context.Context, + Terms, Backing) (bool, error) { + + return s.finalized, nil +} + +// Execute simulates native lnd and materializer completion callbacks. +func (e *serviceExecutor) Execute(ctx context.Context, id ID, + action Action) error { + + e.counts[fmt.Sprintf("%T", action)]++ + + switch action := action.(type) { + case *NegotiateFunding: + backing := testBacking(e.t, action.Terms, action.Source) + for _, fact := range []struct { + party Party + event Event + }{ + { + action.Terms.Funder, + &BackingSigned{ + Backing: backing, + }, + }, + { + PartyClient, + &FundingFinalized{ + Party: PartyClient, + }, + }, + { + PartyHub, + &FundingFinalized{ + Party: PartyHub, + }, + }, + } { + if _, err := e.applyPartyEvent( + ctx, id, fact.party, fact.event, + ); err != nil { + return err + } + } + + case *CommitOOR: + _, err := e.applyPartyEvent( + ctx, id, action.Terms.Funder, &OORFinalized{ + SessionID: action.Source.OORSessionID, + }, + ) + + return err + + case *PrepareRecovery: + for _, party := range []Party{PartyClient, PartyHub} { + if _, err := e.applyPartyEvent( + ctx, id, party, &RecoveryPackageInstalled{ + Party: party, + }, + ); err != nil { + return err + } + } + + return nil + + case *AbortOOR: + _, err := e.applyPartyEvent( + ctx, id, action.Terms.Funder, &OORAborted{ + SessionID: action.Source.OORSessionID, + Reason: action.Reason, + }, + ) + + return err + + case *ActivateChannel: + _, err := e.service.ApplyLocalEvent(ctx, id, &ChannelActive{ + ChannelPointHash: action.Backing.ChannelPoint.Hash, + ChannelPointIndex: action.Backing.ChannelPoint.Index, + }) + + return err + + case *CancelFunding: + _, err := e.service.ApplyLocalEvent(ctx, id, &FundingCanceled{}) + + return err + + case *PublishChannel: + if e.failPublish > 0 { + e.failPublish-- + + return fmt.Errorf("injected handoff failure") + } + _, err := e.service.ApplyLocalEvent(ctx, id, &BackingPublished{ + TxID: action.Backing.ChannelPoint.Hash, + }) + + return err + + case *ForceCloseChannel: + return nil + + default: + return fmt.Errorf("unexpected service action %T", action) + } + + return nil +} + +// TestServiceReplaysSourceConflictAction proves repeating the same durable +// chain fact retries a backing publication that failed after state commit. +func TestServiceReplaysSourceConflictAction(t *testing.T) { + t.Parallel() + + coordinator, err := NewCoordinator(newMemoryStore()) + require.NoError(t, err) + executor := &serviceExecutor{ + t: t, counts: make(map[string]int), failPublish: 1, + } + service, err := NewService(PartyClient, coordinator, executor) + require.NoError(t, err) + executor.service = service + executor.localParty = PartyClient + terms := testTerms(t, KindPromotion) + binding := testBinding(terms) + _, err = service.PromoteVTXO(t.Context(), terms, binding) + require.NoError(t, err) + + conflict := &SourceSpent{ + OutPoint: binding.OutPoint, + SpendingTxID: chainhash.Hash{ + 44, + }, + } + _, err = service.ApplyLocalEvent(t.Context(), terms.ID, conflict) + require.ErrorContains(t, err, "injected handoff failure") + record, err := service.GetChannel(t.Context(), terms.ID) + require.NoError(t, err) + require.Equal(t, PhaseMaterializing, record.Snapshot.Phase) + + record, err = service.ApplyLocalEvent(t.Context(), terms.ID, conflict) + require.NoError(t, err) + require.Equal(t, PhaseOnChain, record.Snapshot.Phase) + require.Equal(t, 2, executor.counts["*arkchannel.PublishChannel"]) + require.Equal(t, 1, executor.counts["*arkchannel.ForceCloseChannel"]) +} + +// TestServiceResumesMaterializationAction proves a retry cannot acknowledge a +// durable materializing state without re-running the failed handoff and +// publication action. +func TestServiceResumesMaterializationAction(t *testing.T) { + t.Parallel() + + coordinator, err := NewCoordinator(newMemoryStore()) + require.NoError(t, err) + executor := &serviceExecutor{ + t: t, counts: make(map[string]int), + } + service, err := NewService(PartyClient, coordinator, executor) + require.NoError(t, err) + executor.service = service + executor.localParty = PartyClient + + terms := testTerms(t, KindPromotion) + _, err = service.PromoteVTXO( + t.Context(), terms, testBinding(terms), + ) + require.NoError(t, err) + executor.failPublish = 1 + + _, err = service.Materialize(t.Context(), terms.ID) + require.ErrorContains(t, err, "injected handoff failure") + record, err := service.GetChannel(t.Context(), terms.ID) + require.NoError(t, err) + require.Equal(t, PhaseMaterializing, record.Snapshot.Phase) + + record, err = service.Materialize(t.Context(), terms.ID) + require.NoError(t, err) + require.Equal(t, PhaseOnChain, record.Snapshot.Phase) + require.Equal(t, 2, executor.counts["*arkchannel.PublishChannel"]) +} + +// TestServicePromotesAndMaterializesVTXO verifies the compact public workflow +// drives callbacks without owning Lightning state. +func TestServicePromotesAndMaterializesVTXO(t *testing.T) { + t.Parallel() + + coordinator, err := NewCoordinator(newMemoryStore()) + require.NoError(t, err) + executor := &serviceExecutor{ + t: t, + counts: make(map[string]int), + } + service, err := NewService(PartyClient, coordinator, executor) + require.NoError(t, err) + executor.service = service + executor.localParty = PartyClient + + terms := testTerms(t, KindPromotion) + record, err := service.PromoteVTXO( + t.Context(), terms, testBinding(terms), + ) + require.NoError(t, err) + require.Equal(t, PhaseActive, record.Snapshot.Phase) + require.Equal(t, 1, executor.counts["*arkchannel.NegotiateFunding"]) + require.Equal(t, 1, executor.counts["*arkchannel.CommitOOR"]) + require.Equal(t, 1, executor.counts["*arkchannel.ActivateChannel"]) + + record, err = service.PromoteVTXO( + t.Context(), terms, testBinding(terms), + ) + require.NoError(t, err) + require.Equal(t, PhaseActive, record.Snapshot.Phase) + require.Equal(t, 1, executor.counts["*arkchannel.NegotiateFunding"]) + require.Equal(t, 1, executor.counts["*arkchannel.CommitOOR"]) + require.Equal(t, 1, executor.counts["*arkchannel.ActivateChannel"]) + + record, err = service.Materialize(t.Context(), terms.ID) + require.NoError(t, err) + require.Equal(t, PhaseOnChain, record.Snapshot.Phase) +} + +// TestServiceSeparatesPromotionRegistrationFromBinding verifies two peers can +// persist identical terms before either one starts lnd negotiation. +func TestServiceSeparatesPromotionRegistrationFromBinding(t *testing.T) { + t.Parallel() + + coordinator, err := NewCoordinator(newMemoryStore()) + require.NoError(t, err) + executor := &serviceExecutor{ + t: t, + counts: make(map[string]int), + } + service, err := NewService(PartyClient, coordinator, executor) + require.NoError(t, err) + executor.service = service + executor.localParty = PartyClient + terms := testTerms(t, KindPromotion) + + record, err := service.RegisterPromotion(t.Context(), terms) + require.NoError(t, err) + require.Equal(t, PhaseRequested, record.Snapshot.Phase) + require.Empty(t, executor.counts) + + record, err = service.BindPreparedOOR( + t.Context(), terms.ID, testBinding(terms), + ) + require.NoError(t, err) + require.Equal(t, PhaseActive, record.Snapshot.Phase) + require.Equal(t, 1, executor.counts["*arkchannel.NegotiateFunding"]) +} + +// TestServiceReconcilesFundingByChannelPoint proves a missed lnd callback is +// recoverable from the pending channel record keyed by signed backing. +func TestServiceReconcilesFundingByChannelPoint(t *testing.T) { + t.Parallel() + + coordinator, err := NewCoordinator(newMemoryStore()) + require.NoError(t, err) + service, err := NewService( + PartyClient, coordinator, &noOpActionExecutor{}, + ) + require.NoError(t, err) + terms := testTerms(t, KindPromotion) + _, err = service.RegisterPromotion(t.Context(), terms) + require.NoError(t, err) + binding := testBinding(terms) + _, err = service.BindPreparedOOR(t.Context(), terms.ID, binding) + require.NoError(t, err) + backing := testBacking(t, terms, binding) + _, err = service.ApplyLocalEvent(t.Context(), terms.ID, &BackingSigned{ + Backing: backing, + }) + require.NoError(t, err) + + source := &staticFundingFinalizationSource{finalized: true} + require.NoError( + t, + service.ReconcileFunding(t.Context(), source), + ) + record, err := service.ApplyPeerEvent( + t.Context(), terms.ID, &FundingFinalized{ + Party: PartyHub, + }, + ) + require.NoError(t, err) + require.True(t, record.Snapshot.ClientFinalized) + require.True(t, record.Snapshot.HubFinalized) + require.Equal(t, PhaseBackingReady, record.Snapshot.Phase) + require.True(t, record.Snapshot.ReadyToCommitOOR()) + + _, err = service.ObserveFundingFinalized( + t.Context(), wire.OutPoint{ + Hash: [32]byte{99}, + }, + ) + require.ErrorIs(t, err, ErrNotFound) +} + +// TestServiceEventAuthorityMatrix pins the owner of every durable event class. +// Party-bearing evidence may only be asserted by that authenticated side, and +// local subsystem observations never cross the peer ingress boundary. +func TestServiceEventAuthorityMatrix(t *testing.T) { + t.Parallel() + + newService := func(localParty Party, terms Terms) *Service { + coordinator, err := NewCoordinator(newMemoryStore()) + require.NoError(t, err) + _, err = coordinator.Request(t.Context(), terms) + require.NoError(t, err) + service, err := NewService( + localParty, coordinator, &noOpActionExecutor{}, + ) + require.NoError(t, err) + + return service + } + + promotion := testTerms(t, KindPromotion) + clientService := newService(PartyClient, promotion) + + tests := []struct { + name string + service *Service + id ID + event Event + origin eventOrigin + }{ + {"prepare OOR", clientService, promotion.ID, + &OORPreparationStarted{}, eventOriginLocal}, + {"bind VTXO", clientService, promotion.ID, + &BindVTXO{}, eventOriginLocal}, + {"install backing", clientService, promotion.ID, + &BackingSigned{}, eventOriginLocal}, + {"finalize OOR", clientService, promotion.ID, + &OORFinalized{}, eventOriginLocal}, + {"abort OOR", clientService, promotion.ID, + &OORAborted{}, eventOriginLocal}, + {"client funding finalized", clientService, promotion.ID, + &FundingFinalized{ + Party: PartyClient, + }, eventOriginLocal}, + {"hub funding finalized", clientService, promotion.ID, + &FundingFinalized{ + Party: PartyHub, + }, eventOriginPeer}, + {"client recovery ready", clientService, promotion.ID, + &RecoveryPackageInstalled{ + Party: PartyClient, + }, + eventOriginLocal}, + {"hub recovery ready", clientService, promotion.ID, + &RecoveryPackageInstalled{ + Party: PartyHub, + }, eventOriginPeer}, + {"request close", clientService, promotion.ID, + &RequestCooperativeClose{}, eventOriginLocal}, + {"publish close", clientService, promotion.ID, + &CooperativeClosePublished{}, eventOriginLocal}, + {"abort close", clientService, promotion.ID, + &CooperativeCloseAborted{}, eventOriginLocal}, + {"close signed", clientService, promotion.ID, + &CooperativeCloseSigned{}, eventOriginLocal}, + {"close receipt", clientService, promotion.ID, + &CooperativeCloseReady{}, eventOriginLocal}, + {"close finalized", clientService, promotion.ID, + &CooperativeCloseFinalized{}, eventOriginLocal}, + {"expire", clientService, promotion.ID, + &ExpirePrePONR{}, eventOriginLocal}, + {"cancel funding", clientService, promotion.ID, + &FundingCanceled{}, eventOriginLocal}, + {"activate", clientService, promotion.ID, + &ChannelActive{}, eventOriginLocal}, + {"materialize", clientService, promotion.ID, + &Materialize{}, eventOriginLocal}, + {"source expiring", clientService, promotion.ID, + &SourceExpiring{}, eventOriginLocal}, + {"cooperative payout observed", clientService, promotion.ID, + &CooperativeCloseObserved{}, eventOriginLocal}, + {"source spent", clientService, promotion.ID, + &SourceSpent{}, eventOriginLocal}, + {"backing published", clientService, promotion.ID, + &BackingPublished{}, eventOriginLocal}, + {"backing observed", clientService, promotion.ID, + &BackingObserved{}, eventOriginLocal}, + {"channel closed", clientService, promotion.ID, + &ChannelClosed{}, eventOriginLocal}, + { + "fail", + clientService, + promotion.ID, + &Fail{}, + eventOriginLocal, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require.NoError( + t, + test.service.authorizeEvent( + t.Context(), test.id, test.event, + test.origin, + ), + ) + + wrongOrigin := eventOriginLocal + if test.origin == eventOriginLocal { + wrongOrigin = eventOriginPeer + } + require.Error( + t, + test.service.authorizeEvent( + t.Context(), test.id, test.event, + wrongOrigin, + ), + ) + }) + } +} + +// TestServiceResumeIsolatesChannelFailures proves one corrupt or unavailable +// channel cannot prevent independent durable channels from replaying. +func TestServiceResumeIsolatesChannelFailures(t *testing.T) { + t.Parallel() + + coordinator, err := NewCoordinator(newMemoryStore()) + require.NoError(t, err) + first := testTerms(t, KindPromotion) + second := testTerms(t, KindPromotion) + second.ID[0] = 2 + second.PendingChannelID[0] = 6 + second.ReservedSCID += 1 << 16 + for _, terms := range []Terms{first, second} { + _, err := coordinator.Request(t.Context(), terms) + require.NoError(t, err) + _, actions, err := coordinator.Apply( + t.Context(), terms.ID, &BindVTXO{ + Binding: testBinding(terms), + }, + ) + require.NoError(t, err) + require.Len(t, actions, 1) + } + + executor := &recordingResumeExecutor{failID: first.ID} + service, err := NewService(PartyClient, coordinator, executor) + require.NoError(t, err) + err = service.Resume(t.Context()) + + var failures *ResumeFailures + require.ErrorAs(t, err, &failures) + require.Len(t, failures.Failures, 1) + require.Equal(t, first.ID, failures.Failures[0].ChannelID) + require.ErrorContains( + t, failures.Failures[0].Err, "injected channel failure", + ) + require.ElementsMatch(t, []ID{first.ID, second.ID}, executor.calls) +} + +var ( + _ ActionExecutor = (*serviceExecutor)(nil) + _ FundingFinalizationSource = (*staticFundingFinalizationSource)(nil) +) diff --git a/arkchannel/source_expiry_test.go b/arkchannel/source_expiry_test.go new file mode 100644 index 000000000..dc39c09ec --- /dev/null +++ b/arkchannel/source_expiry_test.go @@ -0,0 +1,161 @@ +package arkchannel + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// TestSourceExpiryPersistsUnilateralHandoff proves expiry cannot wait on an +// offline peer's recovery or activation acknowledgement after funding exists. +func TestSourceExpiryPersistsUnilateralHandoff(t *testing.T) { + t.Parallel() + + terms := testTerms(t, KindPromotion) + source := testBinding(terms) + coordinator := activeCooperativeChannel(t, terms, source) + record, err := coordinator.Get(t.Context(), terms.ID) + require.NoError(t, err) + for _, phase := range []Phase{ + PhaseActive, PhaseActivating, PhaseBackingReady, + } { + t.Run(phase.String(), func(t *testing.T) { + snapshot := record.Snapshot.Clone() + snapshot.Phase = phase + if phase == PhaseBackingReady { + snapshot.HubRecoveryReady = false + } + state, err := RestoreState(snapshot) + require.NoError(t, err) + transition, err := state.ProcessEvent( + t.Context(), &SourceExpiring{}, nil, + ) + require.NoError(t, err) + nextState, ok := transition.NextState.(State) + require.True(t, ok) + next := nextState.Snapshot() + require.Equal(t, PhaseMaterializing, next.Phase) + require.Nil( + t, next.SourceConflict, "a deadline is not "+ + "fabricated chain-spend evidence", + ) + require.Equal(t, snapshot.Backing, next.Backing) + _, err = RestoreState(next) + require.NoError(t, err) + action, err := PendingAction(next) + require.NoError(t, err) + require.IsType(t, &PublishChannel{}, action) + changed, err := applySourceExpiring(&next) + require.NoError(t, err) + require.False(t, changed) + _, err = applyBackingPublished( + &next, next.Backing.ChannelPoint.Hash, + ) + require.NoError(t, err) + _, err = RestoreState(next) + require.NoError(t, err) + _, err = applyEvent(&next, &ChannelClosed{}) + require.NoError(t, err) + _, err = RestoreState(next) + require.NoError(t, err) + }) + } +} + +// TestSourceExpiryDoesNotAuthorizeUnfundedExit preserves the OOR signing and +// native commitment barriers even when a local deadline fires. +func TestSourceExpiryDoesNotAuthorizeUnfundedExit(t *testing.T) { + t.Parallel() + + terms := testTerms(t, KindPromotion) + source := testBinding(terms) + coordinator := activeCooperativeChannel(t, terms, source) + record, err := coordinator.Get(t.Context(), terms.ID) + require.NoError(t, err) + for _, missing := range []string{"funding", "recovery"} { + snapshot := record.Snapshot.Clone() + if missing == "funding" { + snapshot.OORFinalized = false + } else { + snapshot.ClientRecoveryReady = false + snapshot.HubRecoveryReady = false + } + _, err := applySourceExpiring(&snapshot) + require.Error(t, err) + require.Equal(t, PhaseActive, snapshot.Phase) + } +} + +// TestSourceExpiryPreservesAuthorizedRefresh protects the old source even if +// the operator stalls after release, without treating the release as revoked +// or accepting a peer receipt as proof that native watchers can be retired. +func TestSourceExpiryPreservesAuthorizedRefresh(t *testing.T) { + t.Parallel() + + terms, source, request, clientKey, hubKey, operatorKey := + testCooperativeCloseFixture(t, KindPromotion, 5_000) + coordinator := activeCooperativeChannel(t, terms, source) + _, _, err := coordinator.Apply( + t.Context(), terms.ID, &RequestCooperativeClose{ + Request: request, + }, + ) + require.NoError(t, err) + template, err := NewCooperativeCloseTemplate( + terms, source, request, 70_000, 30_000, 5, + ) + require.NoError(t, err) + settlement := completeTestCooperativeClose( + t, template, terms, source, request, clientKey, hubKey, + operatorKey, + ) + for _, event := range []Event{ + &CooperativeCloseSigned{ + Close: settlement, + }, + &CooperativeCloseReady{ + Receipt: settlement.AuthorizationReceipt(), + }, + } { + _, _, err = coordinator.Apply(t.Context(), terms.ID, event) + require.NoError(t, err) + } + record, actions, err := coordinator.Apply( + t.Context(), terms.ID, &SourceExpiring{}, + ) + require.NoError(t, err) + require.Equal(t, PhaseMaterializing, record.Snapshot.Phase) + require.Equal(t, &settlement, record.Snapshot.CooperativeClose) + + require.IsType(t, &PublishChannel{}, requireOneAction(t, actions)) + _, err = RestoreState(record.Snapshot) + require.NoError(t, err) + record, _, err = coordinator.Apply( + t.Context(), terms.ID, &CooperativeClosePublished{ + TxID: settlement.TxID, + }, + ) + require.NoError(t, err) + require.Equal( + t, PhaseMaterializing, record.Snapshot.Phase, + "an off-chain receipt cannot prove a competing backing lost", + ) + _, _, err = coordinator.Apply( + t.Context(), terms.ID, &CooperativeCloseObserved{ + TxID: [32]byte{1}, + }, + ) + require.Error(t, err) + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &CooperativeCloseObserved{ + TxID: settlement.TxID, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseCoopClosePublished, record.Snapshot.Phase) + require.IsType( + t, &FinalizeCooperativeClose{}, requireOneAction(t, actions), + ) + _, err = RestoreState(record.Snapshot) + require.NoError(t, err) +} diff --git a/arkchannel/source_lifetime_test.go b/arkchannel/source_lifetime_test.go new file mode 100644 index 000000000..21fe96817 --- /dev/null +++ b/arkchannel/source_lifetime_test.go @@ -0,0 +1,156 @@ +package arkchannel + +import ( + "math" + "testing" + + "github.com/stretchr/testify/require" +) + +// TestSourceMaterializationHeight pins the reserve and rejects unknown or +// impossible deadlines without allowing either signed or unsigned wraparound. +func TestSourceMaterializationHeight(t *testing.T) { + t.Parallel() + + require.Equal(t, 40, SourceExpirySafetyMargin) + tests := []struct { + name string + expiry int32 + allowance uint32 + deadline int32 + invalid bool + }{ + { + name: "full reserve", expiry: 1000, allowance: 100, + deadline: 860, + }, + { + name: "minimum deadline", expiry: 42, allowance: 1, + deadline: 1, + }, + { + name: "maximum expiry", expiry: math.MaxInt32, + allowance: 1, deadline: math.MaxInt32 - 41, + }, + { + name: "maximum reserve with deadline", + expiry: math.MaxInt32, allowance: math.MaxInt32 - 41, + deadline: 1, + }, + { + name: "absent expiry", allowance: 1, invalid: true, + }, + { + name: "negative expiry", expiry: -1, allowance: 1, + invalid: true, + }, + { + name: "minimum expiry", expiry: math.MinInt32, + allowance: 1, invalid: true, + }, + { + name: "zero allowance", expiry: 1000, invalid: true, + }, + { + name: "zero deadline", expiry: 140, allowance: 100, + invalid: true, + }, + { + name: "negative deadline", expiry: 139, allowance: 100, + invalid: true, + }, + { + name: "signed reserve overflow", expiry: math.MaxInt32, + allowance: math.MaxInt32, invalid: true, + }, + { + name: "unsigned reserve overflow", + expiry: math.MaxInt32, + allowance: math.MaxUint32, invalid: true, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + deadline, err := SourceMaterializationHeight( + test.expiry, test.allowance, + ) + if test.invalid { + require.Error(t, err) + require.Zero(t, deadline) + + return + } + + require.NoError(t, err) + require.Equal(t, test.deadline, deadline) + }) + } +} + +// TestValidateSourceLifetime requires strict admission before the computed +// deadline and never treats a negative backend height as usable chain state. +func TestValidateSourceLifetime(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + expiry int32 + height int32 + allowance uint32 + invalid bool + }{ + { + name: "genesis", expiry: 1000, allowance: 100, + }, + { + name: "before deadline", expiry: 1000, height: 859, + allowance: 100, + }, + { + name: "at deadline", expiry: 1000, height: 860, + allowance: 100, invalid: true, + }, + { + name: "after deadline", expiry: 1000, height: 861, + allowance: 100, invalid: true, + }, + { + name: "expired", expiry: 1000, height: 1000, + allowance: 100, invalid: true, + }, + { + name: "negative height", expiry: 1000, height: -1, + allowance: 100, invalid: true, + }, + { + name: "unknown expiry", height: 1, allowance: 100, + invalid: true, + }, + { + name: "unknown allowance", expiry: 1000, height: 1, + invalid: true, + }, + { + name: "overflow", expiry: math.MaxInt32, height: 1, + allowance: math.MaxUint32, invalid: true, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + err := ValidateSourceLifetime( + test.expiry, test.height, test.allowance, + ) + if test.invalid { + require.Error(t, err) + + return + } + + require.NoError(t, err) + }) + } +} diff --git a/arkchannel/state.go b/arkchannel/state.go new file mode 100644 index 000000000..7b2b319be --- /dev/null +++ b/arkchannel/state.go @@ -0,0 +1,1361 @@ +package arkchannel + +import ( + "context" + "fmt" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/baselib/protofsm" + "github.com/lightningnetwork/lnd/fn/v2" +) + +// Environment names one pure Ark-channel state machine instance. +type Environment struct { + ChannelID ID +} + +// Name returns the stable state machine name. +func (e *Environment) Name() string { + return fmt.Sprintf("ark_channel_%x", e.ChannelID[:4]) +} + +// State is one protofsm state carrying only Ark coordination facts. +type State interface { + protofsm.State[Event, Action, *Environment] + + Snapshot() Snapshot + + stateSealed() +} + +// StateTransition is the Ark-channel protofsm transition type. +type StateTransition = protofsm.StateTransition[ + Event, Action, *Environment, +] + +// EmittedEvent is the Ark-channel protofsm emission type. +type EmittedEvent = protofsm.EmittedEvent[Event, Action] + +// channelState is intentionally one compact state representation. Phase is +// durable and validated; lnd remains the richer channel state machine. +type channelState struct { + snapshot Snapshot +} + +// NewState validates immutable terms and creates the requested state. +func NewState(terms Terms) (State, error) { + if err := terms.Validate(); err != nil { + return nil, err + } + + return &channelState{snapshot: Snapshot{ + Terms: terms.Clone(), + Phase: PhaseRequested, + }}, nil +} + +// RestoreState validates and restores one durable snapshot. +func RestoreState(snapshot Snapshot) (State, error) { + if err := validateSnapshot(snapshot); err != nil { + return nil, err + } + + return &channelState{snapshot: snapshot.Clone()}, nil +} + +// Snapshot returns an isolated copy of the durable state. +func (s *channelState) Snapshot() Snapshot { + return s.snapshot.Clone() +} + +// String returns the durable coordination phase. +func (s *channelState) String() string { + return s.snapshot.Phase.String() +} + +// IsTerminal reports whether coordination is complete or safely abandoned. +func (s *channelState) IsTerminal() bool { + return s.snapshot.Phase.IsTerminal() +} + +func (*channelState) stateSealed() {} + +// ProcessEvent applies one idempotent fact and emits only replayable actions. +func (s *channelState) ProcessEvent(_ context.Context, event Event, + _ *Environment) (*StateTransition, error) { + + if event == nil { + return nil, fmt.Errorf("channel event is required") + } + + previousPhase := s.snapshot.Phase + next := s.snapshot.Clone() + changed, err := applyEvent(&next, event) + if err != nil { + return nil, err + } + if !changed { + action, err := PendingAction(next) + if err != nil { + return nil, err + } + + return transitionTo(next, action), nil + } + + action, err := advance(&next) + if err != nil { + return nil, err + } + _, sourceSpent := event.(*SourceSpent) + _, oorFinalized := event.(*OORFinalized) + _, oorAborted := event.(*OORAborted) + if next.Phase == previousPhase && !sourceSpent && !oorFinalized && + !oorAborted { + + action = nil + } + if err := validateSnapshot(next); err != nil { + return nil, err + } + + return transitionTo(next, action), nil +} + +// PendingAction returns the idempotent side effect implied by durable state. +func PendingAction(snapshot Snapshot) (Action, error) { + if err := validateSnapshot(snapshot); err != nil { + return nil, err + } + + switch snapshot.Phase { + case PhaseNegotiating: + return &NegotiateFunding{ + Terms: snapshot.Terms.Clone(), + Source: snapshot.Source.Clone(), + }, nil + + case PhaseBackingReady: + if snapshot.OORFinalized { + return &PrepareRecovery{ + Terms: snapshot.Terms.Clone(), + Source: snapshot.Source.Clone(), + }, nil + } + + return &CommitOOR{ + Terms: snapshot.Terms.Clone(), + Source: snapshot.Source.Clone(), + }, nil + + case PhaseActivating: + return &ActivateChannel{ + Terms: snapshot.Terms.Clone(), + Backing: snapshot.Backing.Clone(), + }, nil + + case PhaseCancelling: + if !snapshot.OORAborted { + return &AbortOOR{ + Terms: snapshot.Terms.Clone(), + Source: snapshot.Source.Clone(), + Reason: snapshot.Failure, + }, nil + } + + var backing *Backing + if snapshot.Backing != nil { + clone := snapshot.Backing.Clone() + backing = &clone + } + + return &CancelFunding{ + Terms: snapshot.Terms.Clone(), + Source: snapshot.Source.Clone(), + Backing: backing, + Reason: snapshot.Failure, + }, nil + + case PhaseMaterializing: + return &PublishChannel{ + Terms: snapshot.Terms.Clone(), + Source: snapshot.Source.Clone(), + Backing: snapshot.Backing.Clone(), + }, nil + + case PhaseOnChain: + if snapshot.SourceConflict != nil { + return &ForceCloseChannel{ + Backing: snapshot.Backing.Clone(), + }, nil + } + + case PhaseCoopClosing: + return &NegotiateCooperativeClose{ + Terms: snapshot.Terms.Clone(), + Source: snapshot.Source.Clone(), + Backing: snapshot.Backing.Clone(), + Request: snapshot.CooperativeCloseRequest.Clone(), + }, nil + + case PhaseCoopCloseSigned: + return &PublishCooperativeClose{ + Terms: snapshot.Terms.Clone(), + Source: snapshot.Source.Clone(), + Close: snapshot.CooperativeClose.Clone(), + }, nil + + case PhaseCoopClosePublished: + return &FinalizeCooperativeClose{ + Terms: snapshot.Terms.Clone(), + Source: snapshot.Source.Clone(), + Backing: snapshot.Backing.Clone(), + Request: snapshot.CooperativeCloseRequest.Clone(), + Close: snapshot.CooperativeClose.Clone(), + }, nil + + case PhaseClosed: + if snapshot.CooperativeClose != nil && + snapshot.SourceConflict != nil { + return &PublishCooperativeClose{ + Terms: snapshot.Terms.Clone(), + Source: snapshot.Source.Clone(), + Close: snapshot.CooperativeClose.Clone(), + }, nil + } + + default: + return nil, nil + } + + return nil, nil +} + +// applyEvent mutates only the fact directly asserted by an event. +func applyEvent(next *Snapshot, event Event) (bool, error) { + switch event := event.(type) { + case *OORPreparationStarted: + return applyOORPreparationStarted(next) + + case *ExpirePrePONR: + return applyPrePONRExpiry(next, event.Reason) + + case *BindVTXO: + return applyBinding(next, event.Binding) + + case *FundingFinalized: + return applyFundingFinalized(next, event.Party) + + case *BackingSigned: + return applyBacking(next, event.Backing) + + case *FundingCanceled: + if next.Phase == PhaseFailed { + return false, nil + } + if next.Phase != PhaseCancelling { + return false, fmt.Errorf("cannot finish funding "+ + "cancellation from %s", next.Phase) + } + + if !next.OORAborted { + return false, fmt.Errorf("cannot finish funding " + + "cancellation before OOR abort") + } + + next.Phase = PhaseFailed + + return true, nil + + case *OORFinalized: + return applyOORFinalized(next, event.SessionID) + + case *RecoveryPackageInstalled: + return applyRecoveryPackageInstalled(next, event.Party) + + case *OORAborted: + return applyOORAborted( + next, event.SessionID, event.Reason, + ) + + case *ChannelActive: + return applyChannelActive(next, wire.OutPoint{ + Hash: event.ChannelPointHash, + Index: event.ChannelPointIndex, + }) + + case *Materialize: + if next.Phase == PhaseMaterializing || + next.Phase == PhaseOnChain { + return false, nil + } + switch next.Phase { + case PhaseActive: + case PhaseCoopClosing: + if next.CooperativeClose == nil { + clearCooperativeClose(next) + } + + default: + return false, fmt.Errorf("cannot materialize "+ + "channel from %s", next.Phase) + } + + next.Phase = PhaseMaterializing + + return true, nil + + case *SourceSpent: + return applySourceSpent( + next, event.OutPoint, event.SpendingTxID, + ) + + case *SourceExpiring: + return applySourceExpiring(next) + + case *CooperativeCloseObserved: + return applyCooperativeCloseObserved(next, event.TxID) + + case *BackingPublished: + return applyBackingPublished(next, event.TxID) + + case *BackingObserved: + return applyBackingObserved(next, event.TxID) + + case *ChannelClosed: + if next.Phase == PhaseClosed { + return false, nil + } + if next.Phase != PhaseActive && next.Phase != PhaseOnChain { + return false, fmt.Errorf("cannot close channel from %s", + next.Phase) + } + + clearCooperativeClose(next) + next.Phase = PhaseClosed + + return true, nil + + case *RequestCooperativeClose: + return applyCooperativeCloseRequest(next, event.Request) + + case *CooperativeCloseSigned: + return applyCooperativeCloseSigned( + next, event.Close, + ) + + case *CooperativeCloseReady: + return applyCloseReceipt(next, event) + + case *CooperativeClosePublished: + return applyCooperativeClosePublished(next, event.TxID) + + case *CooperativeCloseFinalized: + return applyCooperativeCloseFinalized(next) + + case *CooperativeCloseAborted: + return applyCooperativeCloseAborted(next) + + case *Fail: + return applyFailure(next, event.Reason) + + default: + return false, fmt.Errorf("unknown channel event %T", event) + } +} + +// applyOORPreparationStarted arms preparation once while immutable channel +// terms are still the only externally visible protocol fact. +func applyOORPreparationStarted(next *Snapshot) (bool, error) { + if next.OORPreparationStarted { + return false, nil + } + if next.Phase != PhaseRequested || next.Source != nil { + return false, fmt.Errorf("cannot start OOR preparation from %s", + next.Phase) + } + + next.OORPreparationStarted = true + + return true, nil +} + +// applyCloseReceipt permits publication only after the client proves it has +// received the signed settlement. The transaction ID alone is not evidence. +func applyCloseReceipt(next *Snapshot, + event *CooperativeCloseReady) (bool, error) { + + signed := next.CooperativeClose + if signed == nil || signed.AuthorizationReceipt() != event.Receipt { + return false, fmt.Errorf("receipt does not match signed " + + "settlement") + } + switch next.Phase { + case PhaseCoopClosing: + next.Phase = PhaseCoopCloseSigned + + return true, nil + + case PhaseCoopCloseSigned, PhaseCoopClosePublished, PhaseClosed: + return false, nil + + default: + return false, fmt.Errorf("cannot accept close receipt from %s", + next.Phase) + } +} + +// applyBinding starts negotiation only after the exact source is bound. +func applyBinding(next *Snapshot, binding VTXOBinding) (bool, error) { + if err := binding.Validate(next.Terms); err != nil { + return false, err + } + if next.Source != nil { + if bindingsEqual(*next.Source, binding) { + if next.OORPreparationStarted { + return false, nil + } + next.OORPreparationStarted = true + + return true, nil + } + + return false, fmt.Errorf("channel already bound to another " + + "VTXO") + } + if next.Phase != PhaseRequested { + return false, fmt.Errorf("cannot bind VTXO from %s", next.Phase) + } + + clone := binding.Clone() + next.Source = &clone + next.OORPreparationStarted = true + next.Phase = PhaseNegotiating + + return true, nil +} + +// applyFundingFinalized records one native lnd finalization acknowledgement. +func applyFundingFinalized(next *Snapshot, party Party) (bool, error) { + if next.Source == nil { + return false, fmt.Errorf("cannot finalize funding before " + + "VTXO binding") + } + if next.Backing == nil { + return false, fmt.Errorf("cannot finalize funding before " + + "signed backing") + } + if next.Phase == PhaseCancelling || next.Phase == PhaseFailed { + return false, fmt.Errorf("cannot finalize abandoned channel") + } + + switch party { + case PartyClient: + if next.ClientFinalized { + return false, nil + } + next.ClientFinalized = true + + case PartyHub: + if next.HubFinalized { + return false, nil + } + next.HubFinalized = true + + default: + return false, fmt.Errorf("unknown funding party %d", party) + } + + return true, nil +} + +// applyBacking validates and records the immutable signed transaction. +func applyBacking(next *Snapshot, backing Backing) (bool, error) { + if next.Source == nil { + return false, fmt.Errorf("cannot record backing before VTXO " + + "binding") + } + if next.Phase == PhaseCancelling || next.Phase == PhaseFailed { + return false, fmt.Errorf("cannot record backing for " + + "abandoned channel") + } + if err := backing.Validate(next.Terms, *next.Source); err != nil { + return false, err + } + if next.Backing != nil { + if backingsEqual(*next.Backing, backing) { + return false, nil + } + + return false, fmt.Errorf("channel already has another backing") + } + + clone := backing.Clone() + next.Backing = &clone + + return true, nil +} + +// applyOORFinalized records completion of the exact prepared transfer. The +// state machine can activate lnd only after this fact is durable. +func applyOORFinalized(next *Snapshot, sessionID [32]byte) (bool, error) { + if next.Source == nil { + return false, fmt.Errorf("cannot finalize OOR before VTXO " + + "binding") + } + if next.Source.OORSessionID != sessionID { + return false, fmt.Errorf("finalized OOR session does not " + + "match channel source") + } + if next.OORFinalized { + return false, nil + } + if next.OORAborted { + return false, fmt.Errorf("cannot finalize an aborted OOR " + + "transfer") + } + if next.Phase != PhaseBackingReady || !backingReady(*next) { + return false, fmt.Errorf("cannot finalize OOR from %s", + next.Phase) + } + + next.OORFinalized = true + + return true, nil +} + +// applyRecoveryPackageInstalled records the symmetric recovery barrier. It is +// valid before the remote OOR-finalized acknowledgement arrives because the +// package itself can only be exported after actual OOR completion. +func applyRecoveryPackageInstalled(next *Snapshot, party Party) (bool, error) { + if next.Source == nil || next.Backing == nil || !backingReady(*next) { + return false, fmt.Errorf("cannot install channel recovery " + + "before finalized backing") + } + if next.OORAborted || next.Phase == PhaseCancelling || + next.Phase == PhaseFailed { + return false, fmt.Errorf("cannot install recovery for " + + "abandoned channel") + } + switch party { + case PartyClient: + if next.ClientRecoveryReady { + return false, nil + } + next.ClientRecoveryReady = true + + case PartyHub: + if next.HubRecoveryReady { + return false, nil + } + next.HubRecoveryReady = true + + default: + return false, fmt.Errorf("unknown recovery party %d", party) + } + + return true, nil +} + +// applySourceSpent persists the first ancestor conflict and drives the +// virtual channel toward its already-negotiated on-chain resolution path. +func applySourceSpent(next *Snapshot, outpoint wire.OutPoint, + spendingTxID chainhash.Hash) (bool, error) { + + if outpoint == (wire.OutPoint{}) || spendingTxID == (chainhash.Hash{}) { + return false, fmt.Errorf("source spend evidence is incomplete") + } + if next.SourceConflict != nil { + return false, nil + } + if !recoveryAvailable(*next) || !next.OORFinalized { + return false, fmt.Errorf("cannot handle source spend before " + + "recovery is ready") + } + next.SourceConflict = &SourceConflict{ + OutPoint: outpoint, SpendingTxID: spendingTxID, + } + + switch next.Phase { + case PhaseActive: + next.Phase = PhaseMaterializing + + case PhaseCoopClosing, PhaseCoopCloseSigned: + // A receipt proves delivery, not settlement. Defend the source + // without discarding a payout that may still win on chain. + if next.CooperativeClose == nil { + clearCooperativeClose(next) + } + next.Phase = PhaseMaterializing + + case PhaseBackingReady: + next.Phase = PhaseMaterializing + + case PhaseActivating, PhaseMaterializing, PhaseOnChain, + PhaseCoopClosePublished, PhaseClosed: + + default: + return false, fmt.Errorf("cannot handle source spend from %s", + next.Phase) + } + + return true, nil +} + +// applySourceExpiring starts the existing unilateral handoff without waiting +// for a peer to activate an already funded source. Released refresh authority +// remains valid, but cannot indefinitely veto protection from batch expiry. +func applySourceExpiring(next *Snapshot) (bool, error) { + switch next.Phase { + case PhaseMaterializing, PhaseOnChain, + PhaseCoopClosePublished, PhaseClosed, PhaseFailed: + return false, nil + + case PhaseBackingReady, PhaseActivating, PhaseActive, + PhaseCoopClosing, PhaseCoopCloseSigned: + + if !next.OORFinalized || !recoveryAvailable(*next) { + return false, fmt.Errorf("source expiry requires " + + "finalized funding and local recovery") + } + if next.CooperativeClose == nil { + clearCooperativeClose(next) + } + next.Phase = PhaseMaterializing + + return true, nil + + default: + return false, fmt.Errorf("cannot protect expiring "+ + "source from %s", next.Phase) + } +} + +// recoveryAvailable reports whether an endpoint has installed the complete +// signed exit. Both endpoints are required for activation, but a missing peer +// must not veto unilateral recovery of an already finalized source. +func recoveryAvailable(snapshot Snapshot) bool { + return snapshot.ClientRecoveryReady || snapshot.HubRecoveryReady +} + +// applyOORAborted records a definitive pre-PONR failure, allowing lnd's +// pending channel reservation to be removed without risking a gifted VTXO. +func applyOORAborted(next *Snapshot, sessionID [32]byte, + reason string) (bool, error) { + + if next.Source == nil { + return false, fmt.Errorf("cannot abort OOR before VTXO binding") + } + if next.Source.OORSessionID != sessionID { + return false, fmt.Errorf("aborted OOR session does not match " + + "channel source") + } + if next.OORFinalized { + return false, fmt.Errorf("cannot abort a finalized OOR " + + "transfer") + } + if next.OORAborted { + return false, nil + } + if next.Phase != PhaseNegotiating && next.Phase != PhaseCancelling && + next.Phase != PhaseBackingReady { + return false, fmt.Errorf("cannot abort OOR from %s", next.Phase) + } + if next.Failure == "" { + if reason == "" { + return false, fmt.Errorf("OOR abort reason is required") + } + next.Failure = reason + } + + next.OORAborted = true + next.Phase = PhaseCancelling + + return true, nil +} + +// applyChannelActive verifies lnd activated the negotiated funding output. +func applyChannelActive(next *Snapshot, + channelPoint wire.OutPoint) (bool, error) { + + if next.Phase == PhaseActive || next.Phase == PhaseMaterializing || + next.Phase == PhaseOnChain || next.Phase == PhaseCoopClosing || + next.Phase == PhaseCoopCloseSigned || + next.Phase == PhaseCoopClosePublished || + next.Phase == PhaseClosed { + + if next.Backing.ChannelPoint == channelPoint { + return false, nil + } + } + if next.Phase != PhaseActivating { + return false, fmt.Errorf("cannot activate channel from %s", + next.Phase) + } + if next.Backing.ChannelPoint != channelPoint { + return false, fmt.Errorf("lnd activated an unexpected " + + "channel point") + } + + if next.SourceConflict != nil { + next.Phase = PhaseMaterializing + } else { + next.Phase = PhaseActive + } + + return true, nil +} + +// applyBackingPublished verifies materialization of the expected transaction. +func applyBackingPublished(next *Snapshot, txID [32]byte) (bool, error) { + if next.Phase == PhaseOnChain { + if next.Backing.ChannelPoint.Hash == txID { + return false, nil + } + } + if next.Phase != PhaseMaterializing { + return false, fmt.Errorf("cannot publish backing from %s", + next.Phase) + } + if next.Backing.ChannelPoint.Hash != txID { + return false, fmt.Errorf("published backing transaction does " + + "not match") + } + + next.BackingPublished = true + next.Phase = PhaseOnChain + + return true, nil +} + +// applyBackingObserved gives independently observed chain state precedence +// over a virtual or unfinished cooperative lifecycle. A fully resolved lnd +// channel proves any conflicting OOR close can no longer finalize. +func applyBackingObserved(next *Snapshot, txID [32]byte) (bool, error) { + if next.Backing == nil || next.Backing.ChannelPoint.Hash != txID { + return false, fmt.Errorf("observed backing transaction does " + + "not match") + } + if next.Phase == PhaseOnChain { + return false, nil + } + switch next.Phase { + case PhaseActivating, PhaseActive, PhaseMaterializing, + PhaseCoopClosing, PhaseCoopCloseSigned: + + default: + return false, fmt.Errorf("cannot observe backing from %s", + next.Phase) + } + + clearCooperativeClose(next) + next.BackingPublished = true + next.Phase = PhaseOnChain + + return true, nil +} + +// clearCooperativeClose removes an attempt only while the backing resolution +// is proven to be the sole remaining path. +func clearCooperativeClose(next *Snapshot) { + next.CooperativeCloseRequest = nil + next.CooperativeClose = nil +} + +// applyCooperativeCloseRequest fixes all payout terms before either endpoint +// quiesces its native lnd link. +func applyCooperativeCloseRequest(next *Snapshot, + request CooperativeCloseRequest) (bool, error) { + + if err := request.Validate(); err != nil { + return false, err + } + if next.CooperativeCloseRequest != nil { + if cooperativeCloseRequestsEqual( + *next.CooperativeCloseRequest, request, + ) { + return false, nil + } + + return false, fmt.Errorf("channel already has another " + + "cooperative close request") + } + if next.Phase != PhaseActive { + return false, fmt.Errorf("cannot cooperatively close "+ + "channel from %s", next.Phase) + } + clone := request.Clone() + next.CooperativeCloseRequest = &clone + next.Phase = PhaseCoopClosing + + return true, nil +} + +// applyCooperativeCloseSigned makes the exact authorization replayable in +// this endpoint's database. Only the client submits it to the OOR actor. +func applyCooperativeCloseSigned(next *Snapshot, + settlement CooperativeClose) (bool, error) { + + if next.CooperativeCloseRequest == nil || next.Source == nil { + return false, fmt.Errorf("cooperative close request is missing") + } + if err := settlement.Validate( + next.Terms, *next.Source, *next.CooperativeCloseRequest, + ); err != nil { + return false, err + } + if next.Phase != PhaseCoopClosing && + next.Phase != PhaseCoopCloseSigned && + next.Phase != PhaseCoopClosePublished && + next.Phase != PhaseClosed { + return false, fmt.Errorf("cannot authorize cooperative "+ + "close from %s", next.Phase) + } + if next.CooperativeClose != nil { + if !cooperativeClosesEqual(*next.CooperativeClose, settlement) { + return false, fmt.Errorf("channel already has " + + "another cooperative close authorization") + } + + return false, nil + } + clone := settlement.Clone() + next.CooperativeClose = &clone + + return true, nil +} + +// applyCooperativeClosePublished verifies the ordinary OOR actor finalized the +// exact close before lnd state can be archived. The historical function name +// is retained because its event type predates the OOR implementation. +func applyCooperativeClosePublished(next *Snapshot, + txID chainhash.Hash) (bool, error) { + + if next.CooperativeClose == nil { + return false, fmt.Errorf("authorized cooperative close is " + + "missing") + } + if next.CooperativeClose.TxID != txID { + return false, fmt.Errorf("finalized cooperative close does " + + "not match") + } + if next.Phase == PhaseMaterializing || next.Phase == PhaseOnChain { + + // A competing exit may already have published. Keep native + // watchers until local chain evidence proves which spend won. + return false, nil + } + if next.Phase == PhaseCoopClosePublished || next.Phase == PhaseClosed { + return false, nil + } + if next.Phase != PhaseCoopCloseSigned { + return false, fmt.Errorf("cannot finalize cooperative "+ + "close from %s", next.Phase) + } + next.Phase = PhaseCoopClosePublished + + return true, nil +} + +// applyCooperativeCloseObserved chooses the exact confirmed payout over an +// expiring channel's competing backing. Both authorizations are retained until +// one transaction actually wins on chain; neither peer can assert this fact. +func applyCooperativeCloseObserved(next *Snapshot, + txID chainhash.Hash) (bool, error) { + + if next.CooperativeClose == nil || next.CooperativeClose.TxID != txID { + return false, fmt.Errorf("observed cooperative payout does " + + "not match authorization") + } + if next.Phase == PhaseCoopClosePublished || next.Phase == PhaseClosed { + return false, nil + } + if next.Phase != PhaseMaterializing && next.Phase != PhaseOnChain { + return false, fmt.Errorf("unexpected observed cooperative " + + "payout phase") + } + next.BackingPublished = false + next.Phase = PhaseCoopClosePublished + + return true, nil +} + +// applyCooperativeCloseFinalized closes the local FSM only after lnd archives +// the channel. The peer independently archives against the same OOR outcome. +func applyCooperativeCloseFinalized(next *Snapshot) (bool, error) { + if next.CooperativeClose == nil || + (next.Phase != PhaseCoopClosePublished && + next.Phase != PhaseClosed) { + return false, fmt.Errorf("cannot finalize cooperative "+ + "close from %s", next.Phase) + } + if next.Phase == PhaseClosed { + return false, nil + } + next.Phase = PhaseClosed + + return true, nil +} + +// applyCooperativeCloseAborted permits recovery only before the hub-authorized +// OOR package is durable at both endpoints. +func applyCooperativeCloseAborted(next *Snapshot) (bool, error) { + if next.Phase == PhaseActive && next.CooperativeCloseRequest == nil { + return false, nil + } + if next.Phase != PhaseCoopClosing || next.CooperativeClose != nil { + return false, fmt.Errorf("cannot abort cooperative "+ + "close from %s", next.Phase) + } + next.CooperativeCloseRequest = nil + next.Phase = PhaseActive + + return true, nil +} + +// applyPrePONRExpiry lets a stale timer lose cleanly once the commit action is +// replayable. The phase check is applied against the CAS-reloaded state, not +// the record that the expiry scan originally observed. +func applyPrePONRExpiry(next *Snapshot, reason string) (bool, error) { + if reason == "" { + return false, fmt.Errorf("expiry reason is required") + } + if next.Phase != PhaseRequested && next.Phase != PhaseNegotiating { + return false, nil + } + + return applyFailure(next, reason) +} + +// applyFailure permits abandonment only before the OOR commit action is +// durable. A commit-time failure must arrive as OORAborted so the coordinator +// knows the transfer stayed before its point of no return. +func applyFailure(next *Snapshot, reason string) (bool, error) { + if next.Phase == PhaseFailed { + if next.Failure == reason { + return false, nil + } + + return false, fmt.Errorf("channel already failed for another " + + "reason") + } + if next.Phase == PhaseCancelling { + if next.Failure == reason { + return false, nil + } + + return false, fmt.Errorf("channel already cancelling for " + + "another reason") + } + if next.Phase != PhaseRequested && next.Phase != PhaseNegotiating { + return false, fmt.Errorf("cannot fail channel after safety " + + "boundary") + } + if reason == "" { + return false, fmt.Errorf("failure reason is required") + } + + next.Failure = reason + if next.Source == nil { + next.Phase = PhaseFailed + } else { + next.Phase = PhaseCancelling + } + + return true, nil +} + +// advance derives the next phase and replayable action from durable facts. +func advance(next *Snapshot) (Action, error) { + if next.Phase == PhaseNegotiating && backingReady(*next) { + next.Phase = PhaseBackingReady + } + + switch next.Phase { + case PhaseNegotiating: + return &NegotiateFunding{ + Terms: next.Terms.Clone(), + Source: next.Source.Clone(), + }, nil + + case PhaseActivating: + return &ActivateChannel{ + Terms: next.Terms.Clone(), + Backing: next.Backing.Clone(), + }, nil + + case PhaseBackingReady: + if next.OORFinalized && next.RecoveryReady() { + next.Phase = PhaseActivating + + return &ActivateChannel{ + Terms: next.Terms.Clone(), + Backing: next.Backing.Clone(), + }, nil + } + if next.OORFinalized { + return &PrepareRecovery{ + Terms: next.Terms.Clone(), + Source: next.Source.Clone(), + }, nil + } + + return &CommitOOR{ + Terms: next.Terms.Clone(), + Source: next.Source.Clone(), + }, nil + + case PhaseMaterializing: + return &PublishChannel{ + Terms: next.Terms.Clone(), + Source: next.Source.Clone(), + Backing: next.Backing.Clone(), + }, nil + + case PhaseOnChain: + if next.SourceConflict != nil { + return &ForceCloseChannel{ + Backing: next.Backing.Clone(), + }, nil + } + + case PhaseCoopClosing: + return &NegotiateCooperativeClose{ + Terms: next.Terms.Clone(), + Source: next.Source.Clone(), + Backing: next.Backing.Clone(), + Request: next.CooperativeCloseRequest.Clone(), + }, nil + + case PhaseCoopCloseSigned: + return &PublishCooperativeClose{ + Terms: next.Terms.Clone(), + Source: next.Source.Clone(), + Close: next.CooperativeClose.Clone(), + }, nil + + case PhaseCoopClosePublished: + return &FinalizeCooperativeClose{ + Terms: next.Terms.Clone(), + Source: next.Source.Clone(), + Backing: next.Backing.Clone(), + Request: next.CooperativeCloseRequest.Clone(), + Close: next.CooperativeClose.Clone(), + }, nil + + case PhaseClosed: + if next.CooperativeClose != nil && next.SourceConflict != nil { + return &PublishCooperativeClose{ + Terms: next.Terms.Clone(), + Source: next.Source.Clone(), + Close: next.CooperativeClose.Clone(), + }, nil + } + + case PhaseCancelling: + if !next.OORAborted { + return &AbortOOR{ + Terms: next.Terms.Clone(), + Source: next.Source.Clone(), + Reason: next.Failure, + }, nil + } + + var backing *Backing + if next.Backing != nil { + clone := next.Backing.Clone() + backing = &clone + } + + return &CancelFunding{ + Terms: next.Terms.Clone(), + Source: next.Source.Clone(), + Backing: backing, + Reason: next.Failure, + }, nil + + case PhaseRequested, PhaseActive, PhaseFailed: + } + + return nil, nil +} + +// transitionTo wraps one durable next state and optional action. +func transitionTo(snapshot Snapshot, action Action) *StateTransition { + transition := &StateTransition{ + NextState: &channelState{ + snapshot: snapshot, + }, + } + if action != nil { + transition.NewEvents = fn.Some(EmittedEvent{ + Outbox: []Action{action}, + }) + } + + return transition +} + +// validateSnapshot rejects impossible persisted combinations. +func validateSnapshot(snapshot Snapshot) error { + if err := snapshot.Terms.Validate(); err != nil { + return err + } + if snapshot.Phase < PhaseRequested || + snapshot.Phase > PhaseCoopClosePublished { + return fmt.Errorf("unknown channel phase %d", snapshot.Phase) + } + if snapshot.Source != nil { + if err := snapshot.Source.Validate(snapshot.Terms); err != nil { + return err + } + } + if snapshot.Backing != nil { + if snapshot.Source == nil { + return fmt.Errorf("backing has no bound VTXO") + } + if err := snapshot.Backing.Validate( + snapshot.Terms, *snapshot.Source, + ); err != nil { + return err + } + } + if snapshot.Source == nil && (snapshot.Backing != nil || + snapshot.ClientFinalized || snapshot.HubFinalized || + snapshot.OORFinalized || + snapshot.OORAborted || + snapshot.ClientRecoveryReady || snapshot.HubRecoveryReady || + snapshot.SourceConflict != nil) { + return fmt.Errorf("funding facts require a bound VTXO") + } + if snapshot.Backing == nil && (snapshot.ClientFinalized || + snapshot.HubFinalized) { + return fmt.Errorf("funding finalization requires signed " + + "backing") + } + requiresBacking := snapshot.Phase == PhaseBackingReady || + snapshot.Phase == PhaseActivating || + snapshot.Phase == PhaseActive || + snapshot.Phase == PhaseMaterializing || + snapshot.Phase == PhaseOnChain || + snapshot.Phase == PhaseCoopClosing || + snapshot.Phase == PhaseCoopCloseSigned || + snapshot.Phase == PhaseCoopClosePublished || + snapshot.Phase == PhaseClosed + if requiresBacking && !backingReady(snapshot) { + return fmt.Errorf("phase %s requires finalized backing", + snapshot.Phase) + } + if snapshot.OORFinalized && !backingReady(snapshot) { + return fmt.Errorf("OOR finalization requires finalized backing") + } + if snapshot.OORFinalized && snapshot.OORAborted { + return fmt.Errorf("OOR transfer cannot be finalized and " + + "aborted") + } + if (snapshot.ClientRecoveryReady || snapshot.HubRecoveryReady) && + !backingReady(snapshot) { + return fmt.Errorf("channel recovery requires finalized backing") + } + if snapshot.SourceConflict != nil && (!recoveryAvailable(snapshot) || + !snapshot.OORFinalized) { + return fmt.Errorf("source conflict requires ready recovery") + } + if snapshot.BackingPublished && snapshot.Phase != PhaseOnChain && + snapshot.Phase != PhaseClosed { + return fmt.Errorf("published backing requires on-chain phase") + } + if err := validateCooperativeCloseSnapshot(snapshot); err != nil { + return err + } + if (snapshot.Phase == PhaseCancelling || + snapshot.Phase == PhaseFailed) && snapshot.Failure == "" { + return fmt.Errorf("abandoned channel requires a reason") + } + if snapshot.Phase != PhaseCancelling && + snapshot.Phase != PhaseFailed && snapshot.Failure != "" { + return fmt.Errorf("non-failed channel cannot have a failure " + + "reason") + } + + switch snapshot.Phase { + case PhaseRequested: + if snapshot.Source != nil { + return fmt.Errorf("requested channel already has a " + + "bound VTXO") + } + if snapshot.Backing != nil || snapshot.ClientFinalized || + snapshot.HubFinalized || snapshot.OORFinalized || + snapshot.OORAborted || snapshot.ClientRecoveryReady || + snapshot.HubRecoveryReady || + snapshot.SourceConflict != nil || + snapshot.BackingPublished { + return fmt.Errorf("requested channel has advanced " + + "facts") + } + + case PhaseNegotiating: + if snapshot.Source == nil { + return fmt.Errorf("negotiating channel has no bound " + + "VTXO") + } + if snapshot.OORFinalized || snapshot.OORAborted || + snapshot.ClientRecoveryReady || + snapshot.HubRecoveryReady || + snapshot.SourceConflict != nil { + return fmt.Errorf("negotiating channel has terminal " + + "OOR facts") + } + + case PhaseBackingReady: + if snapshot.OORAborted || snapshot.SourceConflict != nil { + return fmt.Errorf("backing-ready channel has " + + "terminal OOR facts") + } + if snapshot.OORFinalized && snapshot.RecoveryReady() { + return fmt.Errorf("recovery-ready channel must be " + + "activating") + } + + case PhaseMaterializing, PhaseOnChain: + if !snapshot.OORFinalized || snapshot.OORAborted || + !recoveryAvailable(snapshot) { + return fmt.Errorf("unilateral recovery requires " + + "finalized funding and an installed exit") + } + + case PhaseActivating, PhaseActive, + PhaseClosed, PhaseCoopClosing, PhaseCoopCloseSigned, + PhaseCoopClosePublished: + + ready := snapshot.RecoveryReady() + if snapshot.Phase == PhaseClosed && snapshot.BackingPublished { + ready = recoveryAvailable(snapshot) + } + if !snapshot.OORFinalized || snapshot.OORAborted || + !ready { + return fmt.Errorf("channel advanced before OOR " + + "finalization and recovery installation") + } + + case PhaseCancelling: + if snapshot.Source == nil { + return fmt.Errorf("cancelling channel has no bound " + + "VTXO") + } + if snapshot.OORFinalized || snapshot.BackingPublished { + return fmt.Errorf("failed channel crossed the safety " + + "boundary") + } + + case PhaseFailed: + if snapshot.OORFinalized || snapshot.BackingPublished { + return fmt.Errorf("failed channel crossed the safety " + + "boundary") + } + if snapshot.Source != nil && !snapshot.OORAborted { + return fmt.Errorf("failed channel did not abort " + + "prepared OOR") + } + } + + if snapshot.Phase == PhaseOnChain && !snapshot.BackingPublished { + return fmt.Errorf("on-chain phase requires published backing") + } + + return nil +} + +// validateCooperativeCloseSnapshot checks artifacts and acknowledgements owned +// by the in-Ark OOR close lifecycle. +func validateCooperativeCloseSnapshot(snapshot Snapshot) error { + if snapshot.CooperativeCloseRequest != nil { + request := snapshot.CooperativeCloseRequest + if err := request.Validate(); err != nil { + return err + } + } + if snapshot.CooperativeClose != nil { + if snapshot.Source == nil || + snapshot.CooperativeCloseRequest == nil { + return fmt.Errorf("cooperative close has no request " + + "or source") + } + if err := snapshot.CooperativeClose.Validate( + snapshot.Terms, *snapshot.Source, + *snapshot.CooperativeCloseRequest, + ); err != nil { + return err + } + } + switch snapshot.Phase { + case PhaseMaterializing, PhaseOnChain, PhaseClosed: + // Keep any prior authorization until the winning spend is + // known. + + case PhaseCoopClosing: + if snapshot.CooperativeCloseRequest == nil { + return fmt.Errorf("invalid cooperative close " + + "negotiation") + } + + case PhaseCoopCloseSigned, PhaseCoopClosePublished: + if snapshot.CooperativeClose == nil { + return fmt.Errorf("cooperative close lacks " + + "authorization") + } + + default: + if snapshot.CooperativeCloseRequest != nil { + return fmt.Errorf("phase %s has cooperative "+ + "close facts", snapshot.Phase) + } + } + + return nil +} + +// backingReady checks the durable prerequisites for committing the OOR source. +func backingReady(snapshot Snapshot) bool { + return snapshot.Source != nil && snapshot.Backing != nil && + snapshot.ClientFinalized && snapshot.HubFinalized +} + +// bindingsEqual checks idempotency for an immutable VTXO binding. +func bindingsEqual(a, b VTXOBinding) bool { + return a.OutPoint == b.OutPoint && a.Amount == b.Amount && + a.OORSessionID == b.OORSessionID && + string(a.PolicyTemplate) == string(b.PolicyTemplate) && + string(a.PkScript) == string(b.PkScript) +} + +// backingsEqual checks idempotency for immutable transaction bytes. +func backingsEqual(a, b Backing) bool { + return a.ChannelPoint == b.ChannelPoint && + string(a.Transaction) == string(b.Transaction) +} + +// cooperativeCloseRequestsEqual checks immutable payout instructions. +func cooperativeCloseRequestsEqual(a, b CooperativeCloseRequest) bool { + return a.Initiator == b.Initiator && + string(a.ClientDeliveryScript) == + string(b.ClientDeliveryScript) && + string(a.HubDeliveryScript) == string(b.HubDeliveryScript) +} + +// cooperativeClosesEqual checks the hub-authorized OOR close artifact. +func cooperativeClosesEqual(a, b CooperativeClose) bool { + return a.TxID == b.TxID && + cooperativeCloseProposalsEqual(a.Proposal, b.Proposal) +} + +// cooperativeCloseProposalsEqual checks canonical unsigned OOR facts. +func cooperativeCloseProposalsEqual(a, b CooperativeCloseProposal) bool { + return a.CommitmentHeight == b.CommitmentHeight && + a.ClientBalance == b.ClientBalance && + a.HubBalance == b.HubBalance && + a.ClientOutput == b.ClientOutput && + a.HubOutput == b.HubOutput && + string(a.Transaction) == string(b.Transaction) +} diff --git a/arkchannel/state_test.go b/arkchannel/state_test.go new file mode 100644 index 000000000..a4b11e5e2 --- /dev/null +++ b/arkchannel/state_test.go @@ -0,0 +1,1604 @@ +package arkchannel + +import ( + "bytes" + "context" + "errors" + "sort" + "sync" + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/psbt/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightningnetwork/lnd/lnwire" + "github.com/stretchr/testify/require" +) + +// testRecordObserver captures post-commit channel projections. +type testRecordObserver struct { + records []Record +} + +// ObserveArkChannel records one already-durable channel revision. +func (o *testRecordObserver) ObserveArkChannel(_ context.Context, + record Record) { + + o.records = append(o.records, record) +} + +// TestOORChannelLifecycle proves the prepared transfer commits only after both +// lnd endpoints and the immutable backing transaction are durable. +func TestOORChannelLifecycle(t *testing.T) { + t.Parallel() + + store := newMemoryStore() + coordinator, err := NewCoordinator(store) + require.NoError(t, err) + + terms := testTerms(t, KindPromotion) + record, err := coordinator.Request(t.Context(), terms) + require.NoError(t, err) + require.Equal(t, PhaseRequested, record.Snapshot.Phase) + + binding := testBinding(terms) + record, actions, err := coordinator.Apply( + t.Context(), terms.ID, &BindVTXO{ + Binding: binding, + }, + ) + require.NoError(t, err) + require.NotNil(t, record.Snapshot.Source) + require.Equal(t, PhaseNegotiating, record.Snapshot.Phase) + require.IsType(t, &NegotiateFunding{}, requireOneAction(t, actions)) + + backing := testBacking(t, terms, binding) + for _, event := range []Event{ + &BackingSigned{ + Backing: backing, + }, + &FundingFinalized{ + Party: PartyClient, + }, + } { + record, _, err = coordinator.Apply(t.Context(), terms.ID, event) + require.NoError(t, err) + require.False(t, record.Snapshot.ReadyToCommitOOR()) + } + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &FundingFinalized{ + Party: PartyHub, + }, + ) + require.NoError(t, err) + require.IsType(t, &CommitOOR{}, requireOneAction(t, actions)) + require.Equal(t, PhaseBackingReady, record.Snapshot.Phase) + require.True(t, record.Snapshot.ReadyToCommitOOR()) + commitRevision := record.Revision + + // A retry after CommitOOR failed must replay that durable action. + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &FundingFinalized{ + Party: PartyHub, + }, + ) + require.NoError(t, err) + require.Equal(t, commitRevision, record.Revision) + require.IsType(t, &CommitOOR{}, requireOneAction(t, actions)) + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &OORFinalized{ + SessionID: binding.OORSessionID, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseBackingReady, record.Snapshot.Phase) + require.IsType(t, &PrepareRecovery{}, requireOneAction(t, actions)) + require.False(t, record.Snapshot.RecoveryReady()) + + _, _, err = coordinator.Apply( + t.Context(), terms.ID, &Fail{ + Reason: "peer disconnected", + }, + ) + require.ErrorContains(t, err, "after safety boundary") + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &RecoveryPackageInstalled{ + Party: PartyClient, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseBackingReady, record.Snapshot.Phase) + require.Empty(t, actions) + require.True(t, record.Snapshot.ClientRecoveryReady) + require.False(t, record.Snapshot.HubRecoveryReady) + recoveryRevision := record.Revision + + // Retrying the stored acknowledgement after package installation failed + // must re-run the remaining recovery action. + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &RecoveryPackageInstalled{ + Party: PartyClient, + }, + ) + require.NoError(t, err) + require.Equal(t, recoveryRevision, record.Revision) + require.IsType(t, &PrepareRecovery{}, requireOneAction(t, actions)) + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &RecoveryPackageInstalled{ + Party: PartyHub, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseActivating, record.Snapshot.Phase) + require.IsType(t, &ActivateChannel{}, requireOneAction(t, actions)) + require.True(t, record.Snapshot.RecoveryReady()) + + _, resumed, err := coordinator.Resume(t.Context(), terms.ID) + require.NoError(t, err) + require.IsType(t, &ActivateChannel{}, requireOneAction(t, resumed)) + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &ChannelActive{ + ChannelPointHash: backing.ChannelPoint.Hash, + ChannelPointIndex: backing.ChannelPoint.Index, + }, + ) + require.NoError(t, err) + require.Empty(t, actions) + require.Equal(t, PhaseActive, record.Snapshot.Phase) + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &Materialize{}, + ) + require.NoError(t, err) + require.Equal(t, PhaseMaterializing, record.Snapshot.Phase) + require.IsType(t, &PublishChannel{}, requireOneAction(t, actions)) + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &BackingPublished{ + TxID: backing.ChannelPoint.Hash, + }, + ) + require.NoError(t, err) + require.Empty(t, actions) + require.Equal(t, PhaseOnChain, record.Snapshot.Phase) + + record, _, err = coordinator.Apply( + t.Context(), terms.ID, &ChannelClosed{}, + ) + require.NoError(t, err) + require.Equal(t, PhaseClosed, record.Snapshot.Phase) +} + +// TestSourceConflictDrivesForceClose proves confirmed ancestry evidence is a +// durable trigger for backing publication followed by native lnd force close. +func TestSourceConflictDrivesForceClose(t *testing.T) { + t.Parallel() + + terms := testTerms(t, KindPromotion) + source := testBinding(terms) + backing := testBacking(t, terms, source) + coordinator := activeCooperativeChannel(t, terms, source) + conflict := &SourceSpent{ + OutPoint: source.OutPoint, + SpendingTxID: chainhash.Hash{ + 99, + }, + } + + record, actions, err := coordinator.Apply( + t.Context(), terms.ID, conflict, + ) + require.NoError(t, err) + require.Equal(t, PhaseMaterializing, record.Snapshot.Phase) + require.Equal( + t, conflict.OutPoint, record.Snapshot.SourceConflict.OutPoint, + ) + require.Equal( + t, conflict.SpendingTxID, + record.Snapshot.SourceConflict.SpendingTxID, + ) + require.IsType(t, &PublishChannel{}, requireOneAction(t, actions)) + + // Replaying the same confirmed fact must also replay an action whose + // prior execution could have failed after the transition was stored. + _, actions, err = coordinator.Apply(t.Context(), terms.ID, conflict) + require.NoError(t, err) + require.IsType(t, &PublishChannel{}, requireOneAction(t, actions)) + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &BackingPublished{ + TxID: backing.ChannelPoint.Hash, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseOnChain, record.Snapshot.Phase) + require.True(t, record.Snapshot.BackingPublished) + require.IsType(t, &ForceCloseChannel{}, requireOneAction(t, actions)) + + _, actions, err = coordinator.Apply(t.Context(), terms.ID, conflict) + require.NoError(t, err) + require.IsType(t, &ForceCloseChannel{}, requireOneAction(t, actions)) +} + +// TestSourceConflictDuringActivationFinishesActivationFirst proves a parent +// conflict cannot strand a channel between lnd funding and materialization. +func TestSourceConflictDuringActivationFinishesActivationFirst(t *testing.T) { + t.Parallel() + + store := newMemoryStore() + coordinator, err := NewCoordinator(store) + require.NoError(t, err) + terms := testTerms(t, KindPromotion) + _, err = coordinator.Request(t.Context(), terms) + require.NoError(t, err) + source := testBinding(terms) + backing := testBacking(t, terms, source) + for _, event := range []Event{ + &BindVTXO{ + Binding: source, + }, + &BackingSigned{ + Backing: backing, + }, + &FundingFinalized{ + Party: PartyClient, + }, + &FundingFinalized{ + Party: PartyHub, + }, + &OORFinalized{ + SessionID: source.OORSessionID, + }, + &RecoveryPackageInstalled{ + Party: PartyClient, + }, + &RecoveryPackageInstalled{ + Party: PartyHub, + }, + } { + _, _, err = coordinator.Apply(t.Context(), terms.ID, event) + require.NoError(t, err) + } + + conflict := &SourceSpent{ + OutPoint: source.OutPoint, + SpendingTxID: chainhash.Hash{ + 100, + }, + } + record, actions, err := coordinator.Apply( + t.Context(), terms.ID, conflict, + ) + require.NoError(t, err) + require.Equal(t, PhaseActivating, record.Snapshot.Phase) + require.IsType(t, &ActivateChannel{}, requireOneAction(t, actions)) + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &ChannelActive{ + ChannelPointHash: backing.ChannelPoint.Hash, + ChannelPointIndex: backing.ChannelPoint.Index, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseMaterializing, record.Snapshot.Phase) + require.IsType(t, &PublishChannel{}, requireOneAction(t, actions)) +} + +// TestSignedCloseSourceSpendResumesMaterialization verifies that a delivery +// receipt cannot veto recovery or prove a signed payout was confirmed. +func TestSignedCloseSourceSpendResumesMaterialization(t *testing.T) { + t.Parallel() + + terms, source, request, clientKey, hubKey, operatorKey := + testCooperativeCloseFixture(t, KindPromotion, 5_000) + coordinator := activeCooperativeChannel(t, terms, source) + _, _, err := coordinator.Apply( + t.Context(), terms.ID, &RequestCooperativeClose{ + Request: request, + }, + ) + require.NoError(t, err) + template, err := NewCooperativeCloseTemplate( + terms, source, request, 70_000, 30_000, 5, + ) + require.NoError(t, err) + settlement := completeTestCooperativeClose( + t, template, terms, source, request, clientKey, hubKey, + operatorKey, + ) + for _, event := range []Event{ + &CooperativeCloseSigned{ + Close: settlement, + }, + &CooperativeCloseReady{ + Receipt: settlement.AuthorizationReceipt(), + }, + } { + _, _, err = coordinator.Apply(t.Context(), terms.ID, event) + require.NoError(t, err) + } + + record, actions, err := coordinator.Apply( + t.Context(), terms.ID, &SourceSpent{ + OutPoint: source.OutPoint, + SpendingTxID: chainhash.Hash{ + 101, + }, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseMaterializing, record.Snapshot.Phase) + require.False(t, record.Snapshot.BackingPublished) + require.Equal(t, &settlement, record.Snapshot.CooperativeClose) + require.IsType(t, &PublishChannel{}, requireOneAction(t, actions)) + replayed, err := PendingAction(record.Snapshot) + require.NoError(t, err) + require.Equal(t, actions[0], replayed) + + record, _, err = coordinator.Apply( + t.Context(), terms.ID, &CooperativeClosePublished{ + TxID: settlement.TxID, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseMaterializing, record.Snapshot.Phase) + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &CooperativeCloseObserved{ + TxID: settlement.TxID, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseCoopClosePublished, record.Snapshot.Phase) + require.IsType( + t, &FinalizeCooperativeClose{}, requireOneAction(t, actions), + ) +} + +// TestSourceConflictPreservesReleasedCooperativeClose proves recovery can +// materialize backing without pretending a released authorization is revoked. +func TestSourceConflictPreservesReleasedCooperativeClose(t *testing.T) { + t.Parallel() + + terms, source, request, clientKey, hubKey, operatorKey := + testCooperativeCloseFixture(t, KindPromotion, 5_000) + template, err := NewCooperativeCloseTemplate( + terms, source, request, 70_000, 30_000, 5, + ) + require.NoError(t, err) + settlement := completeTestCooperativeClose( + t, template, terms, source, request, clientKey, hubKey, + operatorKey, + ) + + for _, test := range []struct { + name string + signed bool + }{ + { + name: "before signatures", + }, + { + name: "after signature release", + signed: true, + }, + } { + t.Run(test.name, func(t *testing.T) { + coordinator := activeCooperativeChannel( + t, terms, source, + ) + _, _, err := coordinator.Apply( + t.Context(), terms.ID, &RequestCooperativeClose{ + Request: request, + }, + ) + require.NoError(t, err) + if test.signed { + _, _, err = coordinator.Apply( + t.Context(), terms.ID, + &CooperativeCloseSigned{ + Close: settlement, + }, + ) + require.NoError(t, err) + } + + record, actions, err := coordinator.Apply( + t.Context(), terms.ID, &SourceSpent{ + OutPoint: source.OutPoint, + SpendingTxID: chainhash.Hash{ + 102, + }, + }, + ) + require.NoError(t, err) + require.Equal( + t, PhaseMaterializing, record.Snapshot.Phase, + ) + if !test.signed { + require.Nil( + t, + record.Snapshot.CooperativeCloseRequest, + ) + require.Nil(t, record.Snapshot.CooperativeClose) + } else { + require.NotNil( + t, + record.Snapshot.CooperativeCloseRequest, + ) + require.NotNil( + t, record.Snapshot.CooperativeClose, + ) + } + require.IsType( + t, &PublishChannel{}, + requireOneAction(t, actions), + ) + }) + } +} + +// TestMaterializePreservesReleasedCooperativeClose proves materialization +// cannot revoke a signature before both durable acknowledgements arrive. +func TestMaterializePreservesReleasedCooperativeClose(t *testing.T) { + t.Parallel() + + terms, source, request, clientKey, hubKey, operatorKey := + testCooperativeCloseFixture(t, KindPromotion, 5_000) + template, err := NewCooperativeCloseTemplate( + terms, source, request, 70_000, 30_000, 5, + ) + require.NoError(t, err) + settlement := completeTestCooperativeClose( + t, template, terms, source, request, clientKey, hubKey, + operatorKey, + ) + coordinator := activeCooperativeChannel(t, terms, source) + _, _, err = coordinator.Apply( + t.Context(), terms.ID, &RequestCooperativeClose{ + Request: request, + }, + ) + require.NoError(t, err) + _, _, err = coordinator.Apply( + t.Context(), terms.ID, &CooperativeCloseSigned{ + Close: settlement, + }, + ) + require.NoError(t, err) + + record, actions, err := coordinator.Apply( + t.Context(), terms.ID, &Materialize{}, + ) + require.NoError(t, err) + require.Equal(t, PhaseMaterializing, record.Snapshot.Phase) + require.NotNil(t, record.Snapshot.CooperativeCloseRequest) + require.NotNil(t, record.Snapshot.CooperativeClose) + require.IsType(t, &PublishChannel{}, requireOneAction(t, actions)) +} + +// TestMaterializeRejectsAuthorizedCooperativeClose pins the other side of the +// resolution boundary: after both acknowledgements the close OOR may already +// be committed, so starting backing publication would risk two resolutions. +func TestMaterializeRejectsAuthorizedCooperativeClose(t *testing.T) { + t.Parallel() + + terms, source, request, clientKey, hubKey, operatorKey := + testCooperativeCloseFixture(t, KindPromotion, 5_000) + template, err := NewCooperativeCloseTemplate( + terms, source, request, 70_000, 30_000, 5, + ) + require.NoError(t, err) + settlement := completeTestCooperativeClose( + t, template, terms, source, request, clientKey, hubKey, + operatorKey, + ) + coordinator := activeCooperativeChannel(t, terms, source) + _, _, err = coordinator.Apply( + t.Context(), terms.ID, &RequestCooperativeClose{ + Request: request, + }, + ) + require.NoError(t, err) + for _, event := range []Event{ + &CooperativeCloseSigned{ + Close: settlement, + }, + &CooperativeCloseReady{ + Receipt: settlement.AuthorizationReceipt(), + }, + } { + _, _, err = coordinator.Apply(t.Context(), terms.ID, event) + require.NoError(t, err) + } + + _, _, err = coordinator.Apply( + t.Context(), terms.ID, &Materialize{}, + ) + require.ErrorContains(t, err, "cannot materialize channel from") + record, err := coordinator.Get(t.Context(), terms.ID) + require.NoError(t, err) + require.Equal(t, PhaseCoopCloseSigned, record.Snapshot.Phase) + require.NotNil(t, record.Snapshot.CooperativeClose) +} + +// TestCooperativeCloseLifecycle proves a finalized in-Ark OOR close is separate +// from backing materialization and becomes terminal after local lnd archival. +func TestCooperativeCloseLifecycle(t *testing.T) { + t.Parallel() + + terms, source, request, clientKey, hubKey, operatorKey := + testCooperativeCloseFixture(t, KindPromotion, 5_000) + coordinator := activeCooperativeChannel(t, terms, source) + backing := testBacking(t, terms, source) + + record, actions, err := coordinator.Apply( + t.Context(), terms.ID, &RequestCooperativeClose{ + Request: request, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseCoopClosing, record.Snapshot.Phase) + require.IsType( + t, &NegotiateCooperativeClose{}, requireOneAction(t, actions), + ) + + template, err := NewCooperativeCloseTemplate( + terms, source, request, 70_000, 30_000, 5, + ) + require.NoError(t, err) + settlement := completeTestCooperativeClose( + t, template, terms, source, request, clientKey, hubKey, + operatorKey, + ) + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &CooperativeCloseSigned{ + Close: settlement, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseCoopClosing, record.Snapshot.Phase) + require.Equal(t, &settlement, record.Snapshot.CooperativeClose) + require.Empty(t, actions) + _, _, err = coordinator.Apply( + t.Context(), terms.ID, &CooperativeCloseReady{ + Receipt: settlement.TxID, + }, + ) + require.ErrorContains(t, err, "does not match") + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &CooperativeCloseReady{ + Receipt: settlement.AuthorizationReceipt(), + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseCoopCloseSigned, record.Snapshot.Phase) + require.IsType( + t, &PublishCooperativeClose{}, requireOneAction(t, actions), + ) + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &ChannelActive{ + ChannelPointHash: backing.ChannelPoint.Hash, + ChannelPointIndex: backing.ChannelPoint.Index, + }, + ) + require.NoError(t, err) + require.IsType( + t, &PublishCooperativeClose{}, requireOneAction(t, actions), + ) + require.Equal(t, PhaseCoopCloseSigned, record.Snapshot.Phase) + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &CooperativeClosePublished{ + TxID: settlement.TxID, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseCoopClosePublished, record.Snapshot.Phase) + require.IsType( + t, &FinalizeCooperativeClose{}, requireOneAction(t, actions), + ) + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &CooperativeCloseFinalized{}, + ) + require.NoError(t, err) + require.Empty(t, actions) + require.Equal(t, PhaseClosed, record.Snapshot.Phase) + require.Equal( + t, backing.ChannelPoint, record.Snapshot.Backing.ChannelPoint, + ) + require.False(t, record.Snapshot.BackingPublished) + + conflictOutpoint := wire.OutPoint{ + Hash: chainhash.Hash{ + 7, + }, Index: 2, + } + conflictTxID := chainhash.Hash{8} + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &SourceSpent{ + OutPoint: conflictOutpoint, SpendingTxID: conflictTxID, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseClosed, record.Snapshot.Phase) + require.Equal( + t, conflictOutpoint, record.Snapshot.SourceConflict.OutPoint, + ) + require.Equal( + t, conflictTxID, record.Snapshot.SourceConflict.SpendingTxID, + ) + require.IsType( + t, &PublishCooperativeClose{}, requireOneAction(t, actions), + ) + _, resumed, err := coordinator.Resume(t.Context(), terms.ID) + require.NoError(t, err) + require.IsType( + t, &PublishCooperativeClose{}, requireOneAction(t, resumed), + ) +} + +// TestMaterializationSupersedesCooperativeNegotiation proves chain evidence +// can move an endpoint into lnd resolution before the cooperative-close OOR is +// finalized. This keeps a peer from blocking force close by going offline. +func TestMaterializationSupersedesCooperativeNegotiation(t *testing.T) { + t.Parallel() + + terms, source, request, clientKey, hubKey, operatorKey := + testCooperativeCloseFixture(t, KindPromotion, 5_000) + template, err := NewCooperativeCloseTemplate( + terms, source, request, 70_000, 30_000, 5, + ) + require.NoError(t, err) + settlement := completeTestCooperativeClose( + t, template, terms, source, request, clientKey, hubKey, + operatorKey, + ) + backing := testBacking(t, terms, source) + + tests := []struct { + name string + signed bool + }{ + { + name: "negotiating", + }, + { + name: "fully signed", + signed: true, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + coordinator := activeCooperativeChannel( + t, terms, source, + ) + _, _, err := coordinator.Apply( + t.Context(), terms.ID, + &RequestCooperativeClose{ + Request: request, + }, + ) + require.NoError(t, err) + if test.signed { + receipt := settlement.AuthorizationReceipt() + for _, event := range []Event{ + &CooperativeCloseSigned{ + Close: settlement, + }, + &CooperativeCloseReady{ + Receipt: receipt, + }, + } { + _, _, err = coordinator.Apply( + t.Context(), terms.ID, event, + ) + require.NoError(t, err) + } + } + + record, actions, err := coordinator.Apply( + t.Context(), terms.ID, &BackingObserved{ + TxID: backing.ChannelPoint.Hash, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseOnChain, record.Snapshot.Phase) + require.Nil(t, record.Snapshot.CooperativeCloseRequest) + require.Nil(t, record.Snapshot.CooperativeClose) + require.Empty(t, actions) + }) + } +} + +// TestCooperativeCloseAbortReturnsActive proves a failure before the signed +// transaction is durable does not strand a quiesced channel. +func TestCooperativeCloseAbortReturnsActive(t *testing.T) { + t.Parallel() + + terms, source, request, _, _, _ := testCooperativeCloseFixture( + t, KindPromotion, 5_000, + ) + coordinator := activeCooperativeChannel(t, terms, source) + _, _, err := coordinator.Apply( + t.Context(), terms.ID, &RequestCooperativeClose{ + Request: request, + }, + ) + require.NoError(t, err) + record, actions, err := coordinator.Apply( + t.Context(), terms.ID, &CooperativeCloseAborted{}, + ) + require.NoError(t, err) + require.Empty(t, actions) + require.Equal(t, PhaseActive, record.Snapshot.Phase) + require.Nil(t, record.Snapshot.CooperativeCloseRequest) + require.Nil(t, record.Snapshot.CooperativeClose) +} + +// TestOORChannelCanAbortBeforePONR proves a definitively failed prepared +// transfer releases its source before lnd funding is canceled. +func TestOORChannelCanAbortBeforePONR(t *testing.T) { + t.Parallel() + + coordinator, err := NewCoordinator(newMemoryStore()) + require.NoError(t, err) + terms := testTerms(t, KindPromotion) + _, err = coordinator.Request(t.Context(), terms) + require.NoError(t, err) + binding := testBinding(terms) + backing := testBacking(t, terms, binding) + + for _, event := range []Event{ + &BindVTXO{ + Binding: binding, + }, + &BackingSigned{ + Backing: backing, + }, + &FundingFinalized{ + Party: PartyClient, + }, + &FundingFinalized{ + Party: PartyHub, + }, + } { + _, _, err = coordinator.Apply(t.Context(), terms.ID, event) + require.NoError(t, err) + } + + record, actions, err := coordinator.Apply( + t.Context(), terms.ID, &OORAborted{ + SessionID: binding.OORSessionID, + Reason: "operator rejected transfer", + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseCancelling, record.Snapshot.Phase) + require.IsType(t, &CancelFunding{}, requireOneAction(t, actions)) + require.True(t, record.Snapshot.OORAborted) + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &OORAborted{ + SessionID: binding.OORSessionID, + Reason: "operator rejected transfer", + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseCancelling, record.Snapshot.Phase) + require.IsType(t, &CancelFunding{}, requireOneAction(t, actions)) + + record, _, err = coordinator.Apply( + t.Context(), terms.ID, &FundingCanceled{}, + ) + require.NoError(t, err) + require.Equal(t, PhaseFailed, record.Snapshot.Phase) +} + +// TestBackingReadyRejectsGenericFailure proves only the OOR actor's definitive +// terminal result can replace a commit action after the durable commit gate. +func TestBackingReadyRejectsGenericFailure(t *testing.T) { + t.Parallel() + + coordinator, err := NewCoordinator(newMemoryStore()) + require.NoError(t, err) + terms := testTerms(t, KindPromotion) + _, err = coordinator.Request(t.Context(), terms) + require.NoError(t, err) + binding := testBinding(terms) + backing := testBacking(t, terms, binding) + for _, event := range []Event{ + &BindVTXO{ + Binding: binding, + }, + &BackingSigned{ + Backing: backing, + }, + &FundingFinalized{ + Party: PartyClient, + }, + &FundingFinalized{ + Party: PartyHub, + }, + } { + _, _, err = coordinator.Apply(t.Context(), terms.ID, event) + require.NoError(t, err) + } + + _, _, err = coordinator.Apply( + t.Context(), terms.ID, &Fail{ + Reason: "incoming HTLC is expiring", + }, + ) + require.ErrorContains(t, err, "after safety boundary") + + record, actions, err := coordinator.Apply( + t.Context(), terms.ID, &ExpirePrePONR{ + Reason: "incoming HTLC is expiring", + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseBackingReady, record.Snapshot.Phase) + require.IsType(t, &CommitOOR{}, requireOneAction(t, actions)) + + _, resumed, err := coordinator.Resume(t.Context(), terms.ID) + require.NoError(t, err) + require.IsType(t, &CommitOOR{}, requireOneAction(t, resumed)) + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &OORAborted{ + SessionID: binding.OORSessionID, + Reason: "operator rejected transfer", + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseCancelling, record.Snapshot.Phase) + require.IsType(t, &CancelFunding{}, requireOneAction(t, actions)) +} + +// TestPrePONRExpiryLosesCommitGateCASRace proves a timer that read Negotiating +// cannot overwrite a concurrently persisted BackingReady commit action. +func TestPrePONRExpiryLosesCommitGateCASRace(t *testing.T) { + t.Parallel() + + store := newMemoryStore() + coordinator, err := NewCoordinator(store) + require.NoError(t, err) + terms := testTerms(t, KindPromotion) + _, err = coordinator.Request(t.Context(), terms) + require.NoError(t, err) + binding := testBinding(terms) + backing := testBacking(t, terms, binding) + for _, event := range []Event{ + &BindVTXO{ + Binding: binding, + }, + } { + _, _, err = coordinator.Apply(t.Context(), terms.ID, event) + require.NoError(t, err) + } + stale, err := coordinator.Get(t.Context(), terms.ID) + require.NoError(t, err) + require.Equal(t, PhaseNegotiating, stale.Snapshot.Phase) + for _, event := range []Event{ + &BackingSigned{ + Backing: backing, + }, + &FundingFinalized{ + Party: PartyClient, + }, + &FundingFinalized{ + Party: PartyHub, + }, + } { + _, _, err = coordinator.Apply(t.Context(), terms.ID, event) + require.NoError(t, err) + } + + staleStore := &staleReadStore{ + memoryStore: store, stale: stale, + } + staleCoordinator, err := NewCoordinator(staleStore) + require.NoError(t, err) + record, actions, err := staleCoordinator.Apply( + t.Context(), terms.ID, &ExpirePrePONR{ + Reason: "expired from stale scan", + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseBackingReady, record.Snapshot.Phase) + require.IsType(t, &CommitOOR{}, requireOneAction(t, actions)) + _, actions, err = staleCoordinator.Resume(t.Context(), terms.ID) + require.NoError(t, err) + require.IsType(t, &CommitOOR{}, requireOneAction(t, actions)) +} + +// TestPromotionWaitsForOORFinalization proves a client-funded promotion uses +// binding alone is insufficient to commit the prepared OOR. +func TestPromotionWaitsForOORFinalization(t *testing.T) { + t.Parallel() + + store := newMemoryStore() + coordinator, err := NewCoordinator(store) + require.NoError(t, err) + terms := testTerms(t, KindPromotion) + _, err = coordinator.Request(t.Context(), terms) + require.NoError(t, err) + + binding := testBinding(terms) + backing := testBacking(t, terms, binding) + for _, event := range []Event{ + &BindVTXO{ + Binding: binding, + }, + &BackingSigned{ + Backing: backing, + }, + &FundingFinalized{ + Party: PartyHub, + }, + } { + _, _, err = coordinator.Apply(t.Context(), terms.ID, event) + require.NoError(t, err) + } + + record, actions, err := coordinator.Apply( + t.Context(), terms.ID, &FundingFinalized{ + Party: PartyClient, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseBackingReady, record.Snapshot.Phase) + require.IsType(t, &CommitOOR{}, requireOneAction(t, actions)) + require.False(t, record.Snapshot.OORFinalized) + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &OORFinalized{ + SessionID: binding.OORSessionID, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseBackingReady, record.Snapshot.Phase) + require.IsType(t, &PrepareRecovery{}, requireOneAction(t, actions)) + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &RecoveryPackageInstalled{ + Party: PartyClient, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseBackingReady, record.Snapshot.Phase) + require.Empty(t, actions) + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &RecoveryPackageInstalled{ + Party: PartyHub, + }, + ) + require.NoError(t, err) + require.Equal(t, PhaseActivating, record.Snapshot.Phase) + require.IsType(t, &ActivateChannel{}, requireOneAction(t, actions)) +} + +// TestFundingFinalizationRequiresBacking ensures an edge-triggered lnd +// notification cannot become the only durable key for recovery. +func TestFundingFinalizationRequiresBacking(t *testing.T) { + t.Parallel() + + coordinator, err := NewCoordinator(newMemoryStore()) + require.NoError(t, err) + terms := testTerms(t, KindPromotion) + _, err = coordinator.Request(t.Context(), terms) + require.NoError(t, err) + _, _, err = coordinator.Apply( + t.Context(), terms.ID, &BindVTXO{ + Binding: testBinding(terms), + }, + ) + require.NoError(t, err) + + _, _, err = coordinator.Apply( + t.Context(), terms.ID, &FundingFinalized{ + Party: PartyHub, + }, + ) + require.ErrorContains(t, err, "before signed backing") +} + +// TestCoordinatorIdempotency verifies duplicate facts do not advance the +// store revision or invent work when the durable state has no pending action. +func TestCoordinatorIdempotency(t *testing.T) { + t.Parallel() + + store := newMemoryStore() + coordinator, err := NewCoordinator(store) + require.NoError(t, err) + terms := testTerms(t, KindPromotion) + requested, err := coordinator.Request(t.Context(), terms) + require.NoError(t, err) + + repeated, err := coordinator.Request(t.Context(), terms.Clone()) + require.NoError(t, err) + require.Equal(t, requested.Revision, repeated.Revision) + + binding := testBinding(terms) + bound, _, err := coordinator.Apply( + t.Context(), terms.ID, &BindVTXO{ + Binding: binding, + }, + ) + require.NoError(t, err) + + duplicate, actions, err := coordinator.Apply( + t.Context(), terms.ID, &BindVTXO{ + Binding: binding.Clone(), + }, + ) + require.NoError(t, err) + require.IsType(t, &NegotiateFunding{}, requireOneAction(t, actions)) + require.Equal(t, bound.Revision, duplicate.Revision) + + restarted, err := NewCoordinator(store) + require.NoError(t, err) + work, err := restarted.ResumeAll(t.Context()) + require.NoError(t, err) + require.Len(t, work, 1) + require.IsType(t, &NegotiateFunding{}, work[0].Action) + + changedTerms := terms.Clone() + changedTerms.Capacity++ + _, err = coordinator.Request(t.Context(), changedTerms) + require.ErrorContains(t, err, "different terms") +} + +// TestFindByPendingChannelID resolves the durable intent used by lnd's +// responder-side channel acceptor. +func TestFindByPendingChannelID(t *testing.T) { + t.Parallel() + + coordinator, err := NewCoordinator(newMemoryStore()) + require.NoError(t, err) + terms := testTerms(t, KindPromotion) + expected, err := coordinator.Request(t.Context(), terms) + require.NoError(t, err) + + record, err := coordinator.FindByPendingChannelID( + t.Context(), terms.PendingChannelID, + ) + require.NoError(t, err) + require.Equal(t, expected, record) + + _, err = coordinator.FindByPendingChannelID( + t.Context(), [32]byte{99}, + ) + require.ErrorIs(t, err, ErrNotFound) + + conflicting := testTerms(t, KindPromotion) + conflicting.ID[0] = 99 + conflicting.PendingChannelID = terms.PendingChannelID + _, err = coordinator.Request(t.Context(), conflicting) + require.ErrorContains(t, err, "belongs to another Ark channel") +} + +// TestPromotionRequiresClientFunding pins admission to the supported opener. +func TestPromotionRequiresClientFunding(t *testing.T) { + t.Parallel() + terms := testTerms(t, KindPromotion) + terms.Funder = PartyHub + require.ErrorContains(t, terms.Validate(), "client funded") + _, err := NewState(terms) + require.ErrorContains(t, err, "client funded") +} + +// TestChannelTermsRejectNonZeroFundingPosition keeps the advertised alias +// consistent with the single output in every channel backing transaction. +func TestChannelTermsRejectNonZeroFundingPosition(t *testing.T) { + t.Parallel() + + terms := testTerms(t, KindPromotion) + scid := lnwire.NewShortChanIDFromInt(terms.ReservedSCID) + scid.TxPosition = 1 + terms.ReservedSCID = scid.ToUint64() + + _, err := NewState(terms) + require.ErrorContains(t, err, "funding output position must be zero") +} + +// TestChannelTermsRejectUnsafeRefundDelay verifies a funder cannot reclaim the +// VTXO before the channel parties have the configured reaction window. +func TestChannelTermsRejectUnsafeRefundDelay(t *testing.T) { + t.Parallel() + + terms := testTerms(t, KindPromotion) + terms.VTXO.FunderDelay = terms.VTXO.ChannelDelay + 431 + + _, err := NewState(terms) + require.ErrorContains(t, err, "preserve the reaction window") +} + +// TestBindingRejectsDifferentChannelPolicy verifies an OOR preparation cannot +// bind an arbitrary output while retaining otherwise valid channel terms. +func TestBindingRejectsDifferentChannelPolicy(t *testing.T) { + t.Parallel() + + terms := testTerms(t, KindPromotion) + binding := testBinding(terms) + binding.PolicyTemplate[0] ^= 1 + + err := binding.Validate(terms) + require.ErrorContains(t, err, "policy does not match") +} + +// TestBackingMustBeSignedAndBound rejects a transaction that lnd could not +// safely activate against the exact VTXO. +func TestBackingMustBeSignedAndBound(t *testing.T) { + t.Parallel() + + terms := testTerms(t, KindPromotion) + binding := testBinding(terms) + backing := testBacking(t, terms, binding) + + tx := wire.NewMsgTx(2) + require.NoError(t, tx.Deserialize(bytes.NewReader(backing.Transaction))) + tx.TxIn[0].Witness = nil + backing.Transaction = serializeTx(t, tx) + backing.ChannelPoint.Hash = tx.TxHash() + + err := backing.Validate(terms, binding) + require.ErrorContains(t, err, "not fully signed") +} + +// TestCoordinatorDoesNotEmitBeforeCommit verifies failed persistence cannot +// leak the side effect produced by an in-memory transition. +func TestCoordinatorDoesNotEmitBeforeCommit(t *testing.T) { + t.Parallel() + + store := newMemoryStore() + coordinator, err := NewCoordinator(store) + require.NoError(t, err) + terms := testTerms(t, KindPromotion) + _, err = coordinator.Request(t.Context(), terms) + require.NoError(t, err) + + store.writeErr = errors.New("disk unavailable") + _, actions, err := coordinator.Apply( + t.Context(), terms.ID, &BindVTXO{ + Binding: testBinding(terms), + }, + ) + require.ErrorIs(t, err, store.writeErr) + require.Empty(t, actions) +} + +// TestCoordinatorObserverRunsAfterCommit proves ancillary accounting sees the +// exact revision that is already present in the canonical channel store. +func TestCoordinatorObserverRunsAfterCommit(t *testing.T) { + t.Parallel() + + store := newMemoryStore() + observer := &testRecordObserver{} + coordinator, err := NewCoordinator(store, observer) + require.NoError(t, err) + terms := testTerms(t, KindPromotion) + _, err = coordinator.Request(t.Context(), terms) + require.NoError(t, err) + updated, _, err := coordinator.Apply( + t.Context(), terms.ID, &BindVTXO{ + Binding: testBinding(terms), + }, + ) + require.NoError(t, err) + require.Len(t, observer.records, 2) + require.Equal(t, updated, observer.records[1]) + persisted, err := store.Get(t.Context(), terms.ID) + require.NoError(t, err) + require.Equal(t, persisted, observer.records[1]) +} + +// TestOORPreparationStartedIsIdempotent proves wallet selection is armed as a +// durable channel fact before the source outpoint exists. +func TestOORPreparationStartedIsIdempotent(t *testing.T) { + t.Parallel() + + coordinator, err := NewCoordinator(newMemoryStore()) + require.NoError(t, err) + terms := testTerms(t, KindPromotion) + _, err = coordinator.Request(t.Context(), terms) + require.NoError(t, err) + + record, actions, err := coordinator.Apply( + t.Context(), terms.ID, &OORPreparationStarted{}, + ) + require.NoError(t, err) + require.Empty(t, actions) + require.True(t, record.Snapshot.OORPreparationStarted) + revision := record.Revision + + record, actions, err = coordinator.Apply( + t.Context(), terms.ID, &OORPreparationStarted{}, + ) + require.NoError(t, err) + require.Empty(t, actions) + require.Equal(t, revision, record.Revision) +} + +// TestPartialFundingFactsDoNotRestartNegotiation verifies callback progress +// stays within one native lnd funding attempt. +func TestPartialFundingFactsDoNotRestartNegotiation(t *testing.T) { + t.Parallel() + + coordinator, err := NewCoordinator(newMemoryStore()) + require.NoError(t, err) + terms := testTerms(t, KindPromotion) + _, err = coordinator.Request(t.Context(), terms) + require.NoError(t, err) + binding := testBinding(terms) + _, actions, err := coordinator.Apply( + t.Context(), terms.ID, &BindVTXO{ + Binding: binding, + }, + ) + require.NoError(t, err) + require.IsType(t, &NegotiateFunding{}, requireOneAction(t, actions)) + + for _, event := range []Event{ + &BackingSigned{ + Backing: testBacking(t, terms, binding), + }, + &FundingFinalized{ + Party: PartyClient, + }, + } { + _, actions, err = coordinator.Apply( + t.Context(), terms.ID, event, + ) + require.NoError(t, err) + require.Empty(t, actions) + } +} + +// memoryStore is a revisioned in-memory implementation for coordinator tests. +type memoryStore struct { + mu sync.Mutex + records map[ID]Record + writeErr error +} + +// staleReadStore serves one stale record before delegating to the real store. +type staleReadStore struct { + *memoryStore + stale Record +} + +// Get returns one stale snapshot to force a compare-and-swap retry. +func (s *staleReadStore) Get(ctx context.Context, id ID) (Record, error) { + if s.stale.Snapshot.Terms.ID == id { + stale := s.stale + s.stale = Record{} + + return cloneRecord(stale), nil + } + + return s.memoryStore.Get(ctx, id) +} + +// newMemoryStore creates an empty test store. +func newMemoryStore() *memoryStore { + return &memoryStore{records: make(map[ID]Record)} +} + +// Create stores a new requested channel at revision one. +func (s *memoryStore) Create(_ context.Context, snapshot Snapshot) (Record, + error) { + + s.mu.Lock() + defer s.mu.Unlock() + + id := snapshot.Terms.ID + if _, ok := s.records[id]; ok { + return Record{}, ErrConflict + } + record := Record{Snapshot: snapshot.Clone(), Revision: 1} + s.records[id] = record + + return cloneRecord(record), nil +} + +// Get loads one channel record. +func (s *memoryStore) Get(_ context.Context, id ID) (Record, error) { + s.mu.Lock() + defer s.mu.Unlock() + + record, ok := s.records[id] + if !ok { + return Record{}, ErrNotFound + } + + return cloneRecord(record), nil +} + +// GetByPendingChannelID loads one record by its lnd funding correlation ID. +func (s *memoryStore) GetByPendingChannelID(_ context.Context, + pendingID [32]byte) (Record, error) { + + s.mu.Lock() + defer s.mu.Unlock() + + for _, record := range s.records { + if record.Snapshot.Terms.PendingChannelID == pendingID { + return cloneRecord(record), nil + } + } + + return Record{}, ErrNotFound +} + +// GetByChannelPoint loads one record by its signed lnd funding outpoint. +func (s *memoryStore) GetByChannelPoint(_ context.Context, + channelPoint wire.OutPoint) (Record, error) { + + s.mu.Lock() + defer s.mu.Unlock() + + for _, record := range s.records { + backing := record.Snapshot.Backing + if backing != nil && backing.ChannelPoint == channelPoint { + return cloneRecord(record), nil + } + } + + return Record{}, ErrNotFound +} + +// ListNonTerminal loads resumable records in stable ID order. +func (s *memoryStore) ListNonTerminal(_ context.Context) ([]Record, error) { + s.mu.Lock() + defer s.mu.Unlock() + + records := make([]Record, 0, len(s.records)) + for _, record := range s.records { + if record.Snapshot.Phase.IsTerminal() { + continue + } + + records = append(records, cloneRecord(record)) + } + sort.Slice(records, func(i, j int) bool { + return bytes.Compare( + records[i].Snapshot.Terms.ID[:], + records[j].Snapshot.Terms.ID[:], + ) < 0 + }) + + return records, nil +} + +// CompareAndSwap advances a channel only from the expected revision. +func (s *memoryStore) CompareAndSwap(_ context.Context, id ID, revision uint64, + snapshot Snapshot) (Record, error) { + + s.mu.Lock() + defer s.mu.Unlock() + + if s.writeErr != nil { + return Record{}, s.writeErr + } + record, ok := s.records[id] + if !ok { + return Record{}, ErrNotFound + } + if record.Revision != revision { + return Record{}, ErrConflict + } + + record = Record{ + Snapshot: snapshot.Clone(), + Revision: revision + 1, + } + s.records[id] = record + + return cloneRecord(record), nil +} + +// cloneRecord returns a record with isolated snapshot byte slices. +func cloneRecord(record Record) Record { + record.Snapshot = record.Snapshot.Clone() + + return record +} + +// activeCooperativeChannel drives one channel through OOR finalization and +// virtual lnd activation. +func activeCooperativeChannel(t *testing.T, terms Terms, + source VTXOBinding) *Coordinator { + + t.Helper() + coordinator, err := NewCoordinator(newMemoryStore()) + require.NoError(t, err) + _, err = coordinator.Request(t.Context(), terms) + require.NoError(t, err) + backing := testBacking(t, terms, source) + for _, event := range []Event{ + &BindVTXO{ + Binding: source, + }, + &BackingSigned{ + Backing: backing, + }, + &FundingFinalized{ + Party: PartyClient, + }, + &FundingFinalized{ + Party: PartyHub, + }, + &OORFinalized{ + SessionID: source.OORSessionID, + }, + &RecoveryPackageInstalled{ + Party: PartyClient, + }, + &RecoveryPackageInstalled{ + Party: PartyHub, + }, + &ChannelActive{ + ChannelPointHash: backing.ChannelPoint.Hash, + ChannelPointIndex: backing.ChannelPoint.Index, + }, + } { + _, _, err = coordinator.Apply(t.Context(), terms.ID, event) + require.NoError(t, err) + } + + return coordinator +} + +// testTerms creates valid immutable terms for one channel kind. +func testTerms(t *testing.T, kind Kind) Terms { + t.Helper() + + clientKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + hubKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + newPolicyKey := func(role byte) [33]byte { + key := testPolicyPrivateKey(kind, role) + var serialized [33]byte + copy(serialized[:], key.PubKey().SerializeCompressed()) + + return serialized + } + + var clientNodeKey, hubNodeKey [33]byte + copy(clientNodeKey[:], clientKey.PubKey().SerializeCompressed()) + copy(hubNodeKey[:], hubKey.PubKey().SerializeCompressed()) + + terms := Terms{ + ID: ID{ + 1, + 2, + byte(kind), + }, + Kind: kind, + Funder: PartyClient, + PendingChannelID: [32]byte{ + 4, + 5, + byte(kind), + }, + Capacity: btcutil.Amount(100_000), + ReservedSCID: lnwire.ShortChannelID{ + BlockHeight: 16_000_000 + uint32(kind), + TxIndex: uint32(kind), + }.ToUint64(), + ClientNodeKey: clientNodeKey, + HubNodeKey: hubNodeKey, + VTXO: VTXOTerms{ + ClientArkKey: newPolicyKey(1), + HubArkKey: newPolicyKey(2), + ArkOperatorKey: newPolicyKey(3), + ClientChannelKey: newPolicyKey(4), + HubChannelKey: newPolicyKey(5), + FunderKey: newPolicyKey(6), + ChannelDelay: 144, + FunderDelay: 576, + MinExitDelay: 144, + }, + } + + return terms +} + +// testPolicyPrivateKey returns stable channel-policy keys so generic lifecycle +// fixtures can construct real signed backing transactions. +func testPolicyPrivateKey(kind Kind, role byte) *btcec.PrivateKey { + seed := bytes.Repeat([]byte{role}, 32) + seed[0] ^= byte(kind) + key, _ := btcec.PrivKeyFromBytes(seed) + + return key +} + +// testBinding creates one exact prepared OOR output for channel terms. +func testBinding(terms Terms) VTXOBinding { + policy, pkScript, err := terms.VTXO.Artifacts() + if err != nil { + panic(err) + } + amount := terms.Capacity + 1_000 + tx := wire.NewMsgTx(2) + tx.AddTxIn(&wire.TxIn{ + PreviousOutPoint: wire.OutPoint{ + Hash: chainhash.Hash{10, byte(terms.Kind)}, + }, + }) + tx.AddTxOut(&wire.TxOut{Value: 1, PkScript: []byte{0x51}}) + tx.AddTxOut(&wire.TxOut{Value: 2, PkScript: []byte{0x51}}) + tx.AddTxOut(&wire.TxOut{Value: int64(amount), PkScript: pkScript}) + var arkTransaction bytes.Buffer + if err := tx.Serialize(&arkTransaction); err != nil { + panic(err) + } + sessionID := [32]byte(tx.TxHash()) + + return VTXOBinding{ + OORSessionID: sessionID, + OutPoint: wire.OutPoint{ + Hash: chainhash.Hash(sessionID), + Index: 2, + }, + Amount: amount, + ArkTransaction: arkTransaction.Bytes(), + PolicyTemplate: policy, + PkScript: pkScript, + } +} + +// testBacking creates a signed single-input funding transaction. +func testBacking(t *testing.T, terms Terms, binding VTXOBinding) Backing { + t.Helper() + + packet, err := psbt.New(nil, []*wire.TxOut{{ + Value: int64(terms.Capacity), + PkScript: []byte{0x51, 0x20, 1}, + }}, 2, 0, nil) + require.NoError(t, err) + template, err := NewBackingTemplate(packet, terms, binding) + require.NoError(t, err) + clientSig := signBacking( + t, template, terms, PartyClient, + testPolicyPrivateKey(terms.Kind, 4), + ) + hubSig := signBacking( + t, template, terms, PartyHub, + testPolicyPrivateKey(terms.Kind, 5), + ) + backing, err := template.Complete(terms, binding, clientSig, hubSig) + require.NoError(t, err) + + return backing +} + +// serializeTx serializes one witness transaction for a test fixture. +func serializeTx(t *testing.T, tx *wire.MsgTx) []byte { + t.Helper() + + var buf bytes.Buffer + require.NoError(t, tx.Serialize(&buf)) + + return buf.Bytes() +} + +// requireOneAction asserts and returns one emitted coordinator action. +func requireOneAction(t *testing.T, actions []Action) Action { + t.Helper() + require.Len(t, actions, 1) + + return actions[0] +} From 4db4ad8218a317a400d7c12550c83b6f14b36a53 Mon Sep 17 00:00:00 2001 From: sputn1ck Date: Wed, 18 Nov 2026 18:48:49 +0100 Subject: [PATCH 5/7] arkchannel: Track payment circuits through durable settlement Bind each payment attempt to its circuit and persist the preimage before allowing a retry or fallback. --- arkchannel/payment_bridge.go | 696 ++++++++++++++++++++++++++++++ arkchannel/payment_bridge_test.go | 203 +++++++++ 2 files changed, 899 insertions(+) create mode 100644 arkchannel/payment_bridge.go create mode 100644 arkchannel/payment_bridge_test.go diff --git a/arkchannel/payment_bridge.go b/arkchannel/payment_bridge.go new file mode 100644 index 000000000..26fac43ae --- /dev/null +++ b/arkchannel/payment_bridge.go @@ -0,0 +1,696 @@ +package arkchannel + +import ( + "context" + "fmt" + + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/lightninglabs/wavelength/baselib/protofsm" + "github.com/lightningnetwork/lnd/lntypes" +) + +// PaymentDirection identifies which side of the private channel holds value +// before the bridge dispatches the same payment hash on its other leg. +type PaymentDirection uint8 + +const ( + // PaymentOutgoing moves a held private-channel HTLC to public + // Lightning. + PaymentOutgoing PaymentDirection = iota + 1 + + // PaymentIncoming moves a held public Lightning HTLC to the private + // channel. + PaymentIncoming +) + +// String returns the durable payment direction name. +func (d PaymentDirection) String() string { + switch d { + case PaymentOutgoing: + return "outgoing" + + case PaymentIncoming: + return "incoming" + + default: + return "unknown" + } +} + +// PaymentPhase is the small cross-system lifecycle around lnd's authoritative +// invoice and payment state machines. +type PaymentPhase uint8 + +const ( + // PaymentRegistered means immutable bridge terms are durable. + PaymentRegistered PaymentPhase = iota + 1 + + // PaymentSourceReady means the outgoing private hold invoice exists. + PaymentSourceReady + + // PaymentSourceLocked means the source HTLC is irrevocably identified + // and held while the destination is dispatched. + PaymentSourceLocked + + // PaymentDestinationInFlight means the destination is durably selected + // and lnd dispatch is pending or owns an attempt for the same hash. + PaymentDestinationInFlight + + // PaymentPreimageKnown means the destination settled and the exact + // preimage is durable before the source is released. + PaymentPreimageKnown + + // PaymentCompleted means the source was released with that preimage. + PaymentCompleted + + // PaymentSourceFailing means the destination failed before revealing a + // preimage and the held source must be failed. + PaymentSourceFailing + + // PaymentFailed means both legs ended without moving value. + PaymentFailed + + retiredPaymentFallback // Never reuse this durable phase. + + // PaymentNeedsIntervention means a known preimage could not be applied + // automatically and value safety requires operator attention. + PaymentNeedsIntervention +) + +// String returns the durable payment phase name. +func (p PaymentPhase) String() string { + switch p { + case PaymentRegistered: + return "registered" + + case PaymentSourceReady: + return "source_ready" + + case PaymentSourceLocked: + return "source_locked" + + case PaymentDestinationInFlight: + return "destination_in_flight" + + case PaymentPreimageKnown: + return "preimage_known" + + case PaymentCompleted: + return "completed" + + case PaymentSourceFailing: + return "source_failing" + + case PaymentFailed: + return "failed" + + case PaymentNeedsIntervention: + return "needs_intervention" + + default: + return "unknown" + } +} + +// IsTerminal reports whether the direct bridge has no pending side effect. +func (p PaymentPhase) IsTerminal() bool { + return p == PaymentCompleted || p == PaymentFailed || + p == PaymentNeedsIntervention +} + +// PaymentCircuit identifies the public HTLC held by the operator interceptor. +type PaymentCircuit struct { + IncomingChannelID uint64 + IncomingHTLCID uint64 + OutgoingSCID uint64 + IncomingExpiry uint32 +} + +// PaymentBridgeSnapshot is the durable boundary between the private lnd +// runtime and the operator's public Lightning node. +type PaymentBridgeSnapshot struct { + Direction PaymentDirection + Phase PaymentPhase + PaymentHash lntypes.Hash + ClientNodeKey [33]byte + ChannelID ID + ReservedSCID uint64 + DestinationSCID uint64 + SourceAmount btcutil.Amount + DestinationAmount btcutil.Amount + // PrivateCLTVDeltaBlocks freezes the block-denominated channel policy + // advertised in an incoming invoice. Missing persisted policy fails + // validation instead of being re-derived from mutable runtime config. + PrivateCLTVDeltaBlocks uint32 + ServerFee btcutil.Amount + RoutingFeeBudget btcutil.Amount + PublicInvoice string + Circuit *PaymentCircuit + Preimage *lntypes.Preimage + Failure string +} + +// Clone returns a snapshot without pointer aliases. +func (s PaymentBridgeSnapshot) Clone() PaymentBridgeSnapshot { + if s.Circuit != nil { + circuit := *s.Circuit + s.Circuit = &circuit + } + if s.Preimage != nil { + preimage := *s.Preimage + s.Preimage = &preimage + } + + return s +} + +// Validate checks the same-hash and value-conservation bridge invariants. +func (s PaymentBridgeSnapshot) Validate() error { + if s.PaymentHash == (lntypes.Hash{}) { + return fmt.Errorf("payment hash is required") + } + if err := validateNodeKey("client", s.ClientNodeKey); err != nil { + return err + } + if s.SourceAmount <= 0 || s.DestinationAmount <= 0 { + return fmt.Errorf("bridge amounts must be positive") + } + if s.SourceAmount < s.DestinationAmount { + return fmt.Errorf("source amount cannot be below destination " + + "amount") + } + if s.Phase < PaymentRegistered || s.Phase > PaymentNeedsIntervention || + s.Phase == retiredPaymentFallback { + return fmt.Errorf("unknown payment phase %d", s.Phase) + } + + switch s.Direction { + case PaymentOutgoing: + if s.PrivateCLTVDeltaBlocks != 0 { + return fmt.Errorf("outgoing bridge cannot reserve a " + + "private CLTV delta") + } + if s.PublicInvoice == "" { + return fmt.Errorf("outgoing bridge requires public " + + "invoice") + } + if s.ChannelID == (ID{}) || s.ReservedSCID == 0 { + return fmt.Errorf("outgoing bridge requires active " + + "channel") + } + if s.Circuit != nil { + return fmt.Errorf("outgoing bridge cannot bind " + + "public circuit") + } + if s.ServerFee < 0 || s.RoutingFeeBudget < 0 || + s.ServerFee > btcutil.MaxSatoshi-s.RoutingFeeBudget || + s.DestinationAmount > btcutil.MaxSatoshi- + s.ServerFee-s.RoutingFeeBudget || + s.SourceAmount != s.DestinationAmount+s.ServerFee+ + s.RoutingFeeBudget { + return fmt.Errorf("outgoing bridge fee accounting is " + + "invalid") + } + + case PaymentIncoming: + if s.PublicInvoice != "" { + return fmt.Errorf("incoming bridge cannot store " + + "public invoice") + } + if s.ReservedSCID == 0 { + return fmt.Errorf("incoming bridge requires reserved " + + "SCID") + } + if s.PrivateCLTVDeltaBlocks == 0 { + return fmt.Errorf("incoming bridge requires a " + + "private CLTV delta") + } + if s.ServerFee != 0 || s.RoutingFeeBudget != 0 || + s.SourceAmount != s.DestinationAmount { + return fmt.Errorf("incoming bridge amounts must match") + } + if s.ChannelID == (ID{}) { + return fmt.Errorf("incoming bridge requires an " + + "active channel") + } + + default: + return fmt.Errorf("unknown payment direction %d", s.Direction) + } + + if s.Circuit != nil && s.Direction != PaymentIncoming { + return fmt.Errorf("only incoming bridge can bind public " + + "circuit") + } + if s.Preimage != nil && s.Preimage.Hash() != s.PaymentHash { + return fmt.Errorf("bridge preimage does not match payment hash") + } + if (s.Phase == PaymentPreimageKnown || + s.Phase == PaymentCompleted || + s.Phase == PaymentNeedsIntervention) && s.Preimage == nil { + return fmt.Errorf("phase %s requires preimage", s.Phase) + } + if (s.Phase == PaymentSourceFailing || s.Phase == PaymentFailed || + s.Phase == PaymentNeedsIntervention) && s.Failure == "" { + return fmt.Errorf("phase %s requires reason", s.Phase) + } + if s.Preimage != nil && (s.Phase == PaymentSourceFailing || + s.Phase == PaymentFailed) { + return fmt.Errorf("known preimage cannot enter failure path") + } + + return nil +} + +// PaymentBridgeEvent is a closed set of durable bridge facts. +type PaymentBridgeEvent interface { + paymentBridgeEventSealed() +} + +// PaymentSourcePrepared records creation of the outgoing hold invoice. +type PaymentSourcePrepared struct{} + +func (*PaymentSourcePrepared) paymentBridgeEventSealed() {} + +// PaymentSourceUnavailable records that the client could not lock the +// outgoing private HTLC after the operator installed its hold invoice. +type PaymentSourceUnavailable struct { + Reason string +} + +func (*PaymentSourceUnavailable) paymentBridgeEventSealed() {} + +// PaymentSourceHTLCLocked records the exact held source HTLC. +type PaymentSourceHTLCLocked struct { + Circuit *PaymentCircuit +} + +func (*PaymentSourceHTLCLocked) paymentBridgeEventSealed() {} + +// PaymentDestinationStarted records that lnd owns the destination attempt. +type PaymentDestinationStarted struct { + ChannelID ID + DestinationSCID uint64 +} + +func (*PaymentDestinationStarted) paymentBridgeEventSealed() {} + +// PaymentDestinationSettled records the destination's revealed preimage. +type PaymentDestinationSettled struct { + Preimage lntypes.Preimage +} + +func (*PaymentDestinationSettled) paymentBridgeEventSealed() {} + +// PaymentSourceSettled records release of the source with the preimage. +type PaymentSourceSettled struct{} + +func (*PaymentSourceSettled) paymentBridgeEventSealed() {} + +// PaymentDestinationFailed records definitive destination failure. +type PaymentDestinationFailed struct { + Reason string +} + +func (*PaymentDestinationFailed) paymentBridgeEventSealed() {} + +// PaymentSourceFailed records definitive cancellation of the held source. +type PaymentSourceFailed struct{} + +func (*PaymentSourceFailed) paymentBridgeEventSealed() {} + +// PaymentInterventionRequired records a failure after a preimage was known. +type PaymentInterventionRequired struct { + Reason string +} + +func (*PaymentInterventionRequired) paymentBridgeEventSealed() {} + +// PaymentBridgeEnvironment names one pure bridge machine. +type PaymentBridgeEnvironment struct { + PaymentHash lntypes.Hash +} + +// Name returns the stable state machine name. +func (e *PaymentBridgeEnvironment) Name() string { + return fmt.Sprintf("ark_channel_payment_%x", e.PaymentHash[:4]) +} + +// PaymentBridgeState is one protofsm state around native lnd lifecycles. +type PaymentBridgeState interface { + protofsm.State[ + PaymentBridgeEvent, struct{}, + *PaymentBridgeEnvironment, + ] + + Snapshot() PaymentBridgeSnapshot +} + +type paymentBridgeState struct { + snapshot PaymentBridgeSnapshot +} + +// NewPaymentBridgeState validates and creates one registered bridge state. +func NewPaymentBridgeState(snapshot PaymentBridgeSnapshot) (PaymentBridgeState, + error) { + + if snapshot.DestinationSCID != 0 || snapshot.Circuit != nil || + snapshot.Preimage != nil || snapshot.Failure != "" { + return nil, fmt.Errorf("new payment bridge contains " + + "lifecycle state") + } + snapshot.Phase = PaymentRegistered + if err := snapshot.Validate(); err != nil { + return nil, err + } + + return &paymentBridgeState{snapshot: snapshot.Clone()}, nil +} + +// SamePaymentBridgeTerms reports whether two snapshots describe the same +// reservation while ignoring lifecycle state advanced by bridge workers. +func SamePaymentBridgeTerms(a, b PaymentBridgeSnapshot) bool { + return a.Direction == b.Direction && a.PaymentHash == b.PaymentHash && + a.ClientNodeKey == b.ClientNodeKey && + a.ChannelID == b.ChannelID && + a.ReservedSCID == b.ReservedSCID && + a.SourceAmount == b.SourceAmount && + a.DestinationAmount == b.DestinationAmount && + a.PrivateCLTVDeltaBlocks == b.PrivateCLTVDeltaBlocks && + a.ServerFee == b.ServerFee && + a.RoutingFeeBudget == b.RoutingFeeBudget && + a.PublicInvoice == b.PublicInvoice +} + +// RestorePaymentBridgeState validates one durable bridge snapshot. +func RestorePaymentBridgeState(snapshot PaymentBridgeSnapshot) ( + PaymentBridgeState, error) { + + if err := snapshot.Validate(); err != nil { + return nil, err + } + + return &paymentBridgeState{snapshot: snapshot.Clone()}, nil +} + +// Snapshot returns an isolated durable snapshot. +func (s *paymentBridgeState) Snapshot() PaymentBridgeSnapshot { + return s.snapshot.Clone() +} + +// String returns the durable bridge phase. +func (s *paymentBridgeState) String() string { + return s.snapshot.Phase.String() +} + +// IsTerminal reports whether the direct bridge owns more work. +func (s *paymentBridgeState) IsTerminal() bool { + return s.snapshot.Phase.IsTerminal() +} + +// ProcessEvent applies one bridge fact without executing I/O. +func (s *paymentBridgeState) ProcessEvent(_ context.Context, + event PaymentBridgeEvent, _ *PaymentBridgeEnvironment) ( + *protofsm.StateTransition[ + PaymentBridgeEvent, struct{}, + *PaymentBridgeEnvironment, + ], error) { + + if event == nil { + return nil, fmt.Errorf("payment bridge event is required") + } + + next := s.snapshot.Clone() + if err := applyPaymentBridgeEvent(&next, event); err != nil { + return nil, err + } + if err := next.Validate(); err != nil { + return nil, err + } + + return &protofsm.StateTransition[ + PaymentBridgeEvent, struct{}, + *PaymentBridgeEnvironment, + ]{ + NextState: &paymentBridgeState{ + snapshot: next, + }, + }, nil +} + +// applyPaymentBridgeEvent dispatches one immutable bridge fact to its narrow +// transition handler. +func applyPaymentBridgeEvent(next *PaymentBridgeSnapshot, + event PaymentBridgeEvent) error { + + switch event := event.(type) { + case *PaymentSourcePrepared: + return applyPaymentSourcePrepared(next) + + case *PaymentSourceUnavailable: + return applyPaymentSourceUnavailable(next, event) + + case *PaymentSourceHTLCLocked: + return applyPaymentSourceLocked(next, event) + + case *PaymentDestinationStarted: + return applyPaymentDestinationStarted(next, event) + + case *PaymentDestinationSettled: + return applyPaymentDestinationSettled(next, event) + + case *PaymentSourceSettled: + return applyPaymentSourceSettled(next) + + case *PaymentDestinationFailed: + return applyPaymentDestinationFailed(next, event) + + case *PaymentSourceFailed: + return applyPaymentSourceFailed(next) + + case *PaymentInterventionRequired: + return applyPaymentInterventionRequired(next, event) + + default: + return fmt.Errorf("unknown payment bridge event %T", event) + } +} + +// applyPaymentSourcePrepared records that the outgoing hold invoice exists. +func applyPaymentSourcePrepared(next *PaymentBridgeSnapshot) error { + if next.Direction != PaymentOutgoing { + return fmt.Errorf("incoming source needs no invoice") + } + if next.Phase == PaymentSourceReady { + return nil + } + if next.Phase != PaymentRegistered { + return fmt.Errorf("cannot prepare source from %s", next.Phase) + } + next.Phase = PaymentSourceReady + + return nil +} + +// applyPaymentSourceUnavailable starts failure of an unavailable outgoing +// source before any destination payment exists. +func applyPaymentSourceUnavailable(next *PaymentBridgeSnapshot, + event *PaymentSourceUnavailable) error { + + if next.Direction != PaymentOutgoing { + return fmt.Errorf("incoming source cannot be unavailable") + } + if next.Phase == PaymentSourceFailing || next.Phase == PaymentFailed { + if next.Failure == event.Reason { + return nil + } + + return fmt.Errorf("payment source already failed differently") + } + if next.Phase != PaymentSourceReady { + return fmt.Errorf("cannot fail source from %s", next.Phase) + } + if event.Reason == "" { + return fmt.Errorf("source failure reason required") + } + next.Failure = event.Reason + next.Phase = PaymentSourceFailing + + return nil +} + +// applyPaymentSourceLocked binds the exact held source HTLC to the bridge. +func applyPaymentSourceLocked(next *PaymentBridgeSnapshot, + event *PaymentSourceHTLCLocked) error { + + if next.Phase == PaymentSourceLocked || + next.Phase == PaymentDestinationInFlight { + + if paymentCircuitsEqual(next.Circuit, event.Circuit) { + return nil + } + + return fmt.Errorf("payment source already bound") + } + if next.Direction == PaymentOutgoing { + if next.Phase != PaymentSourceReady || event.Circuit != nil { + return fmt.Errorf("invalid outgoing source lock") + } + } else if next.Phase != PaymentRegistered || event.Circuit == nil { + return fmt.Errorf("invalid incoming source lock") + } + if event.Circuit != nil { + circuit := *event.Circuit + next.Circuit = &circuit + } + next.Phase = PaymentSourceLocked + + return nil +} + +// applyPaymentDestinationStarted binds the selected active channel and alias. +func applyPaymentDestinationStarted(next *PaymentBridgeSnapshot, + event *PaymentDestinationStarted) error { + + if next.Phase == PaymentDestinationInFlight { + if next.ChannelID == event.ChannelID && + next.DestinationSCID == event.DestinationSCID { + return nil + } + + return fmt.Errorf("payment destination already bound") + } + if next.Phase != PaymentSourceLocked { + return fmt.Errorf("cannot start destination from %s", + next.Phase) + } + if event.ChannelID == (ID{}) || event.DestinationSCID == 0 { + return fmt.Errorf("active destination channel required") + } + if next.ChannelID != event.ChannelID || + (next.Direction == PaymentOutgoing && + next.ReservedSCID != event.DestinationSCID) { + return fmt.Errorf("payment destination changed channel") + } + next.DestinationSCID = event.DestinationSCID + next.Phase = PaymentDestinationInFlight + + return nil +} + +// applyPaymentDestinationSettled persists the preimage before source release. +func applyPaymentDestinationSettled(next *PaymentBridgeSnapshot, + event *PaymentDestinationSettled) error { + + if event.Preimage.Hash() != next.PaymentHash { + return fmt.Errorf("destination preimage mismatch") + } + if next.Phase == PaymentPreimageKnown || + next.Phase == PaymentCompleted { + + if next.Preimage != nil && *next.Preimage == event.Preimage { + return nil + } + + return fmt.Errorf("payment already has another preimage") + } + if next.Phase != PaymentDestinationInFlight { + return fmt.Errorf("cannot settle destination from %s", + next.Phase) + } + preimage := event.Preimage + next.Preimage = &preimage + next.Phase = PaymentPreimageKnown + + return nil +} + +// applyPaymentSourceSettled records completion after applying the preimage. +func applyPaymentSourceSettled(next *PaymentBridgeSnapshot) error { + if next.Phase == PaymentCompleted { + return nil + } + if next.Phase != PaymentPreimageKnown { + return fmt.Errorf("cannot settle source from %s", next.Phase) + } + next.Phase = PaymentCompleted + + return nil +} + +// applyPaymentDestinationFailed starts source failure while no preimage exists. +func applyPaymentDestinationFailed(next *PaymentBridgeSnapshot, + event *PaymentDestinationFailed) error { + + if next.Preimage != nil { + return fmt.Errorf("cannot fail after preimage is known") + } + if next.Phase == PaymentSourceFailing || next.Phase == PaymentFailed { + if next.Failure == event.Reason { + return nil + } + + return fmt.Errorf("payment already failed differently") + } + if next.Phase != PaymentSourceLocked && + next.Phase != PaymentDestinationInFlight && + !(next.Direction == PaymentIncoming && + next.Phase == PaymentRegistered) { + return fmt.Errorf("cannot fail destination from %s", next.Phase) + } + if event.Reason == "" { + return fmt.Errorf("destination failure reason required") + } + next.Failure = event.Reason + next.Phase = PaymentSourceFailing + + return nil +} + +// applyPaymentSourceFailed records that both payment legs failed safely. +func applyPaymentSourceFailed(next *PaymentBridgeSnapshot) error { + if next.Phase == PaymentFailed { + return nil + } + if next.Phase != PaymentSourceFailing { + return fmt.Errorf("cannot fail source from %s", next.Phase) + } + next.Phase = PaymentFailed + + return nil +} + +// applyPaymentInterventionRequired preserves a known preimage for recovery. +func applyPaymentInterventionRequired(next *PaymentBridgeSnapshot, + event *PaymentInterventionRequired) error { + + if next.Preimage == nil { + return fmt.Errorf("intervention requires known preimage") + } + if event.Reason == "" { + return fmt.Errorf("intervention reason required") + } + if next.Phase == PaymentNeedsIntervention { + if next.Failure == event.Reason { + return nil + } + + return fmt.Errorf("intervention reason changed") + } + if next.Phase != PaymentPreimageKnown { + return fmt.Errorf("cannot require intervention from %s", + next.Phase) + } + next.Failure = event.Reason + next.Phase = PaymentNeedsIntervention + + return nil +} + +func paymentCircuitsEqual(a, b *PaymentCircuit) bool { + if a == nil || b == nil { + return a == b + } + + return *a == *b +} diff --git a/arkchannel/payment_bridge_test.go b/arkchannel/payment_bridge_test.go new file mode 100644 index 000000000..1138d2214 --- /dev/null +++ b/arkchannel/payment_bridge_test.go @@ -0,0 +1,203 @@ +package arkchannel + +import ( + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/lightningnetwork/lnd/lntypes" + "github.com/stretchr/testify/require" +) + +// TestPaymentBridgeOutgoing proves the public preimage is durable before the +// private source can settle. +func TestPaymentBridgeOutgoing(t *testing.T) { + snapshot, preimage := testPaymentBridgeSnapshot(t, PaymentOutgoing) + state, err := NewPaymentBridgeState(snapshot) + require.NoError(t, err) + + state = applyPaymentEvent(t, state, &PaymentSourcePrepared{}) + require.Equal(t, PaymentSourceReady, state.Snapshot().Phase) + state = applyPaymentEvent(t, state, &PaymentSourceHTLCLocked{}) + require.Equal(t, PaymentSourceLocked, state.Snapshot().Phase) + state = applyPaymentEvent(t, state, &PaymentDestinationStarted{ + ChannelID: snapshot.ChannelID, + DestinationSCID: snapshot.ReservedSCID, + }) + require.Equal(t, PaymentDestinationInFlight, state.Snapshot().Phase) + state = applyPaymentEvent(t, state, &PaymentDestinationSettled{ + Preimage: preimage, + }) + require.Equal(t, PaymentPreimageKnown, state.Snapshot().Phase) + require.Equal(t, preimage, *state.Snapshot().Preimage) + state = applyPaymentEvent(t, state, &PaymentSourceSettled{}) + require.True(t, state.IsTerminal()) + require.Equal(t, PaymentCompleted, state.Snapshot().Phase) +} + +// TestPaymentBridgeRequiresActiveChannel verifies an incoming registration +// cannot defer channel selection until the public HTLC arrives. +func TestPaymentBridgeRequiresActiveChannel(t *testing.T) { + snapshot, _ := testPaymentBridgeSnapshot(t, PaymentIncoming) + snapshot.ChannelID = ID{} + _, err := NewPaymentBridgeState(snapshot) + require.ErrorContains(t, err, "requires an active channel") +} + +// TestPaymentBridgeCancelsRegisteredReceive verifies an unpaid channel +// reservation can terminate without a public circuit or destination dispatch. +func TestPaymentBridgeCancelsRegisteredReceive(t *testing.T) { + snapshot, _ := testPaymentBridgeSnapshot(t, PaymentIncoming) + state, err := NewPaymentBridgeState(snapshot) + require.NoError(t, err) + + state = applyPaymentEvent(t, state, &PaymentDestinationFailed{ + Reason: "invoice expired", + }) + state = applyPaymentEvent(t, state, &PaymentSourceFailed{}) + require.Equal(t, PaymentFailed, state.Snapshot().Phase) + require.True(t, state.IsTerminal()) +} + +// TestPaymentBridgeRejectsFailureAfterPreimage proves a bridge never converts +// a known preimage into a failure path that could lose the source payment. +func TestPaymentBridgeRejectsFailureAfterPreimage(t *testing.T) { + snapshot, preimage := testPaymentBridgeSnapshot(t, PaymentIncoming) + state, err := NewPaymentBridgeState(snapshot) + require.NoError(t, err) + + state = applyPaymentEvent(t, state, &PaymentSourceHTLCLocked{ + Circuit: &PaymentCircuit{ + IncomingChannelID: 1, IncomingHTLCID: 2, + OutgoingSCID: snapshot.ReservedSCID, + }, + }) + state = applyPaymentEvent(t, state, &PaymentDestinationStarted{ + ChannelID: ID{2}, + DestinationSCID: snapshot.ReservedSCID + 1, + }) + require.Equal(t, snapshot.ReservedSCID, state.Snapshot().ReservedSCID) + require.Equal( + t, snapshot.ReservedSCID+1, state.Snapshot().DestinationSCID, + ) + state = applyPaymentEvent(t, state, &PaymentDestinationSettled{ + Preimage: preimage, + }) + + _, err = state.ProcessEvent( + t.Context(), &PaymentDestinationFailed{ + Reason: "late failure", + }, &PaymentBridgeEnvironment{ + PaymentHash: snapshot.PaymentHash, + }, + ) + require.ErrorContains(t, err, "cannot fail after preimage") +} + +// TestPaymentBridgeOutgoingSourceUnavailable proves client-side failure before +// the hold invoice locks cannot dispatch the public destination payment. +func TestPaymentBridgeOutgoingSourceUnavailable(t *testing.T) { + snapshot, _ := testPaymentBridgeSnapshot(t, PaymentOutgoing) + state, err := NewPaymentBridgeState(snapshot) + require.NoError(t, err) + state = applyPaymentEvent(t, state, &PaymentSourcePrepared{}) + state = applyPaymentEvent(t, state, &PaymentSourceUnavailable{ + Reason: "private route failed", + }) + + require.Equal(t, PaymentSourceFailing, state.Snapshot().Phase) + require.Equal(t, "private route failed", state.Snapshot().Failure) + + _, err = state.ProcessEvent( + t.Context(), &PaymentDestinationStarted{ + ChannelID: snapshot.ChannelID, + DestinationSCID: snapshot.ReservedSCID, + }, &PaymentBridgeEnvironment{PaymentHash: snapshot.PaymentHash}, + ) + require.Error(t, err) +} + +// TestSamePaymentBridgeTerms excludes worker-owned lifecycle fields while +// retaining all caller-owned reservation terms. +func TestSamePaymentBridgeTerms(t *testing.T) { + snapshot, preimage := testPaymentBridgeSnapshot(t, PaymentIncoming) + advanced := snapshot.Clone() + advanced.Phase = PaymentPreimageKnown + advanced.DestinationSCID = 44 + advanced.Circuit = &PaymentCircuit{IncomingChannelID: 1} + advanced.Preimage = &preimage + + require.True(t, SamePaymentBridgeTerms(snapshot, advanced)) + advanced.ChannelID = ID{3} + require.False(t, SamePaymentBridgeTerms(snapshot, advanced)) + advanced = snapshot.Clone() + advanced.SourceAmount++ + require.False(t, SamePaymentBridgeTerms(snapshot, advanced)) + advanced = snapshot.Clone() + advanced.PrivateCLTVDeltaBlocks++ + require.False(t, SamePaymentBridgeTerms(snapshot, advanced)) +} + +// TestPaymentBridgeRejectsChannelSubstitution verifies dispatch cannot move +// a held public payment to another channel. +func TestPaymentBridgeRejectsChannelSubstitution(t *testing.T) { + snapshot, _ := testPaymentBridgeSnapshot(t, PaymentIncoming) + state, err := NewPaymentBridgeState(snapshot) + require.NoError(t, err) + state = applyPaymentEvent( + t, state, &PaymentSourceHTLCLocked{ + Circuit: &PaymentCircuit{}, + }, + ) + _, err = state.ProcessEvent(t.Context(), &PaymentDestinationStarted{ + ChannelID: ID{3}, DestinationSCID: 43, + }, &PaymentBridgeEnvironment{PaymentHash: snapshot.PaymentHash}) + require.ErrorContains(t, err, "changed channel") +} + +func applyPaymentEvent(t *testing.T, state PaymentBridgeState, + event PaymentBridgeEvent) PaymentBridgeState { + + t.Helper() + transition, err := state.ProcessEvent( + t.Context(), event, &PaymentBridgeEnvironment{ + PaymentHash: state.Snapshot().PaymentHash, + }, + ) + require.NoError(t, err) + next, ok := transition.NextState.(PaymentBridgeState) + require.True(t, ok) + + return next +} + +func testPaymentBridgeSnapshot(t *testing.T, + direction PaymentDirection) (PaymentBridgeSnapshot, lntypes.Preimage) { + + t.Helper() + clientKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + preimage := lntypes.Preimage{1, 2, 3} + var clientNode [33]byte + copy(clientNode[:], clientKey.PubKey().SerializeCompressed()) + snapshot := PaymentBridgeSnapshot{ + Direction: direction, PaymentHash: preimage.Hash(), + ClientNodeKey: clientNode, ReservedSCID: 42, + SourceAmount: btcutil.Amount(2_100), + DestinationAmount: btcutil.Amount(2_000), + ServerFee: btcutil.Amount(60), + RoutingFeeBudget: btcutil.Amount(40), + } + if direction == PaymentOutgoing { + snapshot.ChannelID = ID{1} + snapshot.PublicInvoice = "lnbcrt1test" + } else { + snapshot.ChannelID = ID{2} + snapshot.SourceAmount = snapshot.DestinationAmount + snapshot.PrivateCLTVDeltaBlocks = 616 + snapshot.ServerFee = 0 + snapshot.RoutingFeeBudget = 0 + } + + return snapshot, preimage +} From 34cc95a055978e84ba34cf1bc1481df7e2f9e6e9 Mon Sep 17 00:00:00 2001 From: sputn1ck Date: Wed, 18 Nov 2026 18:49:36 +0100 Subject: [PATCH 6/7] db: Scope channel transitions to their authenticated peer Store revision-checked snapshots and recovery artifacts together so restart never combines two owners or two versions of a channel. --- db/AGENTS.md | 54 +- db/CLAUDE.md | 54 +- db/ark_channel_store.go | 1025 ++++++++++++++++++++++++++++++++++ db/ark_channel_store_test.go | 589 +++++++++++++++++++ db/store.go | 5 + 5 files changed, 1715 insertions(+), 12 deletions(-) create mode 100644 db/ark_channel_store.go create mode 100644 db/ark_channel_store_test.go diff --git a/db/AGENTS.md b/db/AGENTS.md index 1c488eec4..e7300a647 100644 --- a/db/AGENTS.md +++ b/db/AGENTS.md @@ -3,9 +3,9 @@ ## Purpose Database abstractions and persistent storage for all wavelength state: -boarding intents, boarding sweeps, rounds, VTXOs, OOR sessions, actor -delivery checkpoints, and client-side fee accounting. Supports SQLite and -PostgreSQL backends. +boarding intents, boarding sweeps, rounds, VTXOs, OOR sessions, Ark channel +coordination, actor delivery checkpoints, and client-side fee accounting. +Supports SQLite and PostgreSQL backends. ## Key Types @@ -72,6 +72,19 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/db.)`. The first checkpoint after OOR + preparation begins stamps it, while later state changes preserve it. This + keeps pre-point-of-no-return expiry tied to the age of preparation instead + of the most recent write. +- `ListNonTerminalArkChannels` keeps a cooperatively closed channel (phase 8) + resumable while `cooperative_close_txid IS NOT NULL`. Its signed replacement + VTXOs still require source-ancestry defense, so restart recovery must keep + observing it. Only phase 10 (failed) and a closed channel without a recorded + close transaction drop out. - `unilateral_exit_jobs.exit_policy_kind` and `exit_policy_ref` persist the durable final spend policy identity. Standard timeout jobs use `standard_vtxo_timeout` with an empty ref; policy-specific @@ -478,6 +516,10 @@ when adding one. post-step detects the old refresh/exit collision and reconstructs the missing net exit-send row from the surviving refresh-send and exit-fee rows, repairing the overstated VTXO balance atomically with the key rewrite. +- `000032_ark_channels` — creates the channel record and its uniqueness and + recovery indexes. It stores signed Ark backing, each peer's recovery + readiness, observed source spends, preparation start time, and cooperative + settlement. Lightning commitments, HTLCs and payment attempts stay in lnd. - `000021_round_admission_deadlines` — records accepted attempt expiry and closure separately from signature checkpoints. Deadline constraints only diff --git a/db/CLAUDE.md b/db/CLAUDE.md index 1c488eec4..e7300a647 100644 --- a/db/CLAUDE.md +++ b/db/CLAUDE.md @@ -3,9 +3,9 @@ ## Purpose Database abstractions and persistent storage for all wavelength state: -boarding intents, boarding sweeps, rounds, VTXOs, OOR sessions, actor -delivery checkpoints, and client-side fee accounting. Supports SQLite and -PostgreSQL backends. +boarding intents, boarding sweeps, rounds, VTXOs, OOR sessions, Ark channel +coordination, actor delivery checkpoints, and client-side fee accounting. +Supports SQLite and PostgreSQL backends. ## Key Types @@ -72,6 +72,19 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/db.)`. The first checkpoint after OOR + preparation begins stamps it, while later state changes preserve it. This + keeps pre-point-of-no-return expiry tied to the age of preparation instead + of the most recent write. +- `ListNonTerminalArkChannels` keeps a cooperatively closed channel (phase 8) + resumable while `cooperative_close_txid IS NOT NULL`. Its signed replacement + VTXOs still require source-ancestry defense, so restart recovery must keep + observing it. Only phase 10 (failed) and a closed channel without a recorded + close transaction drop out. - `unilateral_exit_jobs.exit_policy_kind` and `exit_policy_ref` persist the durable final spend policy identity. Standard timeout jobs use `standard_vtxo_timeout` with an empty ref; policy-specific @@ -478,6 +516,10 @@ when adding one. post-step detects the old refresh/exit collision and reconstructs the missing net exit-send row from the surviving refresh-send and exit-fee rows, repairing the overstated VTXO balance atomically with the key rewrite. +- `000032_ark_channels` — creates the channel record and its uniqueness and + recovery indexes. It stores signed Ark backing, each peer's recovery + readiness, observed source spends, preparation start time, and cooperative + settlement. Lightning commitments, HTLCs and payment attempts stay in lnd. - `000021_round_admission_deadlines` — records accepted attempt expiry and closure separately from signature checkpoints. Deadline constraints only diff --git a/db/ark_channel_store.go b/db/ark_channel_store.go new file mode 100644 index 000000000..b350f5f94 --- /dev/null +++ b/db/ark_channel_store.go @@ -0,0 +1,1025 @@ +package db + +import ( + "context" + "database/sql" + "encoding/binary" + "errors" + "fmt" + "math" + "slices" + "time" + + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/db/sqlc" + "github.com/lightningnetwork/lnd/clock" +) + +const initialArkChannelRevision = int64(1) + +// ArkChannelStoreDB persists the narrow Ark-to-lnd coordination state. +type ArkChannelStoreDB struct { + *TransactionExecutor[*sqlc.Queries] + + clock clock.Clock + peer *[33]byte +} + +// ForPeer restricts operations on the shared database to one authenticated +// client. A scoped view borrows the database; it never owns its lifetime. +func (s *ArkChannelStoreDB) ForPeer(peer [33]byte) *ArkChannelStoreDB { + return &ArkChannelStoreDB{ + TransactionExecutor: s.TransactionExecutor, + clock: s.clock, + peer: &peer, + } +} + +// RecoveryPeers lists owners with native, unroll or refresh-defense work. +func (s *ArkChannelStoreDB) RecoveryPeers(ctx context.Context) ([][33]byte, + error) { + + var peers [][33]byte + err := s.ExecTx(ctx, ReadTxOption(), func(q *sqlc.Queries) error { + keys, err := q.ListArkRecoveryPeers(ctx) + if err != nil { + return err + } + peers = nil + for _, key := range keys { + var peer [33]byte + if err := copyFixed( + peer[:], key, "client node key", + ); err != nil { + return err + } + if s.peer == nil || peer == *s.peer { + peers = append(peers, peer) + } + } + + return nil + }) + + return peers, err +} + +// readChannel conceals absent and foreign records behind the same result, +// regardless of which unique key was used to find the channel. +func (s *ArkChannelStoreDB) readChannel(ctx context.Context, + lookup func(*sqlc.Queries) (sqlc.ArkChannel, error)) (arkchannel.Record, + error) { + + var row sqlc.ArkChannel + err := s.ExecTx(ctx, ReadTxOption(), func(q *sqlc.Queries) error { + var err error + row, err = lookup(q) + + return err + }) + if errors.Is(err, sql.ErrNoRows) { + return arkchannel.Record{}, arkchannel.ErrNotFound + } + if err != nil { + return arkchannel.Record{}, err + } + if s.peer != nil && !slices.Equal(row.ClientNodeKey, s.peer[:]) { + return arkchannel.Record{}, arkchannel.ErrNotFound + } + + return arkChannelRecordFromRow(row) +} + +// NewArkChannelStore creates a revisioned Ark channel store. +func NewArkChannelStore(store *Store, clk clock.Clock) *ArkChannelStoreDB { + baseDB := store.BaseDB() + txExec := NewTransactionExecutor( + baseDB, + func(tx *sql.Tx) *sqlc.Queries { + return store.Queries().WithTx(tx) + }, + store.log, + ) + + return &ArkChannelStoreDB{ + TransactionExecutor: txExec, + clock: clk, + } +} + +// Create inserts a channel at revision one without replacing existing terms. +func (s *ArkChannelStoreDB) Create(ctx context.Context, + snapshot arkchannel.Snapshot) (arkchannel.Record, error) { + + if s.peer != nil && *s.peer != snapshot.Terms.ClientNodeKey { + return arkchannel.Record{}, arkchannel.ErrNotFound + } + if _, err := arkchannel.RestoreState(snapshot); err != nil { + return arkchannel.Record{}, err + } + nowTime := time.Unix(s.clock.Now().Unix(), 0).UTC() + now := nowTime.Unix() + params, err := insertArkChannelParams(snapshot, now) + if err != nil { + return arkchannel.Record{}, err + } + + var rows int64 + err = s.ExecTx(ctx, WriteTxOption(), func(q *sqlc.Queries) error { + var err error + rows, err = q.InsertArkChannel(ctx, params) + + return err + }) + if err != nil { + return arkchannel.Record{}, err + } + if rows != 1 { + return arkchannel.Record{}, arkchannel.ErrConflict + } + + record := arkchannel.Record{ + Snapshot: snapshot.Clone(), + Revision: uint64(initialArkChannelRevision), + CreatedAt: nowTime, UpdatedAt: nowTime, + } + if snapshot.OORPreparationStarted || snapshot.Source != nil { + record.PrePONRStartedAt = nowTime + } + + return record, nil +} + +// Get loads one channel by stable ID. +func (s *ArkChannelStoreDB) Get(ctx context.Context, id arkchannel.ID) ( + arkchannel.Record, error) { + + return s.readChannel( + ctx, + func(q *sqlc.Queries) (sqlc.ArkChannel, error) { + return q.GetArkChannel(ctx, id[:]) + }, + ) +} + +// GetByPendingChannelID loads one channel by lnd's funding correlation ID. +func (s *ArkChannelStoreDB) GetByPendingChannelID(ctx context.Context, + pendingID [32]byte) (arkchannel.Record, error) { + + return s.readChannel( + ctx, + func(q *sqlc.Queries) (sqlc.ArkChannel, error) { + return q.GetArkChannelByPendingID(ctx, pendingID[:]) + }, + ) +} + +// GetBySCID resolves an alias without loading unrelated signed transactions. +func (s *ArkChannelStoreDB) GetBySCID(ctx context.Context, scid uint64) ( + arkchannel.Record, error) { + + return s.readChannel( + ctx, + func(q *sqlc.Queries) (sqlc.ArkChannel, error) { + return q.GetArkChannelBySCID(ctx, encodeSCID(scid)) + }, + ) +} + +// GetByChannelPoint loads one channel by lnd's durable funding outpoint. +func (s *ArkChannelStoreDB) GetByChannelPoint(ctx context.Context, + channelPoint wire.OutPoint) (arkchannel.Record, error) { + + params := sqlc.GetArkChannelByChannelPointParams{ + ChannelPointTxid: channelPoint.Hash[:], + ChannelPointIndex: sql.NullInt64{ + Int64: int64(channelPoint.Index), Valid: true, + }, + } + + return s.readChannel( + ctx, + func(q *sqlc.Queries) (sqlc.ArkChannel, error) { + return q.GetArkChannelByChannelPoint(ctx, params) + }, + ) +} + +// ListNonTerminal loads channels that need recovery or observation. This +// includes cooperatively closed channels whose replacement VTXOs retain a +// source-ancestry defense obligation. +func (s *ArkChannelStoreDB) ListNonTerminal(ctx context.Context) ( + []arkchannel.Record, error) { + + var rows []sqlc.ArkChannel + err := s.ExecTx(ctx, ReadTxOption(), func(q *sqlc.Queries) error { + var err error + if s.peer == nil { + rows, err = q.ListNonTerminalArkChannels(ctx) + } else { + rows, err = q.ListPeerArkChannels(ctx, s.peer[:]) + } + + return err + }) + if err != nil { + return nil, err + } + + records := make([]arkchannel.Record, 0, len(rows)) + for _, row := range rows { + record, err := arkChannelRecordFromRow(row) + if err != nil { + return nil, err + } + + records = append(records, record) + } + + return records, nil +} + +// BindFundingTxID claims the canonical backing at the same revision whose +// terms, source and phase authorized signing. It cannot replace a prior claim. +func (s *ArkChannelStoreDB) BindFundingTxID(ctx context.Context, + terms arkchannel.Terms, revision uint64, txid chainhash.Hash) error { + + if s.peer != nil && *s.peer != terms.ClientNodeKey { + return arkchannel.ErrNotFound + } + if revision == 0 || revision >= math.MaxInt64 { + return fmt.Errorf("invalid funding authorization revision %d", + revision) + } + + return s.ExecTx(ctx, WriteTxOption(), func(q *sqlc.Queries) error { + rows, err := q.AuthorizeArkFundingBacking(ctx, + sqlc.AuthorizeArkFundingBackingParams{ + Txid: txid[:], UpdatedAt: s.clock.Now().Unix(), + ChannelID: terms.ID[:], Revision: int64( + revision, + ), + OwnerKey: terms.ClientNodeKey[:], + }, + ) + if err != nil { + return err + } + if rows != 1 { + return arkchannel.ErrConflict + } + + return nil + }) +} + +// RecordFundingSignature commits the winning signature before its caller can +// release it. A concurrent cancellation invalidates the observed revision. +func (s *ArkChannelStoreDB) RecordFundingSignature(ctx context.Context, + terms arkchannel.Terms, revision uint64, txid chainhash.Hash, + sig []byte) error { + + if s.peer != nil && *s.peer != terms.ClientNodeKey { + return arkchannel.ErrNotFound + } + if revision == 0 || revision >= math.MaxInt64 { + return fmt.Errorf("invalid funding signature revision %d", + revision) + } + + return s.ExecTx(ctx, WriteTxOption(), func(q *sqlc.Queries) error { + rows, err := q.RecordArkFundingSignature(ctx, + sqlc.RecordArkFundingSignatureParams{ + Signature: sig, + Txid: txid[:], + UpdatedAt: s.clock.Now().Unix(), + ChannelID: terms.ID[:], + Revision: int64(revision), + OwnerKey: terms.ClientNodeKey[:], + }, + ) + if err != nil { + return err + } + if rows != 1 { + return arkchannel.ErrConflict + } + + return nil + }) +} + +// CompareAndSwap advances mutable state from one expected revision. +func (s *ArkChannelStoreDB) CompareAndSwap(ctx context.Context, + id arkchannel.ID, expected uint64, snapshot arkchannel.Snapshot) ( + arkchannel.Record, error) { + + if s.peer != nil && *s.peer != snapshot.Terms.ClientNodeKey { + return arkchannel.Record{}, arkchannel.ErrNotFound + } + if snapshot.Terms.ID != id { + return arkchannel.Record{}, fmt.Errorf("snapshot channel ID " + + "mismatch") + } + if expected == 0 || expected >= math.MaxInt64 { + return arkchannel.Record{}, fmt.Errorf("invalid expected "+ + "revision %d", expected) + } + if _, err := arkchannel.RestoreState(snapshot); err != nil { + return arkchannel.Record{}, err + } + + params, err := compareAndSwapArkChannelParams( + snapshot, int64(expected), s.clock.Now().Unix(), + ) + if err != nil { + return arkchannel.Record{}, err + } + var ( + rows int64 + row sqlc.ArkChannel + ) + err = s.ExecTx(ctx, WriteTxOption(), func(q *sqlc.Queries) error { + var err error + rows, err = q.CompareAndSwapArkChannel(ctx, params) + if err != nil || rows != 1 { + return err + } + row, err = q.GetArkChannel(ctx, id[:]) + + return err + }) + if err != nil { + return arkchannel.Record{}, err + } + if rows != 1 { + return arkchannel.Record{}, arkchannel.ErrConflict + } + + return arkChannelRecordFromRow(row) +} + +// arkChannelMutableFields is the shared SQL representation of mutable state. +type arkChannelMutableFields struct { + phase int32 + oorSessionID []byte + sourceIndex sql.NullInt64 + sourceAmount sql.NullInt64 + sourceArkTx []byte + backingTx []byte + channelPointTxID []byte + channelPointIndex sql.NullInt64 + clientFinalized bool + hubFinalized bool + oorFinalized bool + oorAborted bool + clientRecoveryReady bool + hubRecoveryReady bool + sourceSpentOutpointID []byte + sourceSpentOutpointIndex sql.NullInt64 + sourceSpendingTxID []byte + backingPublished bool + closeInitiator sql.NullInt32 + closeClientScript []byte + closeHubScript []byte + closeFeeRate sql.NullInt64 + cooperativeCloseTx []byte + cooperativeCloseTxID []byte + closeCommitmentHeight sql.NullInt64 + closeClientBalance sql.NullInt64 + closeHubBalance sql.NullInt64 + failure sql.NullString +} + +// mutableArkChannelFields converts optional snapshot fields for sqlc. +func mutableArkChannelFields(snapshot arkchannel.Snapshot) ( + arkChannelMutableFields, error) { + + fields := arkChannelMutableFields{ + phase: int32(snapshot.Phase), + clientFinalized: snapshot.ClientFinalized, + hubFinalized: snapshot.HubFinalized, + oorFinalized: snapshot.OORFinalized, + oorAborted: snapshot.OORAborted, + clientRecoveryReady: snapshot.ClientRecoveryReady, + hubRecoveryReady: snapshot.HubRecoveryReady, + backingPublished: snapshot.BackingPublished, + failure: sql.NullString{ + String: snapshot.Failure, + Valid: snapshot.Failure != "", + }, + } + if snapshot.SourceConflict != nil { + fields.sourceSpentOutpointID = slices.Clone( + snapshot.SourceConflict.OutPoint.Hash[:], + ) + fields.sourceSpentOutpointIndex = sql.NullInt64{ + Int64: int64(snapshot.SourceConflict.OutPoint.Index), + Valid: true, + } + fields.sourceSpendingTxID = slices.Clone( + snapshot.SourceConflict.SpendingTxID[:], + ) + } + if snapshot.Source != nil { + fields.oorSessionID = slices.Clone( + snapshot.Source.OORSessionID[:], + ) + fields.sourceIndex = sql.NullInt64{ + Int64: int64(snapshot.Source.OutPoint.Index), + Valid: true, + } + fields.sourceAmount = sql.NullInt64{ + Int64: int64(snapshot.Source.Amount), + Valid: true, + } + fields.sourceArkTx = slices.Clone( + snapshot.Source.ArkTransaction, + ) + } + if snapshot.Backing != nil { + fields.backingTx = slices.Clone(snapshot.Backing.Transaction) + fields.channelPointTxID = slices.Clone( + snapshot.Backing.ChannelPoint.Hash[:], + ) + fields.channelPointIndex = sql.NullInt64{ + Int64: int64(snapshot.Backing.ChannelPoint.Index), + Valid: true, + } + } + if snapshot.CooperativeCloseRequest != nil { + request := snapshot.CooperativeCloseRequest + fields.closeInitiator = sql.NullInt32{ + Int32: int32(request.Initiator), + Valid: true, + } + fields.closeClientScript = slices.Clone( + request.ClientDeliveryScript, + ) + fields.closeHubScript = slices.Clone(request.HubDeliveryScript) + // The column predates in-Ark OOR close semantics. Keep a zero + // sentinel so existing databases retain their group constraint. + fields.closeFeeRate = sql.NullInt64{Valid: true} + } + if snapshot.CooperativeClose != nil { + settlement := snapshot.CooperativeClose + if settlement.Proposal.CommitmentHeight > math.MaxInt64 { + return arkChannelMutableFields{}, fmt.Errorf( + "cooperative close commitment height is out " + + "of range") + } + fields.cooperativeCloseTx = slices.Clone(settlement.Transaction) + fields.cooperativeCloseTxID = slices.Clone(settlement.TxID[:]) + fields.closeCommitmentHeight = sql.NullInt64{ + Int64: int64(settlement.Proposal.CommitmentHeight), + Valid: true, + } + fields.closeClientBalance = sql.NullInt64{ + Int64: int64(settlement.Proposal.ClientBalance), + Valid: true, + } + fields.closeHubBalance = sql.NullInt64{ + Int64: int64(settlement.Proposal.HubBalance), + Valid: true, + } + } + + return fields, nil +} + +// insertArkChannelParams builds a complete immutable insert. +func insertArkChannelParams(snapshot arkchannel.Snapshot, + now int64) (sqlc.InsertArkChannelParams, error) { + + fields, err := mutableArkChannelFields(snapshot) + if err != nil { + return sqlc.InsertArkChannelParams{}, err + } + terms := snapshot.Terms + + return sqlc.InsertArkChannelParams{ + ChannelID: slices.Clone(terms.ID[:]), + PendingChannelID: slices.Clone(terms.PendingChannelID[:]), + ReservedScid: encodeSCID(terms.ReservedSCID), + Capacity: int64(terms.Capacity), + ClientNodeKey: slices.Clone(terms.ClientNodeKey[:]), + HubNodeKey: slices.Clone(terms.HubNodeKey[:]), + ClientArkKey: slices.Clone(terms.VTXO.ClientArkKey[:]), + HubArkKey: slices.Clone(terms.VTXO.HubArkKey[:]), + ArkOperatorKey: slices.Clone( + terms.VTXO.ArkOperatorKey[:], + ), + ClientChannelKey: slices.Clone( + terms.VTXO.ClientChannelKey[:], + ), + HubChannelKey: slices.Clone( + terms.VTXO.HubChannelKey[:], + ), + FunderKey: slices.Clone(terms.VTXO.FunderKey[:]), + ChannelDelay: int64(terms.VTXO.ChannelDelay), + FunderDelay: int64(terms.VTXO.FunderDelay), + MinExitDelay: int64(terms.VTXO.MinExitDelay), + Phase: fields.phase, + OorSessionID: fields.oorSessionID, + SourceIndex: fields.sourceIndex, + SourceAmount: fields.sourceAmount, + SourceArkTx: fields.sourceArkTx, + BackingTx: fields.backingTx, + ChannelPointTxid: fields.channelPointTxID, + ChannelPointIndex: fields.channelPointIndex, + ClientFinalized: fields.clientFinalized, + HubFinalized: fields.hubFinalized, + OorFinalized: fields.oorFinalized, + OorAborted: fields.oorAborted, + ClientRecoveryReady: fields.clientRecoveryReady, + HubRecoveryReady: fields.hubRecoveryReady, + SourceSpentOutpointTxid: fields.sourceSpentOutpointID, + SourceSpentOutpointIndex: fields.sourceSpentOutpointIndex, + SourceSpendingTxid: fields.sourceSpendingTxID, + BackingPublished: fields.backingPublished, + CloseInitiator: fields.closeInitiator, + CloseClientScript: fields.closeClientScript, + CloseHubScript: fields.closeHubScript, + CloseFeeRateSatPerKw: fields.closeFeeRate, + CooperativeCloseTx: fields.cooperativeCloseTx, + CooperativeCloseTxid: fields.cooperativeCloseTxID, + CloseCommitmentHeight: fields.closeCommitmentHeight, + CloseClientBalance: fields.closeClientBalance, + CloseHubBalance: fields.closeHubBalance, + Failure: fields.failure, + Revision: initialArkChannelRevision, + CreatedAt: now, + UpdatedAt: now, + PrePonrStartedAt: arkChannelPrePONRStartedAt( + snapshot, now, + ), + }, nil +} + +// compareAndSwapArkChannelParams builds a mutable revision update. +func compareAndSwapArkChannelParams(snapshot arkchannel.Snapshot, revision, + now int64) (sqlc.CompareAndSwapArkChannelParams, error) { + + fields, err := mutableArkChannelFields(snapshot) + if err != nil { + return sqlc.CompareAndSwapArkChannelParams{}, err + } + + return sqlc.CompareAndSwapArkChannelParams{ + ChannelID: slices.Clone(snapshot.Terms.ID[:]), + Revision: revision, + OwnerKey: snapshot.Terms.ClientNodeKey[:], + Phase: fields.phase, + OorSessionID: fields.oorSessionID, + SourceIndex: fields.sourceIndex, + SourceAmount: fields.sourceAmount, + SourceArkTx: fields.sourceArkTx, + BackingTx: fields.backingTx, + ChannelPointTxid: fields.channelPointTxID, + ChannelPointIndex: fields.channelPointIndex, + ClientFinalized: fields.clientFinalized, + HubFinalized: fields.hubFinalized, + OorFinalized: fields.oorFinalized, + OorAborted: fields.oorAborted, + ClientRecoveryReady: fields.clientRecoveryReady, + HubRecoveryReady: fields.hubRecoveryReady, + SourceSpentOutpointTxid: fields.sourceSpentOutpointID, + SourceSpentOutpointIndex: fields.sourceSpentOutpointIndex, + SourceSpendingTxid: fields.sourceSpendingTxID, + BackingPublished: fields.backingPublished, + CloseInitiator: fields.closeInitiator, + CloseClientScript: fields.closeClientScript, + CloseHubScript: fields.closeHubScript, + CloseFeeRateSatPerKw: fields.closeFeeRate, + CooperativeCloseTx: fields.cooperativeCloseTx, + CooperativeCloseTxid: fields.cooperativeCloseTxID, + CloseCommitmentHeight: fields.closeCommitmentHeight, + CloseClientBalance: fields.closeClientBalance, + CloseHubBalance: fields.closeHubBalance, + Failure: fields.failure, + UpdatedAt: now, + PrePonrStartedAt: arkChannelPrePONRStartedAt( + snapshot, now, + ), + }, nil +} + +// arkChannelPrePONRStartedAt returns the first timestamp candidate only after +// preparation is durably armed. SQL preserves any earlier timestamp. +func arkChannelPrePONRStartedAt(snapshot arkchannel.Snapshot, + now int64) sql.NullInt64 { + + started := snapshot.OORPreparationStarted || snapshot.Source != nil + + return sql.NullInt64{Int64: now, Valid: started} +} + +// arkChannelRecordFromRow validates one SQL row before exposing it. +func arkChannelRecordFromRow(row sqlc.ArkChannel) (arkchannel.Record, error) { + var terms arkchannel.Terms + if err := copyFixed( + terms.ID[:], row.ChannelID, "channel ID", + ); err != nil { + return arkchannel.Record{}, err + } + if err := copyFixed( + terms.PendingChannelID[:], row.PendingChannelID, + "pending channel ID", + ); err != nil { + return arkchannel.Record{}, err + } + if err := copyFixed( + terms.ClientNodeKey[:], row.ClientNodeKey, "client node key", + ); err != nil { + return arkchannel.Record{}, err + } + if err := copyFixed( + terms.HubNodeKey[:], row.HubNodeKey, "hub node key", + ); err != nil { + return arkchannel.Record{}, err + } + if err := copyFixed( + terms.VTXO.ClientArkKey[:], row.ClientArkKey, "client Ark key", + ); err != nil { + return arkchannel.Record{}, err + } + if err := copyFixed( + terms.VTXO.HubArkKey[:], row.HubArkKey, "hub Ark key", + ); err != nil { + return arkchannel.Record{}, err + } + if err := copyFixed( + terms.VTXO.ArkOperatorKey[:], row.ArkOperatorKey, + "Ark operator key", + ); err != nil { + return arkchannel.Record{}, err + } + if err := copyFixed( + terms.VTXO.ClientChannelKey[:], row.ClientChannelKey, + "client channel key", + ); err != nil { + return arkchannel.Record{}, err + } + if err := copyFixed( + terms.VTXO.HubChannelKey[:], row.HubChannelKey, + "hub channel key", + ); err != nil { + return arkchannel.Record{}, err + } + if err := copyFixed( + terms.VTXO.FunderKey[:], row.FunderKey, "funder key", + ); err != nil { + return arkchannel.Record{}, err + } + channelDelay, err := decodeDelay(row.ChannelDelay, "channel delay") + if err != nil { + return arkchannel.Record{}, err + } + funderDelay, err := decodeDelay(row.FunderDelay, "funder delay") + if err != nil { + return arkchannel.Record{}, err + } + minExitDelay, err := decodeDelay( + row.MinExitDelay, "minimum exit delay", + ) + if err != nil { + return arkchannel.Record{}, err + } + terms.VTXO.ChannelDelay = channelDelay + terms.VTXO.FunderDelay = funderDelay + terms.VTXO.MinExitDelay = minExitDelay + reservedSCID, err := decodeSCID(row.ReservedScid) + if err != nil { + return arkchannel.Record{}, err + } + terms.Kind = arkchannel.KindPromotion + terms.Funder = arkchannel.PartyClient + terms.ReservedSCID = reservedSCID + terms.Capacity = btcutil.Amount(row.Capacity) + + snapshot := arkchannel.Snapshot{ + Terms: terms, + Phase: arkchannel.Phase(row.Phase), + OORPreparationStarted: row.PrePonrStartedAt.Valid, + ClientFinalized: row.ClientFinalized, + HubFinalized: row.HubFinalized, + OORFinalized: row.OorFinalized, + OORAborted: row.OorAborted, + ClientRecoveryReady: row.ClientRecoveryReady, + HubRecoveryReady: row.HubRecoveryReady, + BackingPublished: row.BackingPublished, + Failure: row.Failure.String, + } + conflict, err := arkChannelSourceConflictFromRow(row) + if err != nil { + return arkchannel.Record{}, err + } + snapshot.SourceConflict = conflict + source, err := arkChannelSourceFromRow(row, terms) + if err != nil { + return arkchannel.Record{}, err + } + snapshot.Source = source + backing, err := arkChannelBackingFromRow(row) + if err != nil { + return arkchannel.Record{}, err + } + snapshot.Backing = backing + closeRequest, err := arkChannelCloseRequestFromRow(row) + if err != nil { + return arkchannel.Record{}, err + } + snapshot.CooperativeCloseRequest = closeRequest + cooperativeClose, err := arkChannelCooperativeCloseFromRow( + row, terms, source, closeRequest, + ) + if err != nil { + return arkchannel.Record{}, err + } + snapshot.CooperativeClose = cooperativeClose + + if row.Revision <= 0 { + return arkchannel.Record{}, fmt.Errorf("invalid channel "+ + "revision %d", row.Revision) + } + if _, err := arkchannel.RestoreState(snapshot); err != nil { + return arkchannel.Record{}, fmt.Errorf("restore Ark "+ + "channel: %w", err) + } + + var authorization *chainhash.Hash + if row.AuthorizedBackingTxid != nil { + authorization, err = chainhash.NewHash( + row.AuthorizedBackingTxid, + ) + if err != nil { + return arkchannel.Record{}, err + } + } + + return arkchannel.Record{ + AuthorizedBackingTxID: authorization, + FundingSignature: row.FundingSignature, + Snapshot: snapshot, + Revision: uint64(row.Revision), + CreatedAt: time.Unix(row.CreatedAt, 0).UTC(), + UpdatedAt: time.Unix(row.UpdatedAt, 0).UTC(), + PrePONRStartedAt: nullableUnixTime( + row.PrePonrStartedAt, + ), + }, nil +} + +// nullableUnixTime decodes optional persisted lifecycle metadata. +func nullableUnixTime(value sql.NullInt64) time.Time { + if !value.Valid { + return time.Time{} + } + + return time.Unix(value.Int64, 0).UTC() +} + +// arkChannelSourceConflictFromRow restores the all-or-none source-spend tuple. +func arkChannelSourceConflictFromRow(row sqlc.ArkChannel) ( + *arkchannel.SourceConflict, error) { + + present := len(row.SourceSpentOutpointTxid) != 0 || + row.SourceSpentOutpointIndex.Valid || + len(row.SourceSpendingTxid) != 0 + if !present { + return nil, nil + } + if len(row.SourceSpentOutpointTxid) != chainhash.HashSize || + !row.SourceSpentOutpointIndex.Valid || + row.SourceSpentOutpointIndex.Int64 < 0 || + row.SourceSpentOutpointIndex.Int64 > math.MaxUint32 || + len(row.SourceSpendingTxid) != chainhash.HashSize { + return nil, fmt.Errorf("incomplete Ark channel source conflict") + } + outpointTxID, err := chainhash.NewHash(row.SourceSpentOutpointTxid) + if err != nil { + return nil, err + } + spendingTxID, err := chainhash.NewHash(row.SourceSpendingTxid) + if err != nil { + return nil, err + } + + return &arkchannel.SourceConflict{ + OutPoint: wire.OutPoint{ + Hash: *outpointTxID, + Index: uint32(row.SourceSpentOutpointIndex.Int64), + }, + SpendingTxID: *spendingTxID, + }, nil +} + +// arkChannelSourceFromRow decodes the optional source group. +func arkChannelSourceFromRow(row sqlc.ArkChannel, + terms arkchannel.Terms) (*arkchannel.VTXOBinding, error) { + + if len(row.OorSessionID) == 0 { + return nil, nil + } + var oorSessionID [32]byte + if err := copyFixed( + oorSessionID[:], row.OorSessionID, "OOR session ID", + ); err != nil { + return nil, err + } + sourceIndex, err := decodeIndex(row.SourceIndex, "source index") + if err != nil { + return nil, err + } + if !row.SourceAmount.Valid { + return nil, fmt.Errorf("source amount is missing") + } + policy, pkScript, err := terms.VTXO.Artifacts() + if err != nil { + return nil, err + } + + return &arkchannel.VTXOBinding{ + OORSessionID: oorSessionID, + OutPoint: wire.OutPoint{ + Hash: chainhash.Hash(oorSessionID), + Index: sourceIndex, + }, + Amount: btcutil.Amount(row.SourceAmount.Int64), + ArkTransaction: slices.Clone(row.SourceArkTx), + PolicyTemplate: policy, + PkScript: pkScript, + }, nil +} + +// arkChannelBackingFromRow decodes the optional signed-backing group. +func arkChannelBackingFromRow(row sqlc.ArkChannel) (*arkchannel.Backing, + error) { + + if len(row.BackingTx) == 0 { + return nil, nil + } + txID, err := chainhash.NewHash(row.ChannelPointTxid) + if err != nil { + return nil, fmt.Errorf("decode channel point txid: %w", err) + } + index, err := decodeIndex(row.ChannelPointIndex, "channel point index") + if err != nil { + return nil, err + } + + return &arkchannel.Backing{ + Transaction: slices.Clone(row.BackingTx), + ChannelPoint: wire.OutPoint{ + Hash: *txID, + Index: index, + }, + }, nil +} + +// arkChannelCloseRequestFromRow decodes the optional cooperative-close request +// group. +func arkChannelCloseRequestFromRow(row sqlc.ArkChannel) ( + *arkchannel.CooperativeCloseRequest, error) { + + if !row.CloseInitiator.Valid { + if len(row.CloseClientScript) != 0 || + len(row.CloseHubScript) != 0 || + row.CloseFeeRateSatPerKw.Valid { + return nil, fmt.Errorf("cooperative close request is " + + "incomplete") + } + + return nil, nil + } + if len(row.CloseClientScript) == 0 || len(row.CloseHubScript) == 0 || + !row.CloseFeeRateSatPerKw.Valid { + return nil, fmt.Errorf("cooperative close request is " + + "incomplete") + } + request := &arkchannel.CooperativeCloseRequest{ + Initiator: arkchannel.Party(row.CloseInitiator.Int32), + ClientDeliveryScript: slices.Clone( + row.CloseClientScript, + ), + HubDeliveryScript: slices.Clone(row.CloseHubScript), + } + if err := request.Validate(); err != nil { + return nil, err + } + + return request, nil +} + +// arkChannelCooperativeCloseFromRow rebuilds the canonical unsigned proposal +// from compact SQL facts and attaches the persisted signed witness. +func arkChannelCooperativeCloseFromRow(row sqlc.ArkChannel, + terms arkchannel.Terms, source *arkchannel.VTXOBinding, + request *arkchannel.CooperativeCloseRequest) ( + *arkchannel.CooperativeClose, error) { + + if len(row.CooperativeCloseTx) == 0 { + if len(row.CooperativeCloseTxid) != 0 || + row.CloseCommitmentHeight.Valid || + row.CloseClientBalance.Valid || + row.CloseHubBalance.Valid { + return nil, fmt.Errorf("cooperative close artifact " + + "is incomplete") + } + + return nil, nil + } + if source == nil || request == nil || + len(row.CooperativeCloseTxid) == 0 || + !row.CloseCommitmentHeight.Valid || + !row.CloseClientBalance.Valid || !row.CloseHubBalance.Valid { + return nil, fmt.Errorf("cooperative close artifact is " + + "incomplete") + } + if row.CloseCommitmentHeight.Int64 < 0 || + row.CloseClientBalance.Int64 < 0 || + row.CloseHubBalance.Int64 < 0 { + return nil, fmt.Errorf("cooperative close artifact has " + + "negative values") + } + txID, err := chainhash.NewHash(row.CooperativeCloseTxid) + if err != nil { + return nil, fmt.Errorf("decode cooperative close txid: %w", err) + } + template, err := arkchannel.NewCooperativeCloseTemplate( + terms, *source, *request, + btcutil.Amount(row.CloseClientBalance.Int64), + btcutil.Amount(row.CloseHubBalance.Int64), + uint64(row.CloseCommitmentHeight.Int64), + ) + if err != nil { + return nil, err + } + settlement := &arkchannel.CooperativeClose{ + Proposal: template.Proposal(), + Transaction: slices.Clone(row.CooperativeCloseTx), + TxID: *txID, + } + if err := settlement.Validate(terms, *source, *request); err != nil { + return nil, err + } + + return settlement, nil +} + +// copyFixed rejects corrupt fixed-width SQL blobs. +func copyFixed(dst, src []byte, field string) error { + if len(src) != len(dst) { + return fmt.Errorf("%s has %d bytes, expected %d", field, + len(src), len(dst)) + } + + copy(dst, src) + + return nil +} + +// encodeSCID preserves the full unsigned short-channel-ID domain. +func encodeSCID(scid uint64) []byte { + var encoded [8]byte + binary.BigEndian.PutUint64(encoded[:], scid) + + return encoded[:] +} + +// decodeSCID decodes the fixed-width unsigned short channel ID. +func decodeSCID(raw []byte) (uint64, error) { + if len(raw) != 8 { + return 0, fmt.Errorf("reserved SCID has %d bytes, expected 8", + len(raw)) + } + + return binary.BigEndian.Uint64(raw), nil +} + +// decodeIndex validates a nullable SQL index before narrowing it. +func decodeIndex(index sql.NullInt64, field string) (uint32, error) { + if !index.Valid { + return 0, fmt.Errorf("%s is missing", field) + } + if index.Int64 < 0 || index.Int64 > math.MaxUint32 { + return 0, fmt.Errorf("%s %d is out of range", field, + index.Int64) + } + + return uint32(index.Int64), nil +} + +// decodeDelay rejects corrupt SQL values before narrowing to BIP-68 fields. +func decodeDelay(delay int64, field string) (uint32, error) { + if delay < 0 || delay > math.MaxUint32 { + return 0, fmt.Errorf("%s %d is out of range", field, delay) + } + + return uint32(delay), nil +} + +var _ arkchannel.Store = (*ArkChannelStoreDB)(nil) diff --git a/db/ark_channel_store_test.go b/db/ark_channel_store_test.go new file mode 100644 index 000000000..b150c9123 --- /dev/null +++ b/db/ark_channel_store_test.go @@ -0,0 +1,589 @@ +package db + +import ( + "bytes" + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/psbt/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/tx/psbtutil" + "github.com/lightningnetwork/lnd/clock" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/keychain" + "github.com/lightningnetwork/lnd/lnwire" + "github.com/stretchr/testify/require" +) + +// TestArkChannelStoreRoundTrip verifies revisions, optional backing fields, +// unsigned SCIDs, and non-terminal recovery scans. +func TestArkChannelStoreRoundTrip(t *testing.T) { + t.Parallel() + + store := newArkChannelStoreForTest(t) + coordinator, err := arkchannel.NewCoordinator(store) + require.NoError(t, err) + terms := testArkChannelTerms(t, arkchannel.KindPromotion, 1) + terms.ReservedSCID = lnwire.ShortChannelID{ + BlockHeight: 0x800001, + TxIndex: 1, + }.ToUint64() + + requested, err := coordinator.Request(t.Context(), terms) + require.NoError(t, err) + require.False(t, requested.CreatedAt.IsZero()) + require.False(t, requested.UpdatedAt.IsZero()) + require.True(t, requested.PrePONRStartedAt.IsZero()) + armed, _, err := coordinator.Apply( + t.Context(), terms.ID, &arkchannel.OORPreparationStarted{}, + ) + require.NoError(t, err) + require.True(t, armed.Snapshot.OORPreparationStarted) + require.Nil(t, armed.Snapshot.Source) + require.False(t, armed.PrePONRStartedAt.IsZero()) + prePONRStartedAt := armed.PrePONRStartedAt + binding := testArkChannelBinding(terms) + bound, _, err := coordinator.Apply( + t.Context(), terms.ID, &arkchannel.BindVTXO{ + Binding: binding, + }, + ) + require.NoError(t, err) + require.Equal(t, prePONRStartedAt, bound.PrePONRStartedAt) + backing := testArkChannelBacking(t, terms, binding) + for _, event := range []arkchannel.Event{ + &arkchannel.BackingSigned{ + Backing: backing, + }, + &arkchannel.FundingFinalized{ + Party: arkchannel.PartyClient, + }, + &arkchannel.FundingFinalized{ + Party: arkchannel.PartyHub, + }, + } { + _, _, err = coordinator.Apply(t.Context(), terms.ID, event) + require.NoError(t, err) + } + + loaded, err := store.Get(t.Context(), terms.ID) + require.NoError(t, err) + require.Equal(t, arkchannel.PhaseBackingReady, loaded.Snapshot.Phase) + require.Equal(t, terms.ReservedSCID, loaded.Snapshot.Terms.ReservedSCID) + require.Equal(t, backing, *loaded.Snapshot.Backing) + require.Equal(t, binding, *loaded.Snapshot.Source) + require.Equal(t, prePONRStartedAt, loaded.PrePONRStartedAt) + byPendingID, err := store.GetByPendingChannelID( + t.Context(), terms.PendingChannelID, + ) + require.NoError(t, err) + require.Equal(t, loaded, byPendingID) + byChannelPoint, err := store.GetByChannelPoint( + t.Context(), backing.ChannelPoint, + ) + require.NoError(t, err) + require.Equal(t, loaded, byChannelPoint) + + _, err = store.CompareAndSwap( + t.Context(), terms.ID, bound.Revision, bound.Snapshot, + ) + require.ErrorIs(t, err, arkchannel.ErrConflict) + + failedTerms := testArkChannelTerms(t, arkchannel.KindPromotion, 2) + _, err = coordinator.Request(t.Context(), failedTerms) + require.NoError(t, err) + _, _, err = coordinator.Apply( + t.Context(), failedTerms.ID, &arkchannel.Fail{ + Reason: "negotiation rejected", + }, + ) + require.NoError(t, err) + + records, err := store.ListNonTerminal(t.Context()) + require.NoError(t, err) + require.Len(t, records, 1) + require.Equal(t, terms.ID, records[0].Snapshot.Terms.ID) +} + +// TestArkChannelStoreRejectsDuplicateProtocolBindings proves a virtual SCID +// and prepared OOR output cannot identify more than one channel. +func TestArkChannelStoreRejectsDuplicateProtocolBindings(t *testing.T) { + t.Parallel() + + t.Run("reserved SCID", func(t *testing.T) { + store := newArkChannelStoreForTest(t) + coordinator, err := arkchannel.NewCoordinator(store) + require.NoError(t, err) + first := testArkChannelTerms(t, arkchannel.KindPromotion, 20) + second := testArkChannelTerms(t, arkchannel.KindPromotion, 21) + second.ReservedSCID = first.ReservedSCID + + _, err = coordinator.Request(t.Context(), first) + require.NoError(t, err) + _, err = coordinator.Request(t.Context(), second) + require.Error(t, err) + require.True(t, IsUniqueConstraintViolation(err), err) + }) + + t.Run("prepared source", func(t *testing.T) { + store := newArkChannelStoreForTest(t) + coordinator, err := arkchannel.NewCoordinator(store) + require.NoError(t, err) + first := testArkChannelTerms(t, arkchannel.KindPromotion, 22) + second := first.Clone() + second.ID[0]++ + second.PendingChannelID[0]++ + second.ReservedSCID += 1 << 16 + + _, err = coordinator.Request(t.Context(), first) + require.NoError(t, err) + _, err = coordinator.Request(t.Context(), second) + require.NoError(t, err) + binding := testArkChannelBinding(first) + _, _, err = coordinator.Apply( + t.Context(), first.ID, &arkchannel.BindVTXO{ + Binding: binding, + }, + ) + require.NoError(t, err) + _, _, err = coordinator.Apply( + t.Context(), second.ID, &arkchannel.BindVTXO{ + Binding: binding, + }, + ) + require.Error(t, err) + require.True(t, IsUniqueConstraintViolation(err), err) + }) +} + +// TestArkChannelStoreCooperativeCloseRoundTrip verifies the compact SQL facts +// reconstruct and validate the exact hub-authorized OOR close. +func TestArkChannelStoreCooperativeCloseRoundTrip(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + name string + rotated bool + }{{ + "legacy", + false, + }, { + "rotated", + true, + }} { + t.Run(tc.name, func(t *testing.T) { + testArkChannelCloseRoundTrip(t, tc.rotated) + }) + } +} + +// testArkChannelCloseRoundTrip rebuilds the signed close from SQL, without +// access to the currently advertised operator key. +func testArkChannelCloseRoundTrip(t *testing.T, rotated bool) { + t.Helper() + store := newArkChannelStoreForTest(t) + coordinator, err := arkchannel.NewCoordinator(store) + require.NoError(t, err) + terms := testArkChannelTerms(t, arkchannel.KindPromotion, 8) + clientKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + hubKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + operatorKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + terms.VTXO.ClientArkKey = testArkChannelCompressedKey(clientKey) + terms.VTXO.HubArkKey = testArkChannelCompressedKey(hubKey) + terms.VTXO.ArkOperatorKey = testArkChannelCompressedKey(operatorKey) + binding := testArkChannelBinding(terms) + backing := testArkChannelBacking(t, terms, binding) + _, err = coordinator.Request(t.Context(), terms) + require.NoError(t, err) + for _, event := range []arkchannel.Event{ + &arkchannel.BindVTXO{ + Binding: binding, + }, + &arkchannel.BackingSigned{ + Backing: backing, + }, + &arkchannel.FundingFinalized{ + Party: arkchannel.PartyClient, + }, + &arkchannel.FundingFinalized{ + Party: arkchannel.PartyHub, + }, + &arkchannel.OORFinalized{ + SessionID: binding.OORSessionID, + }, + &arkchannel.RecoveryPackageInstalled{ + Party: arkchannel.PartyClient, + }, + &arkchannel.RecoveryPackageInstalled{ + Party: arkchannel.PartyHub, + }, + &arkchannel.ChannelActive{ + ChannelPointHash: backing.ChannelPoint.Hash, + ChannelPointIndex: backing.ChannelPoint.Index, + }, + } { + _, _, err = coordinator.Apply(t.Context(), terms.ID, event) + require.NoError(t, err) + } + request := arkchannel.CooperativeCloseRequest{ + Initiator: arkchannel.PartyClient, + ClientDeliveryScript: clientKey.PubKey().SerializeCompressed(), + HubDeliveryScript: hubKey.PubKey().SerializeCompressed(), + } + if rotated { + next, err := btcec.NewPrivateKey() + require.NoError(t, err) + encode := arkscript.EncodeStandardVTXOTemplate + request.ClientDeliveryScript, err = encode( + clientKey.PubKey(), next.PubKey(), + terms.VTXO.MinExitDelay, + ) + require.NoError(t, err) + request.HubDeliveryScript, err = encode( + hubKey.PubKey(), next.PubKey(), terms.VTXO.MinExitDelay, + ) + require.NoError(t, err) + } + _, _, err = coordinator.Apply( + t.Context(), terms.ID, &arkchannel.RequestCooperativeClose{ + Request: request, + }, + ) + require.NoError(t, err) + template, err := arkchannel.NewCooperativeCloseTemplate( + terms, binding, request, 70_000, 30_000, 9, + ) + require.NoError(t, err) + hubSig := testArkChannelCloseSignature( + t, template, terms, arkchannel.PartyHub, hubKey, + ) + arkDesc, err := template.ArkSignDescriptor( + terms, arkchannel.PartyHub, keychain.KeyDescriptor{ + PubKey: hubKey.PubKey(), + }, + ) + require.NoError(t, err) + hubArkSig, err := input.NewMockSigner( + []*btcec.PrivateKey{hubKey}, nil, + ).SignOutputRaw(template.ArkTransaction(), arkDesc) + require.NoError(t, err) + settlement, err := template.Complete( + terms, binding, request, hubSig, hubArkSig, + ) + require.NoError(t, err) + for _, event := range []arkchannel.Event{ + &arkchannel.CooperativeCloseSigned{ + Close: settlement, + }, + &arkchannel.CooperativeCloseReady{ + Receipt: settlement.AuthorizationReceipt(), + }, + &arkchannel.CooperativeClosePublished{ + TxID: settlement.TxID, + }, + } { + _, _, err = coordinator.Apply(t.Context(), terms.ID, event) + require.NoError(t, err) + } + + loaded, err := store.Get(t.Context(), terms.ID) + require.NoError(t, err) + require.Equal( + t, arkchannel.PhaseCoopClosePublished, loaded.Snapshot.Phase, + ) + require.Equal(t, request, *loaded.Snapshot.CooperativeCloseRequest) + require.Equal(t, settlement, *loaded.Snapshot.CooperativeClose) + + _, _, err = coordinator.Apply( + t.Context(), terms.ID, &arkchannel.CooperativeCloseFinalized{}, + ) + require.NoError(t, err) + loaded, err = store.Get(t.Context(), terms.ID) + require.NoError(t, err) + require.Equal(t, arkchannel.PhaseClosed, loaded.Snapshot.Phase) + records, err := store.ListNonTerminal(t.Context()) + require.NoError(t, err) + require.Len(t, records, 1) + require.Equal(t, terms.ID, records[0].Snapshot.Terms.ID) +} + +// TestArkChannelStoreNotFound verifies the shared coordinator sentinel. +func TestArkChannelStoreNotFound(t *testing.T) { + t.Parallel() + + store := newArkChannelStoreForTest(t) + _, err := store.Get(t.Context(), arkchannel.ID{99}) + require.ErrorIs(t, err, arkchannel.ErrNotFound) + _, err = store.GetByChannelPoint( + t.Context(), wire.OutPoint{ + Hash: chainhash.Hash{99}, + }, + ) + require.ErrorIs(t, err, arkchannel.ErrNotFound) +} + +// TestArkChannelStoreOwnerScope pins reads, writes and uniqueness to the +// shared SQL database rather than the set of online peers. +func TestArkChannelStoreOwnerScope(t *testing.T) { + t.Parallel() + store := newArkChannelStoreForTest(t) + a := testArkChannelTerms(t, arkchannel.KindPromotion, 1) + b := testArkChannelTerms(t, arkchannel.KindPromotion, 2) + alice, bob := store.ForPeer(a.ClientNodeKey), store.ForPeer( + b.ClientNodeKey, + ) + state, err := arkchannel.NewState(a) + require.NoError(t, err) + record, err := alice.Create(t.Context(), state.Snapshot()) + require.NoError(t, err) + _, err = bob.Create(t.Context(), state.Snapshot()) + require.ErrorIs(t, err, arkchannel.ErrNotFound) + _, err = bob.Get(t.Context(), a.ID) + require.ErrorIs(t, err, arkchannel.ErrNotFound) + _, err = bob.GetByPendingChannelID(t.Context(), a.PendingChannelID) + require.ErrorIs(t, err, arkchannel.ErrNotFound) + _, err = bob.GetBySCID(t.Context(), a.ReservedSCID) + require.ErrorIs(t, err, arkchannel.ErrNotFound) + known, err := alice.GetBySCID(t.Context(), a.ReservedSCID) + require.NoError(t, err) + require.Equal(t, a.ID, known.Snapshot.Terms.ID) + records, err := bob.ListNonTerminal(t.Context()) + require.NoError(t, err) + require.Empty(t, records) + forged := record.Snapshot.Clone() + forged.Terms.ClientNodeKey = b.ClientNodeKey + _, err = bob.CompareAndSwap(t.Context(), a.ID, record.Revision, forged) + require.Error(t, err) + got, err := alice.Get(t.Context(), a.ID) + require.NoError(t, err) + require.Equal(t, record.Revision, got.Revision) + for _, duplicate := range []string{"scid", "pending"} { + terms := b + if duplicate == "scid" { + terms.ReservedSCID = a.ReservedSCID + } else { + terms.PendingChannelID = a.PendingChannelID + } + other, err := arkchannel.NewState(terms) + require.NoError(t, err) + _, err = bob.Create(t.Context(), other.Snapshot()) + require.Error(t, err) + } +} + +// newArkChannelStoreForTest creates a migrated SQL-backed channel store. +func newArkChannelStoreForTest(t *testing.T) *ArkChannelStoreDB { + t.Helper() + + raw := NewTestDB(t) + store := NewStore( + raw.DB, raw.Queries, raw.Backend(), btclog.Disabled, + ) + + return NewArkChannelStore(store, clock.NewDefaultClock()) +} + +// testArkChannelTerms creates valid immutable SQL fixtures. +func testArkChannelTerms(t *testing.T, kind arkchannel.Kind, + seed byte) arkchannel.Terms { + + t.Helper() + clientKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + hubKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + newPolicyKey := func(role byte) [33]byte { + key := testArkChannelPolicyKey(seed, role) + var serialized [33]byte + copy(serialized[:], key.PubKey().SerializeCompressed()) + + return serialized + } + + var clientNodeKey, hubNodeKey [33]byte + copy(clientNodeKey[:], clientKey.PubKey().SerializeCompressed()) + copy(hubNodeKey[:], hubKey.PubKey().SerializeCompressed()) + + terms := arkchannel.Terms{ + ID: arkchannel.ID{ + seed, + 1, + }, + Kind: kind, + Funder: arkchannel.PartyClient, + PendingChannelID: [32]byte{ + seed, + 2, + }, + Capacity: btcutil.Amount(100_000), + ReservedSCID: lnwire.ShortChannelID{ + BlockHeight: 16_000_000 + uint32(seed), + TxIndex: uint32(seed), + }.ToUint64(), + ClientNodeKey: clientNodeKey, + HubNodeKey: hubNodeKey, + VTXO: arkchannel.VTXOTerms{ + ClientArkKey: newPolicyKey(1), + HubArkKey: newPolicyKey(2), + ArkOperatorKey: newPolicyKey(3), + ClientChannelKey: newPolicyKey(4), + HubChannelKey: newPolicyKey(5), + FunderKey: newPolicyKey(6), + ChannelDelay: 144, + FunderDelay: 576, + MinExitDelay: 144, + }, + } + + return terms +} + +// testArkChannelPolicyKey returns a deterministic policy key for one SQL +// fixture role. +func testArkChannelPolicyKey(seed, role byte) *btcec.PrivateKey { + keyBytes := bytes.Repeat([]byte{role}, 32) + keyBytes[0] ^= seed + key, _ := btcec.PrivKeyFromBytes(keyBytes) + + return key +} + +// testArkChannelBinding creates an exact VTXO binding fixture. +func testArkChannelBinding(terms arkchannel.Terms) arkchannel.VTXOBinding { + policy, pkScript, err := terms.VTXO.Artifacts() + if err != nil { + panic(err) + } + + amount := terms.Capacity + 1_000 + tx := wire.NewMsgTx(2) + tx.AddTxIn(&wire.TxIn{ + PreviousOutPoint: wire.OutPoint{ + Hash: chainhash.Hash{terms.ID[0], 5}, + }, + }) + for i := 0; i < 3; i++ { + tx.AddTxOut(&wire.TxOut{ + Value: int64(i + 1), + PkScript: []byte{0x51}, + }) + } + tx.AddTxOut(&wire.TxOut{ + Value: int64(amount), + PkScript: pkScript, + }) + var arkTransaction bytes.Buffer + if err := tx.Serialize(&arkTransaction); err != nil { + panic(err) + } + sessionID := [32]byte(tx.TxHash()) + + return arkchannel.VTXOBinding{ + OORSessionID: sessionID, + OutPoint: wire.OutPoint{ + Hash: chainhash.Hash(sessionID), + Index: 3, + }, + Amount: amount, + ArkTransaction: arkTransaction.Bytes(), + PolicyTemplate: policy, + PkScript: pkScript, + } +} + +// testArkChannelBacking creates a signed funding transaction fixture. +func testArkChannelBacking(t *testing.T, terms arkchannel.Terms, + binding arkchannel.VTXOBinding) arkchannel.Backing { + + t.Helper() + packet, err := psbt.New(nil, []*wire.TxOut{{ + Value: int64(terms.Capacity), + PkScript: []byte{0x51, 0x20, 7}, + }}, 2, 0, nil) + require.NoError(t, err) + template, err := arkchannel.NewBackingTemplate(packet, terms, binding) + require.NoError(t, err) + clientSig := testArkChannelBackingSignature( + t, template, terms, arkchannel.PartyClient, + testArkChannelPolicyKey(terms.ID[0], 4), + ) + hubSig := testArkChannelBackingSignature( + t, template, terms, arkchannel.PartyHub, + testArkChannelPolicyKey(terms.ID[0], 5), + ) + backing, err := template.Complete( + terms, binding, clientSig, hubSig, + ) + require.NoError(t, err) + + return backing +} + +// testArkChannelBackingSignature signs one endpoint's backing branch. +func testArkChannelBackingSignature(t *testing.T, + template *arkchannel.BackingTemplate, terms arkchannel.Terms, + party arkchannel.Party, key *btcec.PrivateKey) input.Signature { + + t.Helper() + desc, err := template.SignDescriptor( + terms, party, keychain.KeyDescriptor{ + PubKey: key.PubKey(), + }, + ) + require.NoError(t, err) + sig, err := input.NewMockSigner( + []*btcec.PrivateKey{key}, nil, + ).SignOutputRaw(template.Packet().UnsignedTx, desc) + require.NoError(t, err) + + return sig +} + +// testArkChannelCompressedKey encodes one policy key. +func testArkChannelCompressedKey(key *btcec.PrivateKey) [33]byte { + var encoded [33]byte + copy(encoded[:], key.PubKey().SerializeCompressed()) + + return encoded +} + +// testArkChannelCloseSignature signs one endpoint's immediate VTXO role. +func testArkChannelCloseSignature(t *testing.T, + template *arkchannel.CooperativeCloseTemplate, terms arkchannel.Terms, + party arkchannel.Party, key *btcec.PrivateKey) input.Signature { + + t.Helper() + desc, err := template.SignDescriptor( + terms, party, keychain.KeyDescriptor{ + PubKey: key.PubKey(), + }, + ) + require.NoError(t, err) + sig, err := input.NewMockSigner( + []*btcec.PrivateKey{key}, nil, + ).SignOutputRaw( + testArkChannelProposalTx(t, template.Proposal()), desc, + ) + require.NoError(t, err) + + return sig +} + +// testArkChannelProposalTx decodes one unsigned OOR checkpoint proposal. +func testArkChannelProposalTx(t *testing.T, + proposal arkchannel.CooperativeCloseProposal) *wire.MsgTx { + + t.Helper() + packet, err := psbtutil.Parse(proposal.Transaction) + require.NoError(t, err) + + return packet.UnsignedTx +} diff --git a/db/store.go b/db/store.go index 1524da573..4d919551b 100644 --- a/db/store.go +++ b/db/store.go @@ -378,3 +378,8 @@ func (s *Store) NewOORSessionRegistryStore( return NewOORSessionRegistryStore(s, clk) } + +// NewArkChannelStore builds the durable Ark-to-lnd coordination store. +func (s *Store) NewArkChannelStore(clk clock.Clock) *ArkChannelStoreDB { + return NewArkChannelStore(s, clk) +} From 7d2b7d56786f3505b716691277b4370011b9235b Mon Sep 17 00:00:00 2001 From: sputn1ck Date: Wed, 18 Nov 2026 18:51:19 +0100 Subject: [PATCH 7/7] arkchannel: Connect prepared funding and on-chain recovery Reconcile funding reservations with durable OOR ownership and hand confirmed source conflicts to the recovery controller. --- arkchannel/oorbridge/controller.go | 699 +++++++++++++++ .../oorbridge/controller_lifetime_test.go | 339 ++++++++ arkchannel/oorbridge/controller_test.go | 817 ++++++++++++++++++ arkchannel/oorbridge/preparer.go | 390 +++++++++ arkchannel/unrollbridge/controller.go | 353 ++++++++ arkchannel/unrollbridge/controller_test.go | 406 +++++++++ 6 files changed, 3004 insertions(+) create mode 100644 arkchannel/oorbridge/controller.go create mode 100644 arkchannel/oorbridge/controller_lifetime_test.go create mode 100644 arkchannel/oorbridge/controller_test.go create mode 100644 arkchannel/oorbridge/preparer.go create mode 100644 arkchannel/unrollbridge/controller.go create mode 100644 arkchannel/unrollbridge/controller_test.go diff --git a/arkchannel/oorbridge/controller.go b/arkchannel/oorbridge/controller.go new file mode 100644 index 000000000..c5a38574b --- /dev/null +++ b/arkchannel/oorbridge/controller.go @@ -0,0 +1,699 @@ +// Package oorbridge connects Ark channel actions to the durable OOR actor. +package oorbridge + +import ( + "bytes" + "context" + "encoding/hex" + "errors" + "fmt" + "slices" + "sync" + "time" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/baselib/actor" + "github.com/lightninglabs/wavelength/lib/arkscript" + "github.com/lightninglabs/wavelength/lib/tx/psbtutil" + "github.com/lightninglabs/wavelength/oor" + "github.com/lightninglabs/wavelength/vtxo" + "github.com/lightningnetwork/lnd/keychain" +) + +const defaultPollInterval = 50 * time.Millisecond + +var ( + // ErrOORPostPONRFailure means the OOR source is no longer safe to + // release, but the channel-policy output has not been proven to exist. + // The channel must remain at its commit gate for explicit recovery or + // intervention. + ErrOORPostPONRFailure = errors.New("channel OOR failed after point " + + "of no return") +) + +// TerminalResult is the authoritative terminal classification of a prepared +// channel OOR. Exactly one of Finalized and Aborted is true. +type TerminalResult struct { + Finalized bool + Aborted bool + Reason string +} + +// Validate rejects ambiguous or contradictory terminal classifications. +func (r TerminalResult) Validate() error { + if r.Finalized == r.Aborted { + return fmt.Errorf("OOR terminal result must be exactly one " + + "of finalized or aborted") + } + if r.Aborted && r.Reason == "" { + return fmt.Errorf("aborted OOR terminal result requires a " + + "reason") + } + if r.Finalized && r.Reason != "" { + return fmt.Errorf("finalized OOR terminal result cannot have " + + "an abort reason") + } + + return nil +} + +// PreparedSourceValidator checks the exact transfer before it is signed. +// Only ErrSourceInadmissible permits a definitive abort. +type PreparedSourceValidator func(context.Context, arkchannel.Terms, + arkchannel.VTXOBinding, *oor.Prepared) error + +// Controller drives the durable OOR actor and reports its terminal result back +// to the channel FSM. +type Controller struct { + ref actor.ActorRef[oor.OORDurableMsg, oor.ActorResp] + + pollInterval time.Duration + + mu sync.RWMutex + sink arkchannel.ChannelEventSink + + sourceValidator PreparedSourceValidator +} + +// New resolves the durable OOR registry from an actor system. +func New(system actor.SystemContext) (*Controller, error) { + if system == nil { + return nil, fmt.Errorf("actor system is required") + } + + return NewWithRef(oor.NewServiceKey().Ref(system)) +} + +// NewWithRef constructs a controller from an explicit actor reference. It is +// useful for runtimes that already resolved the service. +func NewWithRef(ref actor.ActorRef[oor.OORDurableMsg, oor.ActorResp]) ( + *Controller, error) { + + if ref == nil { + return nil, fmt.Errorf("OOR actor reference is required") + } + + return &Controller{ + ref: ref, + pollInterval: defaultPollInterval, + }, nil +} + +// SetPreparedSourceValidator binds the daemon's read-only admission check. +func (c *Controller) SetPreparedSourceValidator( + validate PreparedSourceValidator) { + + c.mu.Lock() + defer c.mu.Unlock() + + c.sourceValidator = validate +} + +// validatePreparedSource checks only new signing admission, never recovery of +// an OOR whose commit already crossed the prepared gate. +func (c *Controller) validatePreparedSource(ctx context.Context, + terms arkchannel.Terms, source arkchannel.VTXOBinding, + prepared *oor.Prepared) error { + + c.mu.RLock() + validate := c.sourceValidator + c.mu.RUnlock() + if validate == nil { + return nil + } + + return validate(ctx, terms, source, prepared) +} + +// BindChannelEventSink connects terminal OOR observations to the channel FSM. +func (c *Controller) BindChannelEventSink( + sink arkchannel.ChannelEventSink) error { + + if sink == nil { + return fmt.Errorf("channel event sink is required") + } + + c.mu.Lock() + defer c.mu.Unlock() + + if c.sink != nil { + return nil + } + c.sink = sink + + return nil +} + +// ValidatePreparedOOR proves that the bound output exists in the exact +// deterministic OOR package and carries the expected channel policy metadata. +func (c *Controller) ValidatePreparedOOR(ctx context.Context, + terms arkchannel.Terms, source arkchannel.VTXOBinding) error { + + if err := source.Validate(terms); err != nil { + return err + } + state, err := c.state(ctx, source.OORSessionID) + if err != nil { + return err + } + prepared, ok := state.(*oor.Prepared) + if !ok { + return fmt.Errorf("OOR session is %T, expected prepared", state) + } + recipients, err := oor.ExtractArkRecipients(prepared.ArkPSBT) + if err != nil { + return fmt.Errorf("extract prepared OOR outputs: %w", err) + } + + for _, recipient := range recipients { + if recipient.OutputIndex != source.OutPoint.Index { + continue + } + if recipient.Value != source.Amount || + !bytes.Equal(recipient.PkScript, source.PkScript) { + return fmt.Errorf("prepared OOR output does not " + + "match binding") + } + for _, declared := range prepared.RecipientOutputs { + if declared.Value != source.Amount || + !bytes.Equal( + declared.PkScript, source.PkScript, + ) { + + continue + } + if !bytes.Equal( + declared.VTXOPolicyTemplate, + source.PolicyTemplate, + ) { + return fmt.Errorf("prepared OOR policy does " + + "not match binding") + } + + return nil + } + + return fmt.Errorf("prepared OOR output has no channel policy") + } + + return fmt.Errorf("prepared OOR output index %d is missing", + source.OutPoint.Index) +} + +// CommitPreparedOOR crosses the OOR signing gate and waits for a durable +// terminal result before advancing the channel FSM. +func (c *Controller) CommitPreparedOOR(ctx context.Context, id arkchannel.ID, + terms arkchannel.Terms, source arkchannel.VTXOBinding) error { + + result, err := c.CommitPreparedOORResult(ctx, id, terms, source) + if err != nil { + return err + } + _, err = c.applyTerminalResult(ctx, id, source, result) + + return err +} + +// CommitPreparedOORResult commits when the session is still prepared, or +// reconciles a prior/lost control response to one authoritative outcome. +func (c *Controller) CommitPreparedOORResult(ctx context.Context, + id arkchannel.ID, terms arkchannel.Terms, + source arkchannel.VTXOBinding) (TerminalResult, error) { + + if err := source.Validate(terms); err != nil { + return TerminalResult{}, err + } + + return c.controlPreparedOOR( + ctx, terms, source, &oor.CommitPreparedEvent{}, + ) +} + +// controlPreparedOOR submits a control event only while the OOR is still at +// its prepared gate. Replays after either side won the gate only observe the +// actor's durable terminal state. +func (c *Controller) controlPreparedOOR(ctx context.Context, + terms arkchannel.Terms, source arkchannel.VTXOBinding, + event oor.Event) (TerminalResult, error) { + + state, err := c.state(ctx, source.OORSessionID) + if err != nil { + return TerminalResult{}, err + } + if result, terminal, err := terminalResult(state); err != nil { + return TerminalResult{}, err + } else if terminal { + return result, nil + } + + prepared, ok := state.(*oor.Prepared) + if !ok { + return c.waitForTerminal(ctx, source) + } + if _, committing := event.(*oor.CommitPreparedEvent); committing { + if err := c.validatePreparedSource( + ctx, terms, source, prepared, + ); err != nil { + + if !errors.Is(err, arkchannel.ErrSourceInadmissible) { + + // Preserve the prepared transfer for retry when + // the validator could not reach a decision. + return TerminalResult{}, err + } + + // Rejection must durably release the prepared source + // instead of wedging the channel's commit gate. A + // concurrent commit still wins normally. + event = &oor.AbortPreparedEvent{ + Reason: fmt.Sprintf( + "channel OOR source lifetime: %v", err, + ), + } + } + } + driveErr := c.drive(ctx, source, event) + if driveErr != nil { + // A concurrent control event can advance the state before this + // request observes its response. Re-read before deciding that + // the control failed. + state, err = c.state(ctx, source.OORSessionID) + if err != nil { + return TerminalResult{}, fmt.Errorf("drive OOR "+ + "session: %v; reconcile state: %w", driveErr, + err) + } + _, stillPrepared := state.(*oor.Prepared) + if stillPrepared { + return TerminalResult{}, driveErr + } + result, terminal, terminalErr := terminalResult(state) + if terminalErr != nil { + return TerminalResult{}, terminalErr + } + if terminal { + return result, nil + } + } + + return c.waitForTerminal(ctx, source) +} + +// SettleCooperativeClose spends the channel-policy VTXO through its no-delay +// 3-of-3 path in the ordinary durable OOR protocol. The Ark operator signs the +// checkpoint before the local actor adds the client's signature; the hub's +// pre-authorized signature is supplied as external witness material. +func (c *Controller) SettleCooperativeClose(ctx context.Context, + id arkchannel.ID, terms arkchannel.Terms, source arkchannel.VTXOBinding, + request arkchannel.CooperativeCloseRequest, + settlement arkchannel.CooperativeClose, + clientKey keychain.KeyDescriptor, + lookup func(context.Context, arkchannel.ID) ([]byte, error)) error { + + if id != terms.ID { + return fmt.Errorf("cooperative close channel ID does not match") + } + if err := settlement.Validate(terms, source, request); err != nil { + return err + } + template, err := arkchannel.NewCooperativeCloseTemplate( + terms, source, request, settlement.Proposal.ClientBalance, + settlement.Proposal.HubBalance, + settlement.Proposal.CommitmentHeight, + ) + if err != nil { + return err + } + spec, err := template.OORSpec() + if err != nil { + return err + } + spendPath, err := arkscript.DecodeSpendPath(spec.SpendPath) + if err != nil { + return fmt.Errorf("decode cooperative close spend path: %w", + err) + } + clientPolicyKey, err := btcec.ParsePubKey( + terms.VTXO.ClientArkKey[:], + ) + if err != nil { + return fmt.Errorf("parse client Ark key: %w", err) + } + if clientKey.PubKey == nil || + !clientKey.PubKey.IsEqual(clientPolicyKey) { + return fmt.Errorf("cooperative close client key does not match") + } + operatorKey, err := btcec.ParsePubKey(terms.VTXO.ArkOperatorKey[:]) + if err != nil { + return fmt.Errorf("parse Ark operator key: %w", err) + } + hubKey, err := btcec.ParsePubKey(terms.VTXO.HubArkKey[:]) + if err != nil { + return fmt.Errorf("parse hub Ark key: %w", err) + } + transferInput := oor.TransferInput{ + OwnerLeafScript: slices.Clone(spec.OwnerLeafScript), + OwnerLeafPolicy: slices.Clone(spec.OwnerLeafPolicy), + VTXO: &vtxo.Descriptor{ + Outpoint: source.OutPoint, Amount: source.Amount, + PolicyTemplate: slices.Clone(source.PolicyTemplate), + PkScript: slices.Clone(source.PkScript), + ClientKey: clientKey, + OperatorKey: operatorKey, + RelativeExpiry: terms.VTXO.MinExitDelay, + }, + VTXOPolicyTemplate: slices.Clone(source.PolicyTemplate), + CustomSpend: spendPath, + } + checkpointSig, arkSig, err := settlement.Signatures() + if err != nil { + return err + } + transferInput.ExternalSignatures = []oor.ExternalTaprootScriptSignature{ + { + PubKey: hubKey, + WitnessScript: slices.Clone(spendPath.WitnessScript), + Signature: checkpointSig.Serialize(), + SigHash: txscript.SigHashDefault, + }, + } + transferInput.ExternalArkSignatures = append( + transferInput.ExternalArkSignatures, + oor.ExternalTaprootScriptSignature{ + PubKey: hubKey, + WitnessScript: slices.Clone(spec.OwnerLeafScript), + Signature: arkSig.Serialize(), + SigHash: txscript.SigHashDefault, + }, + ) + if err := transferInput.Validate(); err != nil { + return fmt.Errorf("validate cooperative close OOR input: %w", + err) + } + + idempotencyKey := "ark-channel-close:" + hex.EncodeToString(id[:]) + result := c.ref.Ask(actor.WithoutTx(ctx), &oor.StartTransferRequest{ + Policy: spec.CheckpointPolicy, + Inputs: []oor.TransferInput{transferInput}, + Recipients: spec.Recipients, + IdempotencyKey: idempotencyKey, + PrepareOnly: true, + }).Await(ctx) + response, err := result.Unpack() + if err != nil { + return fmt.Errorf("start cooperative close OOR: %w", err) + } + started, ok := response.(*oor.StartTransferResponse) + if !ok { + return fmt.Errorf("unexpected cooperative close OOR "+ + "response %T", response) + } + if [32]byte(started.SessionID) != settlement.TxID { + return fmt.Errorf("cooperative close OOR session ID changed") + } + state, err := c.state(ctx, [32]byte(started.SessionID)) + if err != nil { + return err + } + if prepared, ok := state.(*oor.Prepared); ok { + if len(prepared.CheckpointPSBTs) != 1 { + return fmt.Errorf("cooperative close OOR has %d "+ + "checkpoints, expected one", + len(prepared.CheckpointPSBTs)) + } + checkpoint, err := psbtutil.Serialize( + prepared.CheckpointPSBTs[0], + ) + if err != nil { + return fmt.Errorf("serialize prepared cooperative "+ + "close: %w", err) + } + if !bytes.Equal(checkpoint, settlement.Proposal.Transaction) { + return fmt.Errorf("prepared cooperative close " + + "checkpoint does not match hub authorization") + } + // CommitPrepared releases the first client signature request. + // A hub signature is not proof of current wallet registration. + // A committed session, however, must resume its exact package. + if lookup == nil { + return fmt.Errorf("client refresh registration missing") + } + current, err := lookup(ctx, id) + if err != nil { + return fmt.Errorf("register client refresh: %w", err) + } + if !bytes.Equal(current, request.ClientDeliveryScript) { + return fmt.Errorf("client refresh policy changed " + + "since quote") + } + if err := c.driveSession( + ctx, [32]byte(started.SessionID), + &oor.CommitPreparedEvent{}, + ); err != nil { + return err + } + } + + return c.waitForOORCompletion(ctx, [32]byte(started.SessionID)) +} + +// AbortPreparedOOR aborts only a pre-PONR transfer and waits until that fact is +// durable before allowing lnd funding cancellation. +func (c *Controller) AbortPreparedOOR(ctx context.Context, id arkchannel.ID, + terms arkchannel.Terms, source arkchannel.VTXOBinding, + reason string) error { + + result, err := c.AbortPreparedOORResult( + ctx, id, terms, source, reason, + ) + if err != nil { + return err + } + _, err = c.applyTerminalResult(ctx, id, source, result) + + return err +} + +// AbortPreparedOORResult aborts only while the session is prepared. If commit +// already won, it waits for and returns the finalized result instead of +// misclassifying the source as releasable. +func (c *Controller) AbortPreparedOORResult(ctx context.Context, + id arkchannel.ID, terms arkchannel.Terms, source arkchannel.VTXOBinding, + reason string) (TerminalResult, error) { + + if err := source.Validate(terms); err != nil { + return TerminalResult{}, err + } + if reason == "" { + return TerminalResult{}, fmt.Errorf("OOR abort reason is " + + "required") + } + + return c.controlPreparedOOR( + ctx, terms, source, &oor.AbortPreparedEvent{ + Reason: reason, + }, + ) +} + +// drive records one durable control event in the exact OOR session. +func (c *Controller) drive(ctx context.Context, source arkchannel.VTXOBinding, + event oor.Event) error { + + return c.driveSession(ctx, source.OORSessionID, event) +} + +// driveSession records one durable control event in the named OOR session. +func (c *Controller) driveSession(ctx context.Context, sessionID [32]byte, + event oor.Event) error { + + result := c.ref.Ask(actor.WithoutTx(ctx), &oor.DriveEventRequest{ + SessionID: oor.SessionID(sessionID), + Event: event, + }).Await(ctx) + response, err := result.Unpack() + if err != nil { + return fmt.Errorf("drive OOR session: %w", err) + } + if _, ok := response.(*oor.DriveEventResponse); !ok { + return fmt.Errorf("unexpected OOR drive response %T", response) + } + + return nil +} + +// waitForTerminal observes the OOR actor until it can produce an authoritative +// source result without requiring a channel-event sink. A post-PONR failure +// remains unresolved because it proves neither a releasable source nor a +// materialized channel-policy output. +func (c *Controller) waitForTerminal(ctx context.Context, + source arkchannel.VTXOBinding) (TerminalResult, error) { + + for { + state, err := c.state(ctx, source.OORSessionID) + if err != nil { + return TerminalResult{}, err + } + if result, terminal, err := terminalResult(state); err != nil { + return TerminalResult{}, err + } else if terminal { + return result, nil + } + + timer := time.NewTimer(c.pollInterval) + select { + case <-ctx.Done(): + if !timer.Stop() { + <-timer.C + } + + return TerminalResult{}, ctx.Err() + + case <-timer.C: + } + } +} + +// terminalResult maps only proven OOR outcomes onto channel source facts. +// Post-PONR failure remains an error so it cannot activate an unfunded channel. +func terminalResult(state oor.SessionState) (TerminalResult, bool, error) { + switch state := state.(type) { + case *oor.Completed: + return TerminalResult{Finalized: true}, true, nil + + case *oor.Failed: + if state.PrePONR { + reason := state.Reason + if reason == "" { + reason = "OOR failed before point of no return" + } + + return TerminalResult{ + Aborted: true, Reason: reason, + }, true, nil + } + + return TerminalResult{}, true, fmt.Errorf("%w: %s", + ErrOORPostPONRFailure, state.Reason) + + case oor.ReceiveState: + // An incoming self-transfer for the same Ark txid can only + // exist after the operator finalized the outgoing package. Its + // row may replace the reaped outgoing row before this observer + // polls it. + return TerminalResult{Finalized: true}, true, nil + + default: + return TerminalResult{}, false, nil + } +} + +// applyTerminalResult records exactly one terminal OOR fact in the channel +// sink before returning that same classification to the caller. +func (c *Controller) applyTerminalResult(ctx context.Context, id arkchannel.ID, + source arkchannel.VTXOBinding, result TerminalResult) (TerminalResult, + error) { + + if err := result.Validate(); err != nil { + return TerminalResult{}, err + } + var event arkchannel.Event + if result.Finalized { + event = &arkchannel.OORFinalized{ + SessionID: source.OORSessionID, + } + } else { + event = &arkchannel.OORAborted{ + SessionID: source.OORSessionID, + Reason: result.Reason, + } + } + if err := c.apply(ctx, id, event); err != nil { + return TerminalResult{}, err + } + + return result, nil +} + +// waitForOORCompletion observes a cooperative-close OOR without emitting the +// channel-creation OORFinalized event used by prepared funding sessions. +func (c *Controller) waitForOORCompletion(ctx context.Context, + sessionID [32]byte) error { + + for { + state, err := c.state(ctx, sessionID) + if err != nil { + return err + } + + switch state := state.(type) { + case *oor.Completed: + return nil + + case *oor.Failed: + return fmt.Errorf("cooperative close OOR failed: %s", + state.Reason) + + case oor.ReceiveState: + // The sender can also own one replacement output. Its + // incoming row may replace the completed outgoing row. + return nil + } + + timer := time.NewTimer(c.pollInterval) + select { + case <-ctx.Done(): + if !timer.Stop() { + <-timer.C + } + + return ctx.Err() + + case <-timer.C: + } + } +} + +// state loads the authoritative state through the durable OOR registry. +func (c *Controller) state(ctx context.Context, sessionID [32]byte) ( + oor.SessionState, error) { + + result := c.ref.Ask(actor.WithoutTx(ctx), &oor.GetStateRequest{ + SessionID: oor.SessionID(sessionID), + }).Await(ctx) + response, err := result.Unpack() + if err != nil { + return nil, fmt.Errorf("get OOR session state: %w", err) + } + state, ok := response.(*oor.GetStateResponse) + if !ok { + return nil, fmt.Errorf("unexpected OOR state response %T", + response) + } + if state.State == nil { + return nil, fmt.Errorf("OOR session returned an empty state") + } + + return state.State, nil +} + +// apply records one OOR terminal observation through the bound channel service. +func (c *Controller) apply(ctx context.Context, id arkchannel.ID, + event arkchannel.Event) error { + + c.mu.RLock() + sink := c.sink + c.mu.RUnlock() + if sink == nil { + return fmt.Errorf("channel event sink is not bound") + } + + _, err := sink.ApplyLocalEvent(ctx, id, event) + + return err +} + +var _ arkchannel.OORTransferController = (*Controller)(nil) +var _ arkchannel.ChannelEventSinkBinder = (*Controller)(nil) diff --git a/arkchannel/oorbridge/controller_lifetime_test.go b/arkchannel/oorbridge/controller_lifetime_test.go new file mode 100644 index 000000000..1f24c4d36 --- /dev/null +++ b/arkchannel/oorbridge/controller_lifetime_test.go @@ -0,0 +1,339 @@ +package oorbridge + +import ( + "context" + "fmt" + "testing" + + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/baselib/actor" + "github.com/lightninglabs/wavelength/oor" + "github.com/stretchr/testify/require" +) + +// TestSourceLifetimeCommitGate validates the durable selected inputs at the +// signing gate and turns rejection into a proven, replayable pre-PONR abort. +func TestSourceLifetimeCommitGate(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + offset int32 + expiry int32 + backendFail bool + aborted bool + }{ + { + name: "fresh", + expiry: 2000, + offset: -1, + }, + { + name: "deadline", + expiry: 2000, + aborted: true, + }, + { + name: "stale", expiry: 2000, offset: 1, + aborted: true, + }, + { + name: "missing expiry", + aborted: true, + }, + { + name: "backend unavailable", expiry: 2000, offset: -1, + backendFail: true, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + terms, source, prepared, _, _ := preparedChannelBinding( + t, + ) + input := prepared.TransferInputs[0].VTXO + input.BatchExpiry = test.expiry + deadline, err := arkchannel.SourceMaterializationHeight( + 2000, terms.VTXO.FunderDelay, + ) + require.NoError(t, err) + ref := &controllerTestRef{state: prepared} + controller, err := NewWithRef(ref) + require.NoError(t, err) + checks := 0 + controller.SetPreparedSourceValidator(func( + ctx context.Context, gotTerms arkchannel.Terms, + gotSource arkchannel.VTXOBinding, + state *oor.Prepared) error { + + checks++ + require.Equal(t, t.Context(), ctx) + require.Equal(t, terms, gotTerms) + require.Equal( + t, prepared, state, + ) + require.Equal(t, source, gotSource) + if test.backendFail && checks == 1 { + return fmt.Errorf("best block " + + "unavailable") + } + + vtxo := state.TransferInputs[0].VTXO + + return arkchannel.ValidateSourceLifetime( + vtxo.BatchExpiry, deadline+test.offset, + gotTerms.VTXO.FunderDelay, + ) + }) + + commit := controller.CommitPreparedOORResult + result, err := commit( + t.Context(), terms.ID, terms, source, + ) + if test.backendFail { + require.ErrorContains(t, err, "best block") + require.Nil(t, ref.driveEvent) + require.Same(t, prepared, ref.state) + result, err = commit( + t.Context(), terms.ID, terms, source, + ) + } + require.NoError(t, err) + require.NoError(t, result.Validate()) + require.Equal(t, test.aborted, result.Aborted) + require.Equal(t, !test.aborted, result.Finalized) + if test.aborted { + event := ref.driveEvent + abort, ok := event.(*oor.AbortPreparedEvent) + require.True(t, ok) + require.Equal(t, abort.Reason, result.Reason) + require.Contains( + t, result.Reason, "source lifetime", + ) + } else { + require.IsType( + t, &oor.CommitPreparedEvent{}, + ref.driveEvent, + ) + } + + replayed, err := controller.CommitPreparedOORResult( + t.Context(), terms.ID, terms, source, + ) + require.NoError(t, err) + require.Equal(t, result, replayed) + if test.backendFail { + require.Equal(t, 2, checks) + } else { + require.Equal(t, 1, checks) + } + }) + } +} + +// TestSourceLifetimeAbortReconciliation refuses to report an abort without +// durable proof and preserves a concurrent commit's authoritative outcome. +func TestSourceLifetimeAbortReconciliation(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + next oor.SessionState + finalized bool + failed bool + }{ + { + name: "concurrent commit", next: &oor.Completed{}, + finalized: true, + }, + { + name: "lost abort response", + next: &oor.Failed{ + PrePONR: true, + Reason: "source expired", + }, + }, + { + name: "abort not persisted", + failed: true, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + terms, source, prepared, _, _ := preparedChannelBinding( + t, + ) + next := test.next + if next == nil { + next = prepared + } + ref := &controllerTestRef{ + state: prepared, stateAfterDrive: next, + driveErr: fmt.Errorf("lost control response"), + } + controller, err := NewWithRef(ref) + require.NoError(t, err) + controller.SetPreparedSourceValidator( + func(context.Context, arkchannel.Terms, + arkchannel.VTXOBinding, + *oor.Prepared) error { + + return arkchannel.ErrSourceInadmissible + }, + ) + + result, err := controller.CommitPreparedOORResult( + t.Context(), terms.ID, terms, source, + ) + require.IsType( + t, &oor.AbortPreparedEvent{}, ref.driveEvent, + ) + if test.failed { + require.ErrorContains( + t, err, "lost control response", + ) + require.Zero(t, result) + + return + } + + require.NoError(t, err) + require.NoError(t, result.Validate()) + require.Equal(t, test.finalized, result.Finalized) + require.Equal(t, !test.finalized, result.Aborted) + }) + } +} + +// lifetimeReplayRef advances an already committed session on the next read +// without sending a new signing or abort control event. +type lifetimeReplayRef struct { + controllerTestRef + reads int +} + +// Ask lets the controller observe an in-flight replay followed by completion. +func (r *lifetimeReplayRef) Ask(ctx context.Context, + message oor.OORDurableMsg) actor.Future[oor.ActorResp] { + + if _, ok := message.(*oor.GetStateRequest); ok { + r.reads++ + if r.reads > 1 { + r.state = &oor.Completed{} + } + } + + return r.controllerTestRef.Ask(ctx, message) +} + +// TestSourceLifetimeAdvancedReplay never applies a new admission rejection +// after prepared commit, including post-PONR and already terminal replays. +func TestSourceLifetimeAdvancedReplay(t *testing.T) { + t.Parallel() + + states := []oor.SessionState{ + &oor.AwaitingArkSignatures{}, + &oor.AwaitingSubmitAccepted{}, + &oor.AwaitingCheckpointSignatures{}, + &oor.AwaitingFinalizeAccepted{}, + &oor.AwaitingLocalVTXOUpdate{}, + &oor.Completed{}, + &oor.ReceiveCompleted{}, + } + for _, state := range states { + t.Run(state.String(), func(t *testing.T) { + t.Parallel() + + terms, source, _, _, _ := preparedChannelBinding(t) + ref := &lifetimeReplayRef{ + controllerTestRef: controllerTestRef{ + state: state, + }, + } + controller, err := NewWithRef(ref) + require.NoError(t, err) + controller.SetPreparedSourceValidator( + func(context.Context, arkchannel.Terms, + arkchannel.VTXOBinding, + *oor.Prepared) error { + + t.Fatal( + "replay must not " + + "revalidate source " + + "lifetime", + ) + + return fmt.Errorf("expired after " + + "signing") + }, + ) + result, err := controller.CommitPreparedOORResult( + t.Context(), terms.ID, terms, source, + ) + require.NoError(t, err) + require.Equal( + t, TerminalResult{ + Finalized: true, + }, + result, + ) + require.Nil(t, ref.driveEvent) + }) + } +} + +// TestSourceLifetimeExplicitAbort skips admission so a backend outage cannot +// stop an explicit pre-PONR cancellation from releasing its selected inputs. +func TestSourceLifetimeExplicitAbort(t *testing.T) { + t.Parallel() + + terms, source, prepared, _, _ := preparedChannelBinding(t) + controller, err := NewWithRef(&controllerTestRef{state: prepared}) + require.NoError(t, err) + controller.SetPreparedSourceValidator(func(context.Context, + arkchannel.Terms, arkchannel.VTXOBinding, *oor.Prepared) error { + + t.Fatal("explicit abort must not require source admission") + + return fmt.Errorf("backend unavailable") + }) + result, err := controller.AbortPreparedOORResult( + t.Context(), terms.ID, terms, source, "caller canceled", + ) + require.NoError(t, err) + require.Equal(t, TerminalResult{ + Aborted: true, Reason: "caller canceled", + }, result) +} + +// TestSourceLifetimeAbortAppliesTerminalFact advances the channel cancellation +// gate with the durable abort rather than leaving it to retry rejected signing. +func TestSourceLifetimeAbortAppliesTerminalFact(t *testing.T) { + t.Parallel() + + terms, source, prepared, _, _ := preparedChannelBinding(t) + controller, err := NewWithRef(&controllerTestRef{state: prepared}) + require.NoError(t, err) + sink := &controllerTestSink{} + require.NoError(t, controller.BindChannelEventSink(sink)) + controller.SetPreparedSourceValidator(func(context.Context, + arkchannel.Terms, arkchannel.VTXOBinding, *oor.Prepared) error { + + return fmt.Errorf("%w: source expired", + arkchannel.ErrSourceInadmissible) + }) + require.NoError( + t, + controller.CommitPreparedOOR( + t.Context(), terms.ID, terms, source, + ), + ) + event, ok := sink.event.(*arkchannel.OORAborted) + require.True(t, ok) + require.Equal(t, source.OORSessionID, event.SessionID) + require.Contains(t, event.Reason, "source expired") +} diff --git a/arkchannel/oorbridge/controller_test.go b/arkchannel/oorbridge/controller_test.go new file mode 100644 index 000000000..b57c94a53 --- /dev/null +++ b/arkchannel/oorbridge/controller_test.go @@ -0,0 +1,817 @@ +package oorbridge + +import ( + "bytes" + "context" + "encoding/hex" + "fmt" + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/psbt/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/baselib/actor" + "github.com/lightninglabs/wavelength/lib/arkscript" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" + "github.com/lightninglabs/wavelength/lib/tx/psbtutil" + "github.com/lightninglabs/wavelength/oor" + "github.com/lightninglabs/wavelength/vtxo" + fn "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/keychain" + "github.com/lightningnetwork/lnd/lnwire" + "github.com/stretchr/testify/require" +) + +// controllerTestRef returns a fixed OOR state to the controller. +type controllerTestRef struct { + state oor.SessionState + startSessionID oor.SessionID + startExisting bool + startErr error + startPending bool + startRequest *oor.StartTransferRequest + lookupFound bool + lookupPending bool + lookupRequests int + driveEvent oor.Event + driveErr error + stateAfterDrive oor.SessionState +} + +// controllerTestSink records the terminal channel event applied by the bridge. +type controllerTestSink struct { + event arkchannel.Event +} + +// Apply records one channel event. +func (s *controllerTestSink) ApplyLocalEvent(_ context.Context, _ arkchannel.ID, + event arkchannel.Event) (arkchannel.Record, error) { + + s.event = event + + return arkchannel.Record{}, nil +} + +// ID returns the fake actor identity. +func (*controllerTestRef) ID() string { + return "oor-controller-test" +} + +// Tell accepts messages unused by this read-only fixture. +func (*controllerTestRef) Tell(context.Context, oor.OORDurableMsg) error { + return nil +} + +// TryTell accepts messages unused by this read-only fixture. +func (*controllerTestRef) TryTell(context.Context, oor.OORDurableMsg) error { + return nil +} + +// Ask serves the current state query used by source validation. +func (r *controllerTestRef) Ask(_ context.Context, + message oor.OORDurableMsg) actor.Future[oor.ActorResp] { + + promise := actor.NewPromise[oor.ActorResp]() + var response oor.ActorResp + switch message := message.(type) { + case *oor.GetStateRequest: + response = &oor.GetStateResponse{State: r.state} + + case *oor.StartTransferRequest: + r.startRequest = message + if r.startPending { + return promise.Future() + } + if r.startErr != nil { + promise.Complete(fn.Err[oor.ActorResp](r.startErr)) + + return promise.Future() + } + response = &oor.StartTransferResponse{ + SessionID: r.startSessionID, Existing: r.startExisting, + } + + case *oor.LookupTransferRequest: + r.lookupRequests++ + response = &oor.LookupTransferResponse{ + SessionID: r.startSessionID, Found: r.lookupFound, + Pending: r.lookupPending, + } + + case *oor.DriveEventRequest: + r.driveEvent = message.Event + if r.stateAfterDrive != nil { + r.state = r.stateAfterDrive + } else { + switch event := message.Event.(type) { + case *oor.CommitPreparedEvent: + r.state = &oor.Completed{} + + case *oor.AbortPreparedEvent: + r.state = &oor.Failed{ + Reason: event.Reason, PrePONR: true, + } + } + } + if r.driveErr != nil { + promise.Complete(fn.Err[oor.ActorResp](r.driveErr)) + + return promise.Future() + } + response = &oor.DriveEventResponse{} + + default: + response = &oor.DriveEventResponse{} + } + promise.Complete(fn.Ok(response)) + + return promise.Future() +} + +// TestPrepareChannelStopsBeforeOORSignatures proves the channel output is +// created through the ordinary OOR actor while its state remains Prepared. +func TestPrepareChannelStopsBeforeOORSignatures(t *testing.T) { + t.Parallel() + + terms, expected, prepared, _, _ := preparedChannelBinding(t) + operatorKey, err := btcec.ParsePubKey(terms.VTXO.ArkOperatorKey[:]) + require.NoError(t, err) + ref := &controllerTestRef{ + state: prepared, + startSessionID: oor.SessionID(expected.OORSessionID), + } + controller, err := NewWithRef(ref) + require.NoError(t, err) + + result, err := controller.PrepareChannel(t.Context(), PrepareRequest{ + Terms: terms, + CheckpointPolicy: arkscript.CheckpointPolicy{ + OperatorKey: operatorKey, + CSVDelay: terms.VTXO.MinExitDelay, + }, + Inputs: prepared.TransferInputs, + BackingFee: expected.Amount - terms.Capacity, + }) + require.NoError(t, err) + require.Equal(t, expected, result.Binding) + require.False(t, result.Existing) + require.NotNil(t, ref.startRequest) + require.True(t, ref.startRequest.PrepareOnly) + require.Equal( + t, "ark-channel:"+hex.EncodeToString(terms.ID[:]), + ref.startRequest.IdempotencyKey, + ) + require.Equal(t, prepared.TransferInputs, ref.startRequest.Inputs) + require.Len(t, ref.startRequest.Recipients, 1) +} + +// TestPrepareChannelPreservesAmbiguousAdmission proves a caller cannot release +// channel accounting after the OOR registry has returned a durable session ID +// but its exact prepared state cannot be reconstructed yet. +func TestPrepareChannelPreservesAmbiguousAdmission(t *testing.T) { + t.Parallel() + + terms, expected, prepared, _, _ := preparedChannelBinding(t) + operatorKey, err := btcec.ParsePubKey(terms.VTXO.ArkOperatorKey[:]) + require.NoError(t, err) + ref := &controllerTestRef{ + state: &oor.Completed{}, startSessionID: oor.SessionID( + expected.OORSessionID, + ), + } + controller, err := NewWithRef(ref) + require.NoError(t, err) + + _, err = controller.PrepareChannel(t.Context(), PrepareRequest{ + Terms: terms, + CheckpointPolicy: arkscript.CheckpointPolicy{ + OperatorKey: operatorKey, + CSVDelay: terms.VTXO.MinExitDelay, + }, + Inputs: prepared.TransferInputs, BackingFee: expected.Amount - + terms.Capacity, + }) + require.ErrorIs(t, err, arkchannel.ErrOORPreparationAmbiguous) +} + +// TestPrepareChannelReturnsDefinitiveAdmissionError proves an actor rejection +// observed while the caller is live is safe for the wallet to unlock. +func TestPrepareChannelReturnsDefinitiveAdmissionError(t *testing.T) { + t.Parallel() + + terms, expected, prepared, _, _ := preparedChannelBinding(t) + operatorKey, err := btcec.ParsePubKey(terms.VTXO.ArkOperatorKey[:]) + require.NoError(t, err) + ref := &controllerTestRef{ + state: prepared, startSessionID: oor.SessionID( + expected.OORSessionID, + ), + startErr: fmt.Errorf("admission rejected"), + } + controller, err := NewWithRef(ref) + require.NoError(t, err) + + _, err = controller.PrepareChannel(t.Context(), PrepareRequest{ + Terms: terms, + CheckpointPolicy: arkscript.CheckpointPolicy{ + OperatorKey: operatorKey, + CSVDelay: terms.VTXO.MinExitDelay, + }, + Inputs: prepared.TransferInputs, BackingFee: expected.Amount - + terms.Capacity, + }) + require.ErrorContains(t, err, "admission rejected") + require.NotErrorIs(t, err, arkchannel.ErrOORPreparationAmbiguous) +} + +// TestPrepareChannelMarksCanceledWaitAmbiguous proves caller cancellation +// cannot be interpreted as a registry admission rejection. +func TestPrepareChannelMarksCanceledWaitAmbiguous(t *testing.T) { + t.Parallel() + + terms, expected, prepared, _, _ := preparedChannelBinding(t) + operatorKey, err := btcec.ParsePubKey(terms.VTXO.ArkOperatorKey[:]) + require.NoError(t, err) + controller, err := NewWithRef(&controllerTestRef{startPending: true}) + require.NoError(t, err) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + _, err = controller.PrepareChannel(ctx, PrepareRequest{ + Terms: terms, + CheckpointPolicy: arkscript.CheckpointPolicy{ + OperatorKey: operatorKey, + CSVDelay: terms.VTXO.MinExitDelay, + }, + Inputs: prepared.TransferInputs, BackingFee: expected.Amount - + terms.Capacity, + }) + require.ErrorIs(t, err, arkchannel.ErrOORPreparationAmbiguous) +} + +// TestLookupPreparedChannelReconstructsBinding proves restart recovery uses the +// durable idempotency winner without submitting another transfer request. +func TestLookupPreparedChannelReconstructsBinding(t *testing.T) { + t.Parallel() + + terms, expected, prepared, _, _ := preparedChannelBinding(t) + ref := &controllerTestRef{ + state: prepared, startSessionID: oor.SessionID( + expected.OORSessionID, + ), + lookupFound: true, + } + controller, err := NewWithRef(ref) + require.NoError(t, err) + + binding, found, err := controller.LookupPreparedChannel( + t.Context(), terms, expected.Amount-terms.Capacity, + ) + require.NoError(t, err) + require.True(t, found) + require.Equal(t, expected, binding) + require.Equal(t, 1, ref.lookupRequests) + require.Nil(t, ref.startRequest) +} + +// TestLookupChannelPreparationReportsPending proves an accepted registry +// request cannot be treated as an authoritative miss during retry cleanup. +func TestLookupChannelPreparationReportsPending(t *testing.T) { + t.Parallel() + + terms, expected, _, _, _ := preparedChannelBinding(t) + ref := &controllerTestRef{ + startSessionID: oor.SessionID(expected.OORSessionID), + lookupPending: true, + } + controller, err := NewWithRef(ref) + require.NoError(t, err) + + lookup, err := controller.LookupChannelPreparation( + t.Context(), terms, expected.Amount-terms.Capacity, + ) + require.NoError(t, err) + require.Equal(t, PreparationPending, lookup.Status) + require.Empty(t, lookup.InputOutpoints) + _, found, err := controller.LookupPreparedChannel( + t.Context(), terms, expected.Amount-terms.Capacity, + ) + require.ErrorIs(t, err, arkchannel.ErrOORPreparationAmbiguous) + require.False(t, found) + require.Nil(t, ref.startRequest) +} + +// TestLookupChannelPreparationTreatsPrePONRFailureAsAbsent proves a failed +// admission no longer owns wallet inputs and permits a clean retry. +func TestLookupChannelPreparationTreatsPrePONRFailureAsAbsent(t *testing.T) { + t.Parallel() + + terms, expected, _, _, _ := preparedChannelBinding(t) + controller, err := NewWithRef(&controllerTestRef{ + state: &oor.Failed{Reason: "rejected", PrePONR: true}, + startSessionID: oor.SessionID(expected.OORSessionID), + lookupFound: true, + }) + require.NoError(t, err) + + lookup, err := controller.LookupChannelPreparation( + t.Context(), terms, expected.Amount-terms.Capacity, + ) + require.NoError(t, err) + require.Equal(t, PreparationAbsent, lookup.Status) +} + +// TestValidatePreparedOORBindsExactOutput proves a caller cannot bind a +// plausible but nonexistent output from the same deterministic OOR package. +func TestValidatePreparedOORBindsExactOutput(t *testing.T) { + t.Parallel() + + terms, binding, prepared, _, _ := preparedChannelBinding(t) + controller, err := NewWithRef(&controllerTestRef{state: prepared}) + require.NoError(t, err) + require.NoError( + t, + controller.ValidatePreparedOOR( + t.Context(), terms, binding, + ), + ) + + wrongIndex := binding.Clone() + wrongIndex.OutPoint.Index++ + require.ErrorContains( + t, + controller.ValidatePreparedOOR( + t.Context(), terms, wrongIndex, + ), + "does not match", + ) + + wrongAmount := binding.Clone() + wrongAmount.Amount++ + require.ErrorContains( + t, + controller.ValidatePreparedOOR( + t.Context(), terms, wrongAmount, + ), + "does not match", + ) +} + +// TestValidatePreparedOORRejectsAdvancedSession proves binding happens before +// the OOR signature and transport gates are released. +func TestValidatePreparedOORRejectsAdvancedSession(t *testing.T) { + t.Parallel() + + terms, binding, _, _, _ := preparedChannelBinding(t) + controller, err := NewWithRef(&controllerTestRef{ + state: &oor.AwaitingArkSignatures{}, + }) + require.NoError(t, err) + require.ErrorContains( + t, + controller.ValidatePreparedOOR( + t.Context(), terms, binding, + ), + "expected prepared", + ) +} + +// TestWaitForTerminalAcceptsIncomingSelfTransfer verifies a sender's change +// notification proves the same OOR package finalized even after it replaced +// the reaped outgoing status row. +func TestWaitForTerminalAcceptsIncomingSelfTransfer(t *testing.T) { + t.Parallel() + + ref := &controllerTestRef{state: &oor.ReceiveCompleted{}} + controller, err := NewWithRef(ref) + require.NoError(t, err) + + sessionID := [32]byte{2} + result, err := controller.waitForTerminal( + t.Context(), arkchannel.VTXOBinding{ + OORSessionID: sessionID, + }, + ) + require.NoError(t, err) + require.Equal(t, TerminalResult{Finalized: true}, result) +} + +// TestAbortPreparedOORReconcilesLostFinalizedResponse proves replaying abort +// after commit completed reports finalization and never submits an abort event. +func TestAbortPreparedOORReconcilesLostFinalizedResponse(t *testing.T) { + t.Parallel() + + terms, source, _, _, _ := preparedChannelBinding(t) + ref := &controllerTestRef{state: &oor.Completed{}} + controller, err := NewWithRef(ref) + require.NoError(t, err) + result, err := controller.AbortPreparedOORResult( + t.Context(), terms.ID, terms, source, "expired", + ) + require.NoError(t, err) + require.Equal(t, TerminalResult{Finalized: true}, result) + require.Nil(t, ref.driveEvent) +} + +// TestCommitPreparedOORReconcilesPrePONRAbort proves a lost commit response can +// report the actor's definitive pre-PONR failure without retrying signatures. +func TestCommitPreparedOORReconcilesPrePONRAbort(t *testing.T) { + t.Parallel() + + terms, source, _, _, _ := preparedChannelBinding(t) + ref := &controllerTestRef{state: &oor.Failed{ + Reason: "admission rejected", PrePONR: true, + }} + controller, err := NewWithRef(ref) + require.NoError(t, err) + result, err := controller.CommitPreparedOORResult( + t.Context(), terms.ID, terms, source, + ) + require.NoError(t, err) + require.Equal(t, TerminalResult{ + Aborted: true, Reason: "admission rejected", + }, result) + require.Nil(t, ref.driveEvent) +} + +// TestAbortPreparedOORLosesConcurrentCommit proves an abort response race is +// reconciled from actor state instead of releasing the committed source. +func TestAbortPreparedOORLosesConcurrentCommit(t *testing.T) { + t.Parallel() + + terms, source, prepared, _, _ := preparedChannelBinding(t) + ref := &controllerTestRef{ + state: prepared, driveErr: fmt.Errorf("concurrent control"), + stateAfterDrive: &oor.Completed{}, + } + controller, err := NewWithRef(ref) + require.NoError(t, err) + result, err := controller.AbortPreparedOORResult( + t.Context(), terms.ID, terms, source, "expired", + ) + require.NoError(t, err) + require.Equal(t, TerminalResult{Finalized: true}, result) + require.IsType(t, &oor.AbortPreparedEvent{}, ref.driveEvent) +} + +// TestPostPONRFailureRemainsUnresolved proves source loss alone cannot be +// mistaken for proof that the channel-policy output was finalized. +func TestPostPONRFailureRemainsUnresolved(t *testing.T) { + t.Parallel() + + terms, source, _, _, _ := preparedChannelBinding(t) + ref := &controllerTestRef{state: &oor.Failed{ + Reason: "operator rejected finalization", PrePONR: false, + }} + controller, err := NewWithRef(ref) + require.NoError(t, err) + result, err := controller.CommitPreparedOORResult( + t.Context(), terms.ID, terms, source, + ) + require.ErrorIs(t, err, ErrOORPostPONRFailure) + require.Zero(t, result) + require.Nil(t, ref.driveEvent) +} + +// TestCommitPreparedOORAppliesTerminalFact proves the executor-facing wrapper +// still records the result after the sink-independent control method returns. +func TestCommitPreparedOORAppliesTerminalFact(t *testing.T) { + t.Parallel() + + terms, source, _, _, _ := preparedChannelBinding(t) + controller, err := NewWithRef(&controllerTestRef{ + state: &oor.Completed{}, + }) + require.NoError(t, err) + sink := &controllerTestSink{} + require.NoError(t, controller.BindChannelEventSink(sink)) + + require.NoError( + t, + controller.CommitPreparedOOR( + t.Context(), terms.ID, terms, source, + ), + ) + _, ok := sink.event.(*arkchannel.OORFinalized) + require.True(t, ok) +} + +// TestSettleCooperativeClosePreparesBeforeSigning proves the bridge verifies +// the exact hub-authorized checkpoint while the OOR actor is still Prepared, +// then explicitly releases the ordinary operator-first signing flow. +func TestSettleCooperativeClosePreparesBeforeSigning(t *testing.T) { + t.Parallel() + + testSettleCooperativeClose(t, false) +} + +// TestSettleCooperativeCloseAfterRotation keeps the input operator tied to +// the old VTXO and the checkpoint and both payouts tied to the new session. +func TestSettleCooperativeCloseAfterRotation(t *testing.T) { + t.Parallel() + + testSettleCooperativeClose(t, true) +} + +// testSettleCooperativeClose checks the exact ordinary actor request emitted +// after the client validates the hub authorization. +func testSettleCooperativeClose(t *testing.T, rotated bool) { + t.Helper() + terms, source, _, clientKey, hubKey := preparedChannelBinding(t) + request := arkchannel.CooperativeCloseRequest{ + Initiator: arkchannel.PartyClient, + ClientDeliveryScript: clientKey.PubKey().SerializeCompressed(), + HubDeliveryScript: hubKey.PubKey().SerializeCompressed(), + } + sessionKey, err := btcec.ParsePubKey(terms.VTXO.ArkOperatorKey[:]) + require.NoError(t, err) + delay := terms.VTXO.MinExitDelay + if rotated { + key, err := btcec.NewPrivateKey() + require.NoError(t, err) + sessionKey, delay = key.PubKey(), delay+1 + encode := arkscript.EncodeStandardVTXOTemplate + request.ClientDeliveryScript, err = encode( + clientKey.PubKey(), sessionKey, delay, + ) + require.NoError(t, err) + request.HubDeliveryScript, err = encode( + hubKey.PubKey(), sessionKey, delay, + ) + require.NoError(t, err) + } + // A newly opened channel is still at commitment height zero. Its clean + // genesis state must be eligible for an in-Ark cooperative spend. + template, err := arkchannel.NewCooperativeCloseTemplate( + terms, source, request, 60_000, 40_000, 0, + ) + require.NoError(t, err) + desc, err := template.SignDescriptor( + terms, arkchannel.PartyHub, keychain.KeyDescriptor{ + PubKey: hubKey.PubKey(), + }, + ) + require.NoError(t, err) + checkpoint, err := psbtutil.Parse(template.Proposal().Transaction) + require.NoError(t, err) + hubSig, err := input.NewMockSigner( + []*btcec.PrivateKey{hubKey}, nil, + ).SignOutputRaw(checkpoint.UnsignedTx, desc) + require.NoError(t, err) + arkDesc, err := template.ArkSignDescriptor( + terms, arkchannel.PartyHub, keychain.KeyDescriptor{ + PubKey: hubKey.PubKey(), + }, + ) + require.NoError(t, err) + hubArkSig, err := input.NewMockSigner( + []*btcec.PrivateKey{hubKey}, nil, + ).SignOutputRaw(template.ArkTransaction(), arkDesc) + require.NoError(t, err) + settlement, err := template.Complete( + terms, source, request, hubSig, hubArkSig, + ) + require.NoError(t, err) + + ref := &controllerTestRef{ + state: &oor.Prepared{ + CheckpointPSBTs: []*psbt.Packet{ + checkpoint, + }, + }, + startSessionID: oor.SessionID(settlement.TxID), + } + controller, err := NewWithRef(ref) + require.NoError(t, err) + settle := func(registered []byte) error { + lookup := func(context.Context, arkchannel.ID) ([]byte, error) { + return registered, nil + } + + return controller.SettleCooperativeClose( + t.Context(), terms.ID, terms, source, request, + settlement, keychain.KeyDescriptor{ + PubKey: clientKey.PubKey(), + }, lookup, + ) + } + current := clientKey.PubKey().SerializeCompressed() + if rotated { + require.ErrorContains(t, settle(current), "policy changed") + require.Nil(t, ref.driveEvent) + current, err = arkscript.EncodeStandardVTXOTemplate( + clientKey.PubKey(), sessionKey, delay, + ) + require.NoError(t, err) + } + require.NoError(t, settle(current)) + require.NotNil(t, ref.startRequest) + require.True(t, ref.startRequest.PrepareOnly) + require.Equal( + t, "ark-channel-close:"+hex.EncodeToString(terms.ID[:]), + ref.startRequest.IdempotencyKey, + ) + require.Len(t, ref.startRequest.Inputs, 1) + start := ref.startRequest + in := start.Inputs[0] + require.Equal(t, source.PkScript, in.VTXO.PkScript) + require.Equal( + t, terms.VTXO.ArkOperatorKey[:], + in.VTXO.OperatorKey.SerializeCompressed(), + ) + require.NoError( + t, in.CustomSpend.VerifyBindsToPkScript(source.PkScript), + ) + require.Equal(t, delay, start.Policy.CSVDelay) + require.Equal(t, sessionKey.X(), start.Policy.OperatorKey.X()) + ownerLeaf, err := arkscript.DecodeLeafTemplate(in.OwnerLeafPolicy) + require.NoError(t, err) + multi, ok := ownerLeaf.Node.(*arkscript.Multisig) + require.True(t, ok) + require.True(t, arkscript.ContainsKey(multi, sessionKey)) + if rotated { + require.False( + t, arkscript.ContainsKey(multi, in.VTXO.OperatorKey), + ) + } + ark, cps, err := oor.BuildSubmitPackage( + start.Policy, start.Inputs, start.Recipients, + ) + require.NoError(t, err) + require.Equal(t, settlement.TxID, ark.UnsignedTx.TxHash()) + raw, err := psbtutil.Serialize(cps[0]) + require.NoError(t, err) + require.Equal(t, settlement.Proposal.Transaction, raw) + for _, payout := range []struct { + party arkchannel.Party + owner *btcec.PublicKey + }{ + { + arkchannel.PartyClient, + clientKey.PubKey(), + }, + { + arkchannel.PartyHub, + hubKey.PubKey(), + }, + } { + point, err := settlement.ReplacementOutPoint( + terms, source, request, payout.party, + ) + require.NoError(t, err) + _, script, err := arkscript.EncodeStandardVTXOArtifacts( + payout.owner, sessionKey, delay, + ) + require.NoError(t, err) + require.Equal( + t, script, ark.UnsignedTx.TxOut[point.Index].PkScript, + ) + } + require.Len(t, ref.startRequest.Inputs[0].ExternalSignatures, 1) + require.Equal( + t, hubSig.Serialize(), + ref.startRequest.Inputs[0].ExternalSignatures[0].Signature, + ) + require.Len(t, ref.startRequest.Inputs[0].ExternalArkSignatures, 1) + require.Equal( + t, hubArkSig.Serialize(), + ref.startRequest.Inputs[0].ExternalArkSignatures[0].Signature, + ) + require.IsType(t, &oor.CommitPreparedEvent{}, ref.driveEvent) + ref.driveEvent = nil + require.NoError(t, settle(nil)) + require.Nil(t, ref.driveEvent, "completed OOR must not sign again") +} + +// preparedChannelBinding creates a real deterministic OOR package containing +// one channel-policy recipient. +func preparedChannelBinding(t *testing.T) (arkchannel.Terms, + arkchannel.VTXOBinding, *oor.Prepared, *btcec.PrivateKey, + *btcec.PrivateKey) { + + t.Helper() + keys := make([]*btcec.PrivateKey, 8) + for i := range keys { + key, err := btcec.NewPrivateKey() + require.NoError(t, err) + keys[i] = key + } + compressed := func(key *btcec.PublicKey) [33]byte { + var raw [33]byte + copy(raw[:], key.SerializeCompressed()) + + return raw + } + terms := arkchannel.Terms{ + ID: arkchannel.ID{ + 1, + }, + Kind: arkchannel.KindPromotion, + Funder: arkchannel.PartyClient, + PendingChannelID: [32]byte{ + 2, + }, + ReservedSCID: lnwire.ShortChannelID{ + BlockHeight: 16_000_001, + }.ToUint64(), + Capacity: 100_000, + ClientNodeKey: compressed(keys[0].PubKey()), + HubNodeKey: compressed(keys[1].PubKey()), + VTXO: arkchannel.VTXOTerms{ + ClientArkKey: compressed(keys[2].PubKey()), + HubArkKey: compressed(keys[3].PubKey()), + ArkOperatorKey: compressed(keys[4].PubKey()), + ClientChannelKey: compressed(keys[5].PubKey()), + HubChannelKey: compressed(keys[6].PubKey()), + FunderKey: compressed(keys[7].PubKey()), + ChannelDelay: 10, + FunderDelay: 10 + + arkscript.DefaultChannelReactionWindow, + MinExitDelay: 10, + }, + } + policyTemplate, channelScript, err := terms.VTXO.Artifacts() + require.NoError(t, err) + amount := terms.Capacity + 1_000 + recipients := []oortx.RecipientOutput{{ + PkScript: channelScript, + Value: amount, + VTXOPolicyTemplate: policyTemplate, + }} + + owner := keys[0] + operator := keys[4] + exitDelay := uint32(10) + tapScript, err := arkscript.VTXOTapScript( + owner.PubKey(), operator.PubKey(), exitDelay, + ) + require.NoError(t, err) + tapKey, err := arkscript.VTXOTapKey( + owner.PubKey(), operator.PubKey(), exitDelay, + ) + require.NoError(t, err) + inputScript, err := txscript.PayToTaprootScript(tapKey) + require.NoError(t, err) + ownerLeaf, err := arkscript.MultiSigCollabTapLeaf( + owner.PubKey(), operator.PubKey(), + ) + require.NoError(t, err) + inputs := []oor.TransferInput{{ + VTXO: &vtxo.Descriptor{ + Outpoint: wire.OutPoint{ + Hash: chainhash.Hash{ + 9, + }, + }, + Amount: amount, + PkScript: inputScript, + ClientKey: keychain.KeyDescriptor{ + PubKey: owner.PubKey(), + }, + OperatorKey: operator.PubKey(), + TapScript: tapScript, + RelativeExpiry: exitDelay, + }, + OwnerLeafScript: ownerLeaf.Script, + }} + checkpointPolicy := arkscript.CheckpointPolicy{ + OperatorKey: operator.PubKey(), + CSVDelay: exitDelay, + } + session, outbox, err := oor.NewPreparedSessionWithIdempotencyKey( + t.Context(), checkpointPolicy, inputs, recipients, + "ark-channel:1", oor.EnvConfig{}, + ) + require.NoError(t, err) + require.Empty(t, outbox) + t.Cleanup(session.FSM.Stop) + state, err := session.FSM.CurrentState() + require.NoError(t, err) + prepared, ok := state.(*oor.Prepared) + require.True(t, ok) + outpoint, err := oortx.RecipientOutPoint( + chainhash.Hash(session.ID), recipients, recipients[0], + ) + require.NoError(t, err) + var arkTransaction bytes.Buffer + require.NoError( + t, prepared.ArkPSBT.UnsignedTx.Serialize(&arkTransaction), + ) + + return terms, arkchannel.VTXOBinding{ + OORSessionID: [32]byte(session.ID), + OutPoint: outpoint, + Amount: amount, + ArkTransaction: arkTransaction.Bytes(), + PolicyTemplate: policyTemplate, + PkScript: channelScript, + }, prepared, keys[2], keys[3] +} + +var _ actor.ActorRef[ + oor.OORDurableMsg, oor.ActorResp, +] = (*controllerTestRef)(nil) diff --git a/arkchannel/oorbridge/preparer.go b/arkchannel/oorbridge/preparer.go new file mode 100644 index 000000000..0ba9fa90e --- /dev/null +++ b/arkchannel/oorbridge/preparer.go @@ -0,0 +1,390 @@ +package oorbridge + +import ( + "bytes" + "context" + "encoding/hex" + "errors" + "fmt" + "math" + + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/baselib/actor" + "github.com/lightninglabs/wavelength/lib/arkscript" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" + "github.com/lightninglabs/wavelength/oor" +) + +// PrepareRequest contains the funder's selected VTXOs and the operator policy +// needed to create one channel-policy output through the ordinary OOR actor. +type PrepareRequest struct { + Terms arkchannel.Terms + CheckpointPolicy arkscript.CheckpointPolicy + Inputs []oor.TransferInput + BackingFee btcutil.Amount + ChangeOutput *oortx.RecipientOutput +} + +// PrepareResult reports the exact channel-policy output and whether another +// replay already owned the idempotency key. A caller that selected fresh VTXOs +// must release them when Existing is true. +type PrepareResult struct { + Binding arkchannel.VTXOBinding + Existing bool +} + +// PreparationStatus classifies the durable admission state for one channel +// idempotency key. +type PreparationStatus uint8 + +const ( + // PreparationAbsent proves no accepted or durable active session owns + // the channel key. A fresh wallet selection is safe after old locks are + // released. + PreparationAbsent PreparationStatus = iota + + // PreparationPending means the registry accepted the request but its + // child has not committed a durable session row yet. + PreparationPending + + // PreparationPrepared means the exact pre-signing binding is + // recoverable. + PreparationPrepared + + // PreparationAccepted means the keyed session advanced beyond + // preparation. Its inputs must never be unlocked as an unaccepted + // request. + PreparationAccepted +) + +// PreparationLookup is the authoritative keyed admission result. +type PreparationLookup struct { + Status PreparationStatus + Binding arkchannel.VTXOBinding + InputOutpoints []wire.OutPoint +} + +// PrepareChannel durably reserves the selected VTXOs and constructs the exact +// OOR output used by lnd negotiation. It does not release any signature or +// network side effect. +func (c *Controller) PrepareChannel(ctx context.Context, req PrepareRequest) ( + PrepareResult, error) { + + if err := req.Terms.Validate(); err != nil { + return PrepareResult{}, err + } + if req.CheckpointPolicy.OperatorKey == nil { + return PrepareResult{}, fmt.Errorf("OOR checkpoint operator " + + "key is required") + } + if req.CheckpointPolicy.CSVDelay == 0 { + return PrepareResult{}, fmt.Errorf("OOR checkpoint delay is " + + "required") + } + if len(req.Inputs) == 0 { + return PrepareResult{}, fmt.Errorf("at least one OOR funding " + + "input is required") + } + if err := validateBackingAmount(req.Terms, req.BackingFee); err != nil { + return PrepareResult{}, err + } + + policy, pkScript, err := req.Terms.VTXO.Artifacts() + if err != nil { + return PrepareResult{}, err + } + amount := req.Terms.Capacity + req.BackingFee + recipient := oortx.RecipientOutput{ + PkScript: pkScript, + Value: amount, + VTXOPolicyTemplate: policy, + } + recipients := []oortx.RecipientOutput{recipient} + if req.ChangeOutput != nil { + change := *req.ChangeOutput + change.PkScript = append([]byte(nil), change.PkScript...) + change.VTXOPolicyTemplate = append( + []byte(nil), change.VTXOPolicyTemplate..., + ) + if change.Value <= 0 || len(change.PkScript) == 0 || + len(change.VTXOPolicyTemplate) == 0 { + return PrepareResult{}, fmt.Errorf("complete OOR " + + "change output is required") + } + recipients = append(recipients, change) + } + idempotencyKey := channelIdempotencyKey(req.Terms.ID) + actorCtx := actor.WithoutTx(context.WithoutCancel(ctx)) + result := c.ref.Ask(actorCtx, &oor.StartTransferRequest{ + Policy: req.CheckpointPolicy, + Inputs: req.Inputs, + Recipients: recipients, + IdempotencyKey: idempotencyKey, + PrepareOnly: true, + }).Await(ctx) + response, err := result.Unpack() + if err != nil { + if !preparationAwaitCanceled(ctx, err) { + return PrepareResult{}, fmt.Errorf("prepare channel "+ + "OOR transfer: %w", err) + } + + return PrepareResult{}, ambiguousPreparationError( + fmt.Errorf("prepare channel OOR transfer: %w", err), + ) + } + started, ok := response.(*oor.StartTransferResponse) + if !ok { + return PrepareResult{}, ambiguousPreparationError( + fmt.Errorf("unexpected OOR prepare response %T", + response), + ) + } + if started.SessionID == (oor.SessionID{}) { + return PrepareResult{}, ambiguousPreparationError( + fmt.Errorf("prepared OOR session ID is empty"), + ) + } + state, err := c.state(ctx, [32]byte(started.SessionID)) + if err != nil { + return PrepareResult{}, ambiguousPreparationError(err) + } + prepared, ok := state.(*oor.Prepared) + if !ok { + return PrepareResult{}, ambiguousPreparationError( + fmt.Errorf("OOR session is %T, expected prepared", + state), + ) + } + binding, err := c.preparedChannelBinding( + ctx, req.Terms, req.BackingFee, [32]byte(started.SessionID), + prepared, + ) + if err != nil { + return PrepareResult{}, ambiguousPreparationError(err) + } + + return PrepareResult{ + Binding: binding, Existing: started.Existing, + }, nil +} + +// preparationAwaitCanceled distinguishes an interrupted caller wait from an +// actor result that definitively rejected admission. +func preparationAwaitCanceled(ctx context.Context, err error) bool { + if ctx.Err() == nil { + return false + } + + return errors.Is(err, context.Canceled) || + errors.Is(err, context.DeadlineExceeded) +} + +// ambiguousPreparationError prevents a caller from declaring the channel +// failed after the durable OOR actor may already own its selected inputs. +func ambiguousPreparationError(err error) error { + return fmt.Errorf("%w: %w", arkchannel.ErrOORPreparationAmbiguous, err) +} + +// LookupPreparedChannel reconstructs an interrupted channel binding from the +// OOR actor's durable idempotency-key winner without selecting more VTXOs. +func (c *Controller) LookupPreparedChannel(ctx context.Context, + terms arkchannel.Terms, backingFee btcutil.Amount) ( + arkchannel.VTXOBinding, bool, error) { + + lookup, err := c.LookupChannelPreparation(ctx, terms, backingFee) + if err != nil { + return arkchannel.VTXOBinding{}, false, err + } + switch lookup.Status { + case PreparationAbsent: + return arkchannel.VTXOBinding{}, false, nil + + case PreparationPrepared: + return lookup.Binding, true, nil + + case PreparationPending, PreparationAccepted: + return arkchannel.VTXOBinding{}, false, + ambiguousPreparationError( + fmt.Errorf("channel OOR admission is %s", + lookup.Status), + ) + + default: + return arkchannel.VTXOBinding{}, false, fmt.Errorf("unknown "+ + "channel OOR preparation status %d", lookup.Status) + } +} + +// String returns the stable diagnostic name of a preparation status. +func (s PreparationStatus) String() string { + switch s { + case PreparationAbsent: + return "absent" + + case PreparationPending: + return "pending" + + case PreparationPrepared: + return "prepared" + + case PreparationAccepted: + return "accepted" + + default: + return "unknown" + } +} + +// LookupChannelPreparation classifies one keyed admission without selecting +// inputs or starting another OOR transfer. +func (c *Controller) LookupChannelPreparation(ctx context.Context, + terms arkchannel.Terms, backingFee btcutil.Amount) (PreparationLookup, + error) { + + if err := terms.Validate(); err != nil { + return PreparationLookup{}, err + } + if err := validateBackingAmount(terms, backingFee); err != nil { + return PreparationLookup{}, err + } + result := c.ref.Ask(actor.WithoutTx(ctx), &oor.LookupTransferRequest{ + IdempotencyKey: channelIdempotencyKey(terms.ID), + }).Await(ctx) + response, err := result.Unpack() + if err != nil { + return PreparationLookup{}, fmt.Errorf("lookup prepared "+ + "channel OOR: %w", err) + } + lookup, ok := response.(*oor.LookupTransferResponse) + if !ok { + return PreparationLookup{}, fmt.Errorf("unexpected OOR lookup "+ + "response %T", response) + } + if !lookup.Found && !lookup.Pending { + return PreparationLookup{Status: PreparationAbsent}, nil + } + if lookup.SessionID == (oor.SessionID{}) { + return PreparationLookup{}, fmt.Errorf("prepared OOR lookup " + + "returned an empty session ID") + } + if lookup.Pending { + return PreparationLookup{Status: PreparationPending}, nil + } + state, err := c.state(ctx, [32]byte(lookup.SessionID)) + if err != nil { + return PreparationLookup{}, err + } + prepared, ok := state.(*oor.Prepared) + if !ok { + if failed, ok := state.(*oor.Failed); ok && failed.PrePONR { + return PreparationLookup{Status: PreparationAbsent}, nil + } + + return PreparationLookup{ + Status: PreparationAccepted, + InputOutpoints: sessionInputOutpoints(state), + }, nil + } + binding, err := c.preparedChannelBinding( + ctx, terms, backingFee, [32]byte(lookup.SessionID), prepared, + ) + if err != nil { + return PreparationLookup{}, err + } + + return PreparationLookup{ + Status: PreparationPrepared, + Binding: binding, + InputOutpoints: oor.InputOutpoints(prepared.TransferInputs), + }, nil +} + +// sessionInputOutpoints returns the selected inputs retained by outgoing OOR +// states. Terminal success intentionally returns nil because its wallet update +// already owns the source lifecycle. +func sessionInputOutpoints(state oor.SessionState) []wire.OutPoint { + var inputs []oor.TransferInput + switch state := state.(type) { + case *oor.Prepared: + inputs = state.TransferInputs + + case *oor.AwaitingArkSignatures: + inputs = state.TransferInputs + + case *oor.AwaitingSubmitAccepted: + inputs = state.TransferInputs + + case *oor.AwaitingCheckpointSignatures: + inputs = state.TransferInputs + + case *oor.AwaitingFinalizeAccepted: + inputs = state.TransferInputs + + case *oor.AwaitingLocalVTXOUpdate: + inputs = state.TransferInputs + } + + return oor.InputOutpoints(inputs) +} + +// preparedChannelBinding derives and validates the exact target output from a +// durable prepared OOR state. +func (c *Controller) preparedChannelBinding(ctx context.Context, + terms arkchannel.Terms, backingFee btcutil.Amount, sessionID [32]byte, + prepared *oor.Prepared) (arkchannel.VTXOBinding, error) { + + policy, pkScript, err := terms.VTXO.Artifacts() + if err != nil { + return arkchannel.VTXOBinding{}, err + } + recipient := oortx.RecipientOutput{ + PkScript: pkScript, Value: terms.Capacity + backingFee, + VTXOPolicyTemplate: policy, + } + outpoint, err := oortx.RecipientOutPoint( + chainhash.Hash(sessionID), prepared.RecipientOutputs, recipient, + ) + if err != nil { + return arkchannel.VTXOBinding{}, fmt.Errorf("resolve prepared "+ + "channel output: %w", err) + } + var arkTransaction bytes.Buffer + if err := prepared.ArkPSBT.UnsignedTx.Serialize( + &arkTransaction, + ); err != nil { + return arkchannel.VTXOBinding{}, fmt.Errorf("serialize "+ + "prepared Ark transaction: %w", err) + } + binding := arkchannel.VTXOBinding{ + OORSessionID: sessionID, OutPoint: outpoint, + Amount: recipient.Value, ArkTransaction: arkTransaction.Bytes(), + PolicyTemplate: policy, PkScript: pkScript, + } + if err := c.ValidatePreparedOOR(ctx, terms, binding); err != nil { + return arkchannel.VTXOBinding{}, fmt.Errorf("validate "+ + "prepared channel OOR: %w", err) + } + + return binding, nil +} + +// validateBackingAmount rejects arithmetic overflow before building outputs. +func validateBackingAmount(terms arkchannel.Terms, + backingFee btcutil.Amount) error { + + if backingFee <= 0 || terms.Capacity > + btcutil.Amount(math.MaxInt64)-backingFee { + return fmt.Errorf("invalid channel backing amount") + } + + return nil +} + +// channelIdempotencyKey maps one immutable channel ID to its OOR session. +func channelIdempotencyKey(id arkchannel.ID) string { + return "ark-channel:" + hex.EncodeToString(id[:]) +} diff --git a/arkchannel/unrollbridge/controller.go b/arkchannel/unrollbridge/controller.go new file mode 100644 index 000000000..08716966a --- /dev/null +++ b/arkchannel/unrollbridge/controller.go @@ -0,0 +1,353 @@ +// Package unrollbridge materializes Ark-backed channel points through the +// ordinary VTXO unroller with the signed channel backing as its final spend. +package unrollbridge + +import ( + "bytes" + "context" + "encoding/hex" + "fmt" + "sync" + "time" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/baselib/actor" + "github.com/lightninglabs/wavelength/unroll" +) + +const ( + // ExitPolicyKind identifies a materialized channel backing transaction + // in the durable unroll registry. + ExitPolicyKind unroll.ExitPolicyKind = "ark_channel_backing" + + // fallbackChannelExitFeeRateSatPerVByte lets the unroller continue when + // fee estimation is unavailable. The backing transaction's fee is + // immutable, but its publication eventually races the longer funder + // refund path, so deferring the attempt is less safe. + fallbackChannelExitFeeRateSatPerVByte int64 = 2 + + defaultPollInterval = 100 * time.Millisecond +) + +// Controller starts and observes channel materialization jobs. +type Controller struct { + registry actor.ActorRef[unroll.RegistryMsg, unroll.RegistryResp] + sourcePreparer SourcePreparer + + pollInterval time.Duration + + mu sync.RWMutex + sink arkchannel.ChannelEventSink +} + +// SourcePreparer makes the channel-policy VTXO and its finalized OOR package +// available to the common unroller without adding it to wallet inventory. +type SourcePreparer interface { + EnsureChannelSource(context.Context, arkchannel.ID, arkchannel.Terms, + arkchannel.VTXOBinding, unroll.ExitPolicyKind) error + + WaitForChannelBacking(context.Context, arkchannel.ID, + arkchannel.Backing) error +} + +// NewController constructs a channel materializer over the common unroll +// registry. +func NewController( + registry actor.ActorRef[unroll.RegistryMsg, unroll.RegistryResp], + sourcePreparer SourcePreparer) (*Controller, error) { + + if registry == nil { + return nil, fmt.Errorf("unroll registry is required") + } + if sourcePreparer == nil { + return nil, fmt.Errorf("channel source preparer is required") + } + + return &Controller{ + registry: registry, + sourcePreparer: sourcePreparer, + pollInterval: defaultPollInterval, + }, nil +} + +// BindChannelEventSink attaches materialization observations to the durable +// channel service. +func (c *Controller) BindChannelEventSink( + sink arkchannel.ChannelEventSink) error { + + if sink == nil { + return fmt.Errorf("channel event sink is required") + } + c.mu.Lock() + defer c.mu.Unlock() + if c.sink != nil { + return nil + } + c.sink = sink + + return nil +} + +// MaterializeChannel asks the ordinary VTXO unroller to publish all OOR +// ancestry and use the already signed backing transaction as its final spend. +func (c *Controller) MaterializeChannel(ctx context.Context, id arkchannel.ID, + terms arkchannel.Terms, source arkchannel.VTXOBinding, + backing arkchannel.Backing) error { + + if err := c.publishFinalSpend( + ctx, id, terms, source, ExitPolicyKind, + backing.ChannelPoint.Hash, + ); err != nil { + return err + } + if err := c.sourcePreparer.WaitForChannelBacking( + ctx, id, backing, + ); err != nil { + return err + } + + return c.apply(ctx, id, &arkchannel.BackingPublished{ + TxID: backing.ChannelPoint.Hash, + }) +} + +// publishFinalSpend runs one durable unroll job and verifies its final spend. +func (c *Controller) publishFinalSpend(ctx context.Context, id arkchannel.ID, + terms arkchannel.Terms, source arkchannel.VTXOBinding, + policyKind unroll.ExitPolicyKind, expectedTxID chainhash.Hash) error { + + if err := c.sourcePreparer.EnsureChannelSource( + ctx, id, terms, source, policyKind, + ); err != nil { + return fmt.Errorf("prepare channel unroll source: %w", err) + } + + result := c.registry.Ask(actor.WithoutTx(ctx), + &unroll.EnsureUnrollRequest{ + Outpoint: source.OutPoint, + Trigger: unroll.TriggerManual, + ExitPolicyKind: policyKind, + ExitPolicyRef: hex.EncodeToString(id[:]), + }, + ).Await(ctx) + response, err := result.Unpack() + if err != nil { + return fmt.Errorf("start channel materialization: %w", err) + } + if _, ok := response.(*unroll.EnsureUnrollResp); !ok { + return fmt.Errorf("unexpected unroll response %T", response) + } + + for { + statusResult := c.registry.Ask(actor.WithoutTx(ctx), + &unroll.GetStatusRequest{Outpoint: source.OutPoint}, + ).Await(ctx) + statusResponse, err := statusResult.Unpack() + if err != nil { + return fmt.Errorf("read channel materialization: %w", + err) + } + status, ok := statusResponse.(*unroll.GetStatusResp) + if !ok { + return fmt.Errorf("unexpected unroll status %T", + statusResponse) + } + if !status.Found { + return fmt.Errorf("channel materialization job " + + "disappeared") + } + if status.Phase == unroll.PhaseFailed { + return fmt.Errorf("channel materialization failed: %s", + status.FailReason) + } + if status.SweepTxid != nil { + if *status.SweepTxid != expectedTxID { + return fmt.Errorf("unroller published a " + + "different Ark channel transaction") + } + + return nil + } + if status.Phase == unroll.PhaseCompleted { + return fmt.Errorf("completed channel unroll has no " + + "final txid") + } + + timer := time.NewTimer(c.pollInterval) + select { + case <-ctx.Done(): + if !timer.Stop() { + <-timer.C + } + + return ctx.Err() + + case <-timer.C: + } + } +} + +// apply records a materialization observation through the bound service. +func (c *Controller) apply(ctx context.Context, id arkchannel.ID, + event arkchannel.Event) error { + + c.mu.RLock() + sink := c.sink + c.mu.RUnlock() + if sink == nil { + return fmt.Errorf("channel event sink is not bound") + } + _, err := sink.ApplyLocalEvent(ctx, id, event) + + return err +} + +// Resolver reconstructs channel final-spend policies from the durable channel +// FSM instead of persisting another copy in the unroller. +type Resolver struct { + Channels arkchannel.Store +} + +// SupportsKind reports support for channel backing spends. +func (r Resolver) SupportsKind(kind unroll.ExitPolicyKind) bool { + return kind == ExitPolicyKind +} + +// ResolveExitSpendPolicy loads and validates the exact signed backing named by +// the durable channel ID. +func (r Resolver) ResolveExitSpendPolicy(ctx context.Context, + req unroll.ExitSpendPolicyRequest) (unroll.ExitSpendPolicy, error) { + + if r.Channels == nil { + return nil, fmt.Errorf("Ark channel store is required") + } + if !r.SupportsKind(req.Kind) { + return nil, fmt.Errorf("unsupported channel exit policy %q", + req.Kind) + } + rawID, err := hex.DecodeString(req.Ref) + if err != nil || len(rawID) != len(arkchannel.ID{}) { + return nil, fmt.Errorf("invalid Ark channel policy reference") + } + var id arkchannel.ID + copy(id[:], rawID) + record, err := r.Channels.Get(ctx, id) + if err != nil { + return nil, err + } + snapshot := record.Snapshot + if snapshot.Source == nil || snapshot.Backing == nil { + return nil, fmt.Errorf("Ark channel is missing " + + "materialization artifacts") + } + if !snapshot.OORFinalized { + return nil, fmt.Errorf("Ark channel OOR is not finalized") + } + if err := snapshot.Backing.Validate( + snapshot.Terms, *snapshot.Source, + ); err != nil { + return nil, err + } + + return &channelExitPolicy{ + terms: snapshot.Terms, + source: snapshot.Source.Clone(), + backing: snapshot.Backing.Clone(), + }, nil +} + +// channelExitPolicy returns the immutable funding transaction as unroll's +// final spend after lineage publication and CSV maturity. +type channelExitPolicy struct { + terms arkchannel.Terms + source arkchannel.VTXOBinding + backing arkchannel.Backing +} + +// Kind returns the durable channel backing policy kind. +func (p *channelExitPolicy) Kind() unroll.ExitPolicyKind { + return ExitPolicyKind +} + +// CSVDelay returns the delay encoded by the channel materialization leaf. +func (p *channelExitPolicy) CSVDelay() uint32 { + return p.terms.VTXO.ChannelDelay +} + +// RequiredLockTime returns the backing transaction's absolute locktime. +func (p *channelExitPolicy) RequiredLockTime() uint32 { + tx, err := p.transaction() + if err != nil { + return 0 + } + + return tx.LockTime +} + +// FeeEstimateFallbackSatPerVByte returns the emergency rate used to keep a +// race-sensitive channel materialization moving through the common unroller. +// The immutable backing transaction ignores the resulting estimate. +func (p *channelExitPolicy) FeeEstimateFallbackSatPerVByte() int64 { + return fallbackChannelExitFeeRateSatPerVByte +} + +// ValidateTarget binds the materialized output to the channel source. +func (p *channelExitPolicy) ValidateTarget(target *wire.TxOut) error { + if target == nil { + return fmt.Errorf("materialized channel VTXO is required") + } + if target.Value != int64(p.source.Amount) || + !bytes.Equal(target.PkScript, p.source.PkScript) { + return fmt.Errorf("materialized output does not match " + + "channel VTXO") + } + + return nil +} + +// BuildSpendTx returns the fully signed transaction negotiated before the OOR +// transfer crossed its point of no return. +func (p *channelExitPolicy) BuildSpendTx(_ context.Context, + req unroll.ExitSpendRequest) (*wire.MsgTx, error) { + + if req.TargetOutpoint != p.source.OutPoint { + return nil, fmt.Errorf("materialized outpoint does not match " + + "channel VTXO") + } + if err := p.ValidateTarget(req.TargetOutput); err != nil { + return nil, err + } + if err := p.backing.Validate(p.terms, p.source); err != nil { + return nil, err + } + + return p.PreSignedSpendTx() +} + +// PreSignedSpendTx returns the immutable backing transaction negotiated by +// both channel parties before the OOR transfer was finalized. +func (p *channelExitPolicy) PreSignedSpendTx() (*wire.MsgTx, error) { + return p.transaction() +} + +// transaction decodes an isolated copy of the signed backing transaction. +func (p *channelExitPolicy) transaction() (*wire.MsgTx, error) { + tx := wire.NewMsgTx(2) + if err := tx.Deserialize( + bytes.NewReader(p.backing.Transaction), + ); err != nil { + return nil, fmt.Errorf("decode channel backing transaction: %w", + err) + } + + return tx, nil +} + +var _ arkchannel.ChannelMaterializer = (*Controller)(nil) +var _ arkchannel.ChannelEventSinkBinder = (*Controller)(nil) +var _ unroll.ExitSpendPolicyResolver = Resolver{} +var _ unroll.ResolverKindSupport = Resolver{} +var _ unroll.ExitSpendPolicy = (*channelExitPolicy)(nil) +var _ unroll.PreSignedExitSpendPolicy = (*channelExitPolicy)(nil) diff --git a/arkchannel/unrollbridge/controller_test.go b/arkchannel/unrollbridge/controller_test.go new file mode 100644 index 000000000..511619202 --- /dev/null +++ b/arkchannel/unrollbridge/controller_test.go @@ -0,0 +1,406 @@ +package unrollbridge + +import ( + "bytes" + "context" + "fmt" + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/psbt/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/baselib/actor" + "github.com/lightninglabs/wavelength/unroll" + fn "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/keychain" + "github.com/lightningnetwork/lnd/lnwire" + "github.com/stretchr/testify/require" +) + +// fixedChannelStore serves one durable channel to the policy resolver. +type fixedChannelStore struct { + record arkchannel.Record +} + +// Get returns the configured channel. +func (s *fixedChannelStore) Get(_ context.Context, id arkchannel.ID) ( + arkchannel.Record, error) { + + if id != s.record.Snapshot.Terms.ID { + return arkchannel.Record{}, arkchannel.ErrNotFound + } + + return s.record, nil +} + +// Create is unused by the read-only resolver. +func (*fixedChannelStore) Create(context.Context, arkchannel.Snapshot) ( + arkchannel.Record, error) { + + return arkchannel.Record{}, arkchannel.ErrConflict +} + +// GetByPendingChannelID is unused by the read-only resolver. +func (*fixedChannelStore) GetByPendingChannelID(context.Context, [32]byte) ( + arkchannel.Record, error) { + + return arkchannel.Record{}, arkchannel.ErrNotFound +} + +// GetByChannelPoint is unused by the read-only resolver. +func (*fixedChannelStore) GetByChannelPoint(context.Context, wire.OutPoint) ( + arkchannel.Record, error) { + + return arkchannel.Record{}, arkchannel.ErrNotFound +} + +// ListNonTerminal is unused by the read-only resolver. +func (*fixedChannelStore) ListNonTerminal(context.Context) ([]arkchannel.Record, + error) { + + return nil, nil +} + +// CompareAndSwap is unused by the read-only resolver. +func (*fixedChannelStore) CompareAndSwap(context.Context, arkchannel.ID, uint64, + arkchannel.Snapshot) (arkchannel.Record, error) { + + return arkchannel.Record{}, arkchannel.ErrConflict +} + +// materializerRef captures admission and reports the backing as published. +type materializerRef struct { + request *unroll.EnsureUnrollRequest + txid chainhash.Hash + completeAfter int + statusCalls int +} + +// sourcePreparer records the recovery path selected before admission. +type sourcePreparer struct { + id arkchannel.ID + terms arkchannel.Terms + source arkchannel.VTXOBinding + kind unroll.ExitPolicyKind + waitErr error +} + +// EnsureChannelSource records one idempotent source preparation. +func (p *sourcePreparer) EnsureChannelSource(_ context.Context, + id arkchannel.ID, terms arkchannel.Terms, source arkchannel.VTXOBinding, + kind unroll.ExitPolicyKind) error { + + p.id = id + p.terms = terms + p.source = source + p.kind = kind + + return nil +} + +// WaitForChannelBacking accepts the fake registry's confirmed backing. +func (p *sourcePreparer) WaitForChannelBacking(context.Context, arkchannel.ID, + arkchannel.Backing) error { + + return p.waitErr +} + +// ID returns the fake actor identity. +func (*materializerRef) ID() string { + return "channel-unroll-test" +} + +// Tell accepts unused one-way messages. +func (*materializerRef) Tell(context.Context, unroll.RegistryMsg) error { + return nil +} + +// TryTell accepts unused one-way messages. +func (*materializerRef) TryTell(context.Context, unroll.RegistryMsg) error { + return nil +} + +// Ask serves admission and status requests. +func (r *materializerRef) Ask(_ context.Context, + message unroll.RegistryMsg) actor.Future[unroll.RegistryResp] { + + promise := actor.NewPromise[unroll.RegistryResp]() + var response unroll.RegistryResp + switch message := message.(type) { + case *unroll.EnsureUnrollRequest: + r.request = message + response = &unroll.EnsureUnrollResp{Created: true} + + case *unroll.GetStatusRequest: + r.statusCalls++ + phase := unroll.PhaseSweepBroadcast + if r.completeAfter > 0 && r.statusCalls >= r.completeAfter { + phase = unroll.PhaseCompleted + } + response = &unroll.GetStatusResp{ + Found: true, + Phase: phase, + SweepTxid: &r.txid, + ExitPolicyKind: r.request.ExitPolicyKind, + } + } + promise.Complete(fn.Ok(response)) + + return promise.Future() +} + +// materializerSink records the published-backing callback. +type materializerSink struct { + event *arkchannel.BackingPublished +} + +// Apply captures the materialization event. +func (s *materializerSink) ApplyLocalEvent(_ context.Context, _ arkchannel.ID, + event arkchannel.Event) (arkchannel.Record, error) { + + s.event, _ = event.(*arkchannel.BackingPublished) + + return arkchannel.Record{}, nil +} + +// TestChannelExitPolicyReturnsSignedBacking proves the common unroller's final +// spend is exactly the transaction lnd negotiated before OOR commit. +func TestChannelExitPolicyReturnsSignedBacking(t *testing.T) { + t.Parallel() + + record := channelRecord(t) + resolver := Resolver{Channels: &fixedChannelStore{record: record}} + policy, err := resolver.ResolveExitSpendPolicy( + t.Context(), unroll.ExitSpendPolicyRequest{ + Kind: ExitPolicyKind, + Ref: channelRef(record.Snapshot.Terms.ID), + }, + ) + require.NoError(t, err) + require.Equal( + t, record.Snapshot.Terms.VTXO.ChannelDelay, policy.CSVDelay(), + ) + require.Equal( + t, fallbackChannelExitFeeRateSatPerVByte, + policy.FeeEstimateFallbackSatPerVByte(), + ) + preSigned, ok := policy.(unroll.PreSignedExitSpendPolicy) + require.True(t, ok) + preSignedTx, err := preSigned.PreSignedSpendTx() + require.NoError(t, err) + require.Equal( + t, record.Snapshot.Backing.ChannelPoint.Hash, + preSignedTx.TxHash(), + ) + + tx, err := policy.BuildSpendTx(t.Context(), unroll.ExitSpendRequest{ + TargetOutpoint: record.Snapshot.Source.OutPoint, + TargetOutput: &wire.TxOut{ + Value: int64(record.Snapshot.Source.Amount), + PkScript: record.Snapshot.Source.PkScript, + }, + }) + require.NoError(t, err) + require.Equal(t, record.Snapshot.Backing.ChannelPoint.Hash, + tx.TxHash()) + require.Equal( + t, record.Snapshot.Source.OutPoint, tx.TxIn[0].PreviousOutPoint, + ) +} + +// TestControllerAdmitsChannelPolicy proves materialization uses a durable +// channel policy reference and reports only the expected backing transaction. +func TestControllerAdmitsChannelPolicy(t *testing.T) { + t.Parallel() + + record := channelRecord(t) + ref := &materializerRef{txid: record.Snapshot.Backing.ChannelPoint.Hash} + preparer := &sourcePreparer{} + controller, err := NewController(ref, preparer) + require.NoError(t, err) + sink := &materializerSink{} + require.NoError(t, controller.BindChannelEventSink(sink)) + require.NoError( + t, + controller.MaterializeChannel( + t.Context(), record.Snapshot.Terms.ID, + record.Snapshot.Terms, *record.Snapshot.Source, + *record.Snapshot.Backing, + ), + ) + require.Equal(t, record.Snapshot.Terms.ID, preparer.id) + require.Equal(t, record.Snapshot.Terms, preparer.terms) + require.Equal(t, *record.Snapshot.Source, preparer.source) + require.Equal(t, ExitPolicyKind, preparer.kind) + require.NotNil(t, ref.request) + require.Equal(t, ExitPolicyKind, ref.request.ExitPolicyKind) + require.Equal( + t, channelRef(record.Snapshot.Terms.ID), + ref.request.ExitPolicyRef, + ) + require.NotNil(t, sink.event) + require.Equal(t, ref.txid, sink.event.TxID) +} + +// TestControllerDoesNotReportUnconfirmedBacking proves a published final +// spend cannot advance the channel while the winning confirmation is unknown. +func TestControllerDoesNotReportUnconfirmedBacking(t *testing.T) { + t.Parallel() + + record := channelRecord(t) + ref := &materializerRef{txid: record.Snapshot.Backing.ChannelPoint.Hash} + preparer := &sourcePreparer{waitErr: context.Canceled} + controller, err := NewController(ref, preparer) + require.NoError(t, err) + sink := &materializerSink{} + require.NoError(t, controller.BindChannelEventSink(sink)) + err = controller.MaterializeChannel( + t.Context(), record.Snapshot.Terms.ID, record.Snapshot.Terms, + *record.Snapshot.Source, *record.Snapshot.Backing, + ) + require.ErrorIs(t, err, context.Canceled) + require.Nil(t, sink.event) +} + +// channelRecord creates one durable, OOR-finalized channel fixture. +func channelRecord(t *testing.T) arkchannel.Record { + record, _ := channelRecordWithKeys(t) + + return record +} + +// channelRecordWithKeys creates a durable channel fixture and retains the +// policy keys needed to construct a valid cooperative-close OOR package. +func channelRecordWithKeys(t *testing.T) (arkchannel.Record, + []*btcec.PrivateKey) { + + t.Helper() + + keys := make([]*btcec.PrivateKey, 8) + for i := range keys { + key, err := btcec.NewPrivateKey() + require.NoError(t, err) + keys[i] = key + } + compressed := func(key *btcec.PrivateKey) [33]byte { + var value [33]byte + copy(value[:], key.PubKey().SerializeCompressed()) + + return value + } + terms := arkchannel.Terms{ + ID: arkchannel.ID{ + 1, + 2, + 3, + }, + Kind: arkchannel.KindPromotion, + Funder: arkchannel.PartyClient, + PendingChannelID: [32]byte{ + 4, + 5, + 6, + }, + ReservedSCID: lnwire.ShortChannelID{ + BlockHeight: 16_000_001, + }.ToUint64(), + Capacity: btcutil.Amount(100_000), + ClientNodeKey: compressed(keys[0]), + HubNodeKey: compressed(keys[1]), + VTXO: arkchannel.VTXOTerms{ + ClientArkKey: compressed(keys[2]), + HubArkKey: compressed(keys[3]), + ArkOperatorKey: compressed(keys[4]), + ClientChannelKey: compressed(keys[5]), + HubChannelKey: compressed(keys[6]), + FunderKey: compressed(keys[7]), + ChannelDelay: 144, + FunderDelay: 576, + MinExitDelay: 144, + }, + } + policy, pkScript, err := terms.VTXO.Artifacts() + require.NoError(t, err) + amount := terms.Capacity + 1_000 + arkTx := wire.NewMsgTx(2) + arkTx.AddTxIn(&wire.TxIn{ + PreviousOutPoint: wire.OutPoint{Hash: chainhash.Hash{7}}, + }) + arkTx.AddTxOut(&wire.TxOut{Value: int64(amount), PkScript: pkScript}) + var rawArk bytes.Buffer + require.NoError(t, arkTx.Serialize(&rawArk)) + source := arkchannel.VTXOBinding{ + OORSessionID: [32]byte(arkTx.TxHash()), + OutPoint: wire.OutPoint{ + Hash: arkTx.TxHash(), + }, + Amount: amount, + ArkTransaction: rawArk.Bytes(), + PolicyTemplate: policy, + PkScript: pkScript, + } + packet, err := psbt.New(nil, []*wire.TxOut{{ + Value: int64(terms.Capacity), + PkScript: []byte{0x51, 0x20, 1}, + }}, 2, 0, nil) + require.NoError(t, err) + template, err := arkchannel.NewBackingTemplate(packet, terms, source) + require.NoError(t, err) + clientSig := signChannelBacking( + t, template, terms, arkchannel.PartyClient, keys[5], + ) + hubSig := signChannelBacking( + t, template, terms, arkchannel.PartyHub, keys[6], + ) + backing, err := template.Complete( + terms, source, clientSig, hubSig, + ) + require.NoError(t, err) + + return arkchannel.Record{ + Revision: 5, + Snapshot: arkchannel.Snapshot{ + Terms: terms, + Phase: arkchannel.PhaseActive, + Source: &source, + Backing: &backing, + OORFinalized: true, + }, + }, keys +} + +// signChannelBacking signs one endpoint's channel-policy branch. +func signChannelBacking(t *testing.T, template *arkchannel.BackingTemplate, + terms arkchannel.Terms, party arkchannel.Party, + key *btcec.PrivateKey) input.Signature { + + t.Helper() + + desc, err := template.SignDescriptor( + terms, party, keychain.KeyDescriptor{ + PubKey: key.PubKey(), + }, + ) + require.NoError(t, err) + sig, err := input.NewMockSigner( + []*btcec.PrivateKey{key}, nil, + ).SignOutputRaw(template.Packet().UnsignedTx, desc) + require.NoError(t, err) + + return sig +} + +// channelRef returns the durable hexadecimal channel policy reference. +func channelRef(id arkchannel.ID) string { + return fmt.Sprintf("%x", id[:]) +} + +var _ arkchannel.Store = (*fixedChannelStore)(nil) +var _ actor.ActorRef[ + unroll.RegistryMsg, unroll.RegistryResp, +] = (*materializerRef)(nil) +var _ arkchannel.ChannelEventSink = (*materializerSink)(nil)