diff --git a/cmd/wavecli/waveclicommands/AGENTS.md b/cmd/wavecli/waveclicommands/AGENTS.md index bf20dfbcb..60193df5c 100644 --- a/cmd/wavecli/waveclicommands/AGENTS.md +++ b/cmd/wavecli/waveclicommands/AGENTS.md @@ -17,15 +17,16 @@ default `--help` face: 2. **Daemon introspection (group "Introspection")** — getinfo, bakemacaroon, schema, mcp (the built-in `help` command is grouped here too). -3. **Advanced subtrees (`ark`, `dev`, `recovery`)** — raw - waverpc/devrpc commands for power users and operator runbooks. +3. **Advanced subtrees (`ark`, `channel`, `dev`, `recovery`)** — raw + waverpc/arkchannelrpc/devrpc commands for power users and operator + runbooks. Hidden from the default `--help` via cobra `Hidden` (not a build tag), so they stay compiled and fully runnable in the shipped binary; `WAVELENGTH_DEV=1` reveals them under an "Advanced" group. The env var only changes visibility — it never gates execution. `ark.*` stays on the `schema`/MCP surfaces; `dev` is reachable only as the generated (hidden) - CLI subtree — it is not registered in `schema`/MCP — and `recovery` is - exposed on neither. + CLI subtree — it is not registered in `schema`/MCP — and `channel` and + `recovery` are exposed on neither. The `swap.*` verbs were retired: `send`/`recv --offchain` and `activity` cover them (the swapruntime daemon runtime that powers those verbs is @@ -75,6 +76,21 @@ who want direct access. | `ark listtransactions` | `ListTransactions` | Raw paginated transaction history | | `ark send {inround,oor}` | `SendVTXO` / `SendOOR` | Raw in-round / OOR send; real transfers require interactive approval or `--yes` | +### `channel.*` advanced commands + +Development control surface for native Ark-backed Lightning channels, +served by `arkchannelrpc.ArkChannelService` on the daemon's local listener. +Every command prints the raw protobuf JSON response. + +| Command | RPC | Description | +|---------|-----|-------------| +| `channel create ` | `PromoteVTXO` | Promote wallet value into a channel; the daemon derives the protocol terms from capacity | +| `channel get ` | `GetChannel` | Show one durable channel snapshot and live balances when available | +| `channel list` | `ListChannels` | List channels that still need recovery, observation, or operator action | +| `channel pay ` | `PayLightningInvoice` | Hold the private channel leg while the hub pays a public Lightning invoice; `--max-fee-sat` defaults to 1,000 | +| `channel close ` | `RequestCooperativeClose` | Start or resume the client-owned cooperative close | +| `channel force-close ` | `MaterializeAndForceClose` | Publish the Ark ancestry, signed backing, and latest commitment | + ### `recovery.*` advanced commands Manual control of daemon-owned vHTLC recovery rows; normal swap clients @@ -139,6 +155,8 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/cmd/wave - `rpc/wavewalletrpc` (generated stubs for the top-level wallet verbs; `WalletService` / `WalletInspectionService` clients). - `waverpc` (generated stubs for `ark.*`, `recovery.*`, getinfo). + - `rpc/arkchannelrpc` (generated `ArkChannelService` stubs for + `channel.*`). - `cmd/wavecli/waveclicommands/devrpc` (the generated `dev` subtree; its registry references `swapclientrpc` service descriptors). @@ -195,6 +213,16 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/cmd/wave which flag to drop and why, since stating the constraint alone invites dropping `--onchain-address` and silently getting the more dangerous unilateral exit (`swapwallet.forceUnroll` carries the same wording). +- `channel.*` dials `ArkChannelService` through the same `getDaemonConn` + transport as the other local commands. `parseChannelID` accepts either + 32-byte hex or the base64 representation printed by protobuf JSON; + amounts must be positive signed 64-bit integers. +- Every channel mutation (`create`, `send`, `receive`, `pay`, `close`, and + `force-close`) requires interactive confirmation or `--yes`. These + development commands remain outside the `schema` and MCP surfaces. +- `channel create` sends a mandatory idempotency key. The caller may supply + `--idempotency-key`; otherwise the CLI generates one, prints it on stderr, + and reuses it while retrying transient transport and admission failures. - `recovery escalate` refuses to run on non-interactive stdin unless `--yes` is passed — it never blocks on a y/N prompt an agent can't answer. diff --git a/cmd/wavecli/waveclicommands/CLAUDE.md b/cmd/wavecli/waveclicommands/CLAUDE.md index bf20dfbcb..60193df5c 100644 --- a/cmd/wavecli/waveclicommands/CLAUDE.md +++ b/cmd/wavecli/waveclicommands/CLAUDE.md @@ -17,15 +17,16 @@ default `--help` face: 2. **Daemon introspection (group "Introspection")** — getinfo, bakemacaroon, schema, mcp (the built-in `help` command is grouped here too). -3. **Advanced subtrees (`ark`, `dev`, `recovery`)** — raw - waverpc/devrpc commands for power users and operator runbooks. +3. **Advanced subtrees (`ark`, `channel`, `dev`, `recovery`)** — raw + waverpc/arkchannelrpc/devrpc commands for power users and operator + runbooks. Hidden from the default `--help` via cobra `Hidden` (not a build tag), so they stay compiled and fully runnable in the shipped binary; `WAVELENGTH_DEV=1` reveals them under an "Advanced" group. The env var only changes visibility — it never gates execution. `ark.*` stays on the `schema`/MCP surfaces; `dev` is reachable only as the generated (hidden) - CLI subtree — it is not registered in `schema`/MCP — and `recovery` is - exposed on neither. + CLI subtree — it is not registered in `schema`/MCP — and `channel` and + `recovery` are exposed on neither. The `swap.*` verbs were retired: `send`/`recv --offchain` and `activity` cover them (the swapruntime daemon runtime that powers those verbs is @@ -75,6 +76,21 @@ who want direct access. | `ark listtransactions` | `ListTransactions` | Raw paginated transaction history | | `ark send {inround,oor}` | `SendVTXO` / `SendOOR` | Raw in-round / OOR send; real transfers require interactive approval or `--yes` | +### `channel.*` advanced commands + +Development control surface for native Ark-backed Lightning channels, +served by `arkchannelrpc.ArkChannelService` on the daemon's local listener. +Every command prints the raw protobuf JSON response. + +| Command | RPC | Description | +|---------|-----|-------------| +| `channel create ` | `PromoteVTXO` | Promote wallet value into a channel; the daemon derives the protocol terms from capacity | +| `channel get ` | `GetChannel` | Show one durable channel snapshot and live balances when available | +| `channel list` | `ListChannels` | List channels that still need recovery, observation, or operator action | +| `channel pay ` | `PayLightningInvoice` | Hold the private channel leg while the hub pays a public Lightning invoice; `--max-fee-sat` defaults to 1,000 | +| `channel close ` | `RequestCooperativeClose` | Start or resume the client-owned cooperative close | +| `channel force-close ` | `MaterializeAndForceClose` | Publish the Ark ancestry, signed backing, and latest commitment | + ### `recovery.*` advanced commands Manual control of daemon-owned vHTLC recovery rows; normal swap clients @@ -139,6 +155,8 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/cmd/wave - `rpc/wavewalletrpc` (generated stubs for the top-level wallet verbs; `WalletService` / `WalletInspectionService` clients). - `waverpc` (generated stubs for `ark.*`, `recovery.*`, getinfo). + - `rpc/arkchannelrpc` (generated `ArkChannelService` stubs for + `channel.*`). - `cmd/wavecli/waveclicommands/devrpc` (the generated `dev` subtree; its registry references `swapclientrpc` service descriptors). @@ -195,6 +213,16 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/cmd/wave which flag to drop and why, since stating the constraint alone invites dropping `--onchain-address` and silently getting the more dangerous unilateral exit (`swapwallet.forceUnroll` carries the same wording). +- `channel.*` dials `ArkChannelService` through the same `getDaemonConn` + transport as the other local commands. `parseChannelID` accepts either + 32-byte hex or the base64 representation printed by protobuf JSON; + amounts must be positive signed 64-bit integers. +- Every channel mutation (`create`, `send`, `receive`, `pay`, `close`, and + `force-close`) requires interactive confirmation or `--yes`. These + development commands remain outside the `schema` and MCP surfaces. +- `channel create` sends a mandatory idempotency key. The caller may supply + `--idempotency-key`; otherwise the CLI generates one, prints it on stderr, + and reuses it while retrying transient transport and admission failures. - `recovery escalate` refuses to run on non-interactive stdin unless `--yes` is passed — it never blocks on a y/N prompt an agent can't answer. diff --git a/cmd/wavecli/waveclicommands/cmd_channel.go b/cmd/wavecli/waveclicommands/cmd_channel.go new file mode 100644 index 000000000..5e68dcd43 --- /dev/null +++ b/cmd/wavecli/waveclicommands/cmd_channel.go @@ -0,0 +1,388 @@ +package waveclicommands + +import ( + "context" + "crypto/rand" + "encoding/base64" + "encoding/hex" + "fmt" + "strconv" + "time" + + "github.com/lightninglabs/wavelength/rpc/arkchannelrpc" + "github.com/spf13/cobra" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +const ( + channelCreateKeyPrefix = "wavecli-channel-" + channelCreateRetryWait = 250 * time.Millisecond +) + +// getArkChannelClient is replaceable by command wiring tests. +var getArkChannelClient = defaultGetArkChannelClient + +// defaultGetArkChannelClient connects to the local Ark channel service. +func defaultGetArkChannelClient(cmd *cobra.Command) ( + arkchannelrpc.ArkChannelServiceClient, *grpc.ClientConn, error) { + + conn, err := getDaemonConn(cmd) + if err != nil { + return nil, nil, err + } + + return arkchannelrpc.NewArkChannelServiceClient(conn), conn, nil +} + +// newChannelCmd builds the daemon-development Ark channel control surface. +func newChannelCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "channel", + Short: "Manage native Ark-backed Lightning channels", + } + cmd.AddCommand( + newChannelCreateCmd(), newChannelGetCmd(), newChannelListCmd(), + newChannelPayCmd(), newChannelRefreshCmd(), + newChannelForceCloseCmd(), + ) + + return cmd +} + +// newChannelCreateCmd promotes one wallet VTXO into an OOR channel. +func newChannelCreateCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "create ", + Short: "Promote wallet value into a channel", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + amount, err := parsePositiveChannelAmount(args[0]) + if err != nil { + return err + } + if err := confirmMoneyMovement( + cmd, fmt.Sprintf("promote %d sat into an "+ + "Ark channel", amount), + ); err != nil { + return err + } + idempotencyKey, _ := cmd.Flags().GetString( + "idempotency-key", + ) + if idempotencyKey == "" { + idempotencyKey, err = newChannelCreateKey() + if err != nil { + return err + } + fmt.Fprintf( + cmd.ErrOrStderr(), + "Channel creation idempotency key: "+ + "%s\n", idempotencyKey, + ) + } + client, conn, err := getArkChannelClient(cmd) + if err != nil { + return err + } + defer conn.Close() + resp, err := promoteVTXOWithRetry( + cmd, client, &arkchannelrpc.PromoteVTXORequest{ + AmountSat: amount, + IdempotencyKey: idempotencyKey, + }, + ) + if err != nil { + return fmt.Errorf("create channel with "+ + "idempotency key %q: %w", + idempotencyKey, err) + } + + return printJSON(resp) + }, + } + cmd.Flags().String("idempotency-key", "", + "stable key for safely retrying this creation") + cmd.Flags().Bool("yes", false, + "approve promoting wallet funds into a channel") + + return cmd +} + +// newChannelCreateKey returns the retry identity used for one CLI invocation. +func newChannelCreateKey() (string, error) { + var entropy [16]byte + if _, err := rand.Read(entropy[:]); err != nil { + return "", fmt.Errorf("generate channel creation key: %w", err) + } + + return channelCreateKeyPrefix + hex.EncodeToString(entropy[:]), nil +} + +// promoteVTXOWithRetry keeps one logical channel creation alive across finite +// RPC attempt deadlines and transient transport loss. The command context +// remains the overall cancellation boundary. +func promoteVTXOWithRetry(cmd *cobra.Command, + client arkchannelrpc.ArkChannelServiceClient, + req *arkchannelrpc.PromoteVTXORequest) ( + *arkchannelrpc.PromoteVTXOResponse, error) { + + ctx := commandContext(cmd) + for { + attemptCtx, cancel := rpcContextFrom(cmd, ctx) + response, err := client.PromoteVTXO(attemptCtx, req) + cancel() + if err == nil { + return response, nil + } + if ctx.Err() != nil { + return nil, ctx.Err() + } + if !retryChannelCreateError(err) { + return nil, err + } + if err := waitChannelCreateRetry(ctx); err != nil { + return nil, err + } + } +} + +// retryChannelCreateError reports transport outcomes that can be retried with +// the same mandatory idempotency key. +func retryChannelCreateError(err error) bool { + switch status.Code(err) { + case codes.Aborted, codes.DeadlineExceeded, codes.ResourceExhausted, + codes.Unavailable: + return true + + default: + return false + } +} + +// waitChannelCreateRetry applies bounded backoff without obscuring command +// cancellation. +func waitChannelCreateRetry(ctx context.Context) error { + timer := time.NewTimer(channelCreateRetryWait) + defer timer.Stop() + + select { + case <-ctx.Done(): + return ctx.Err() + + case <-timer.C: + return nil + } +} + +// newChannelGetCmd returns one durable channel snapshot. +func newChannelGetCmd() *cobra.Command { + return channelIDCommand( + "get ", "Show one channel", "", + func(cmd *cobra.Command, + client arkchannelrpc.ArkChannelServiceClient, + channelID []byte) error { + + ctx, cancel := rpcContext(cmd) + defer cancel() + resp, err := client.GetChannel( + ctx, &arkchannelrpc.GetChannelRequest{ + ChannelId: channelID, + }, + ) + if err != nil { + return err + } + + return printJSON(resp) + }, + ) +} + +// newChannelListCmd returns every channel that still needs daemon recovery or +// operator action. +func newChannelListCmd() *cobra.Command { + return &cobra.Command{ + Use: "list", + Short: "List recoverable channels and live balances", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + client, conn, err := getArkChannelClient(cmd) + if err != nil { + return err + } + defer conn.Close() + ctx, cancel := rpcContext(cmd) + defer cancel() + response, err := client.ListChannels( + ctx, &arkchannelrpc.ListChannelsRequest{}, + ) + if err != nil { + return err + } + + return printJSON(response) + }, + } +} + +// newChannelPayCmd bridges a private source HTLC to a public invoice. +func newChannelPayCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "pay ", + Short: "Pay a public Lightning invoice through a channel", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + maxFee, _ := cmd.Flags().GetUint64("max-fee-sat") + if err := confirmMoneyMovement( + cmd, fmt.Sprintf("pay a public invoice with "+ + "a maximum %d sat fee", maxFee), + ); err != nil { + return err + } + client, conn, err := getArkChannelClient(cmd) + if err != nil { + return err + } + defer conn.Close() + ctx, cancel := rpcContext(cmd) + defer cancel() + resp, err := client.PayLightningInvoice( + ctx, &arkchannelrpc.PayLightningInvoiceRequest{ + PaymentRequest: args[0], + MaxFeeSat: maxFee, + }, + ) + if err != nil { + return err + } + + return printJSON(resp) + }, + } + cmd.Flags().Uint64("max-fee-sat", 1_000, + "maximum public Lightning routing fee") + cmd.Flags().Bool("yes", false, + "approve paying the public invoice") + + return cmd +} + +// newChannelRefreshCmd settles one clean channel into replacement VTXOs. +func newChannelRefreshCmd() *cobra.Command { + return channelIDCommand( + "refresh ", "Refresh one channel inside Ark", + "refresh Ark channel", func(cmd *cobra.Command, + client arkchannelrpc.ArkChannelServiceClient, + channelID []byte) error { + + ctx, cancel := rpcContext(cmd) + defer cancel() + resp, err := client.RefreshChannel( + ctx, + &arkchannelrpc.RefreshChannelRequest{ + ChannelId: channelID, + }, + ) + if err != nil { + return err + } + + return printJSON(resp) + }, + ) +} + +// newChannelForceCloseCmd materializes and force closes one channel. +func newChannelForceCloseCmd() *cobra.Command { + return channelIDCommand( + "force-close ", "Materialize and force close a "+ + "channel", "materialize and force close Ark channel", + func(cmd *cobra.Command, + client arkchannelrpc.ArkChannelServiceClient, + channelID []byte) error { + + ctx, cancel := rpcContext(cmd) + defer cancel() + resp, err := client.MaterializeAndForceClose( + ctx, + &arkchannelrpc.MaterializeAndForceCloseRequest{ + ChannelId: channelID, + }, + ) + if err != nil { + return err + } + + return printJSON(resp) + }, + ) +} + +// channelIDDispatch executes one channel-ID-bearing RPC. +type channelIDDispatch func( + *cobra.Command, arkchannelrpc.ArkChannelServiceClient, []byte, +) error + +// channelIDCommand builds a command whose sole argument is a channel ID. +func channelIDCommand(use, short, action string, + dispatch channelIDDispatch) *cobra.Command { + + cmd := &cobra.Command{ + Use: use, + Short: short, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + channelID, err := parseChannelID(args[0]) + if err != nil { + return err + } + if action != "" { + err := confirmMoneyMovement( + cmd, fmt.Sprintf("%s %x", action, + channelID[:4]), + ) + if err != nil { + return err + } + } + client, conn, err := getArkChannelClient(cmd) + if err != nil { + return err + } + defer conn.Close() + + return dispatch(cmd, client, channelID) + }, + } + if action != "" { + cmd.Flags().Bool("yes", false, "approve the channel action") + } + + return cmd +} + +// parsePositiveChannelAmount parses one positive signed RPC amount. +func parsePositiveChannelAmount(value string) (int64, error) { + amount, err := strconv.ParseInt(value, 10, 64) + if err != nil || amount <= 0 { + return 0, fmt.Errorf("amount-sat must be a positive integer") + } + + return amount, nil +} + +// parseChannelID accepts either canonical hex or protobuf JSON base64. +func parseChannelID(value string) ([]byte, error) { + decoded, err := hex.DecodeString(value) + if err != nil || len(decoded) != 32 { + decoded, err = base64.StdEncoding.DecodeString(value) + } + if err != nil || len(decoded) != 32 { + return nil, fmt.Errorf("channel-id must encode exactly 32 " + + "bytes") + } + + return decoded, nil +} diff --git a/cmd/wavecli/waveclicommands/cmd_channel_test.go b/cmd/wavecli/waveclicommands/cmd_channel_test.go new file mode 100644 index 000000000..bb05bb2fd --- /dev/null +++ b/cmd/wavecli/waveclicommands/cmd_channel_test.go @@ -0,0 +1,228 @@ +package waveclicommands + +import ( + "context" + "encoding/base64" + "encoding/hex" + "strings" + "sync" + "testing" + + "github.com/lightninglabs/wavelength/rpc/arkchannelrpc" + "github.com/spf13/cobra" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type retryArkChannelClient struct { + arkchannelrpc.ArkChannelServiceClient + + mu sync.Mutex + requests []*arkchannelrpc.PromoteVTXORequest + errors []error +} + +// PromoteVTXO records retries and returns configured failures before success. +func (c *retryArkChannelClient) PromoteVTXO(_ context.Context, + req *arkchannelrpc.PromoteVTXORequest, _ ...grpc.CallOption) ( + *arkchannelrpc.PromoteVTXOResponse, error) { + + c.mu.Lock() + defer c.mu.Unlock() + + c.requests = append(c.requests, req) + if len(c.errors) > 0 { + err := c.errors[0] + c.errors = c.errors[1:] + + return nil, err + } + + return &arkchannelrpc.PromoteVTXOResponse{}, nil +} + +// TestParseChannelIDAcceptsCLIEncodings verifies command chaining works with +// both the protobuf JSON response and the canonical hexadecimal identifier. +func TestParseChannelIDAcceptsCLIEncodings(t *testing.T) { + t.Parallel() + + id := make([]byte, 32) + for i := range id { + id[i] = byte(i + 1) + } + + for _, encoded := range []string{ + hex.EncodeToString(id), base64.StdEncoding.EncodeToString(id), + } { + decoded, err := parseChannelID(encoded) + require.NoError(t, err) + require.Equal(t, id, decoded) + } +} + +// TestParseChannelIDRejectsWrongLength verifies malformed identifiers fail +// before the CLI opens a daemon connection. +func TestParseChannelIDRejectsWrongLength(t *testing.T) { + t.Parallel() + + _, err := parseChannelID(hex.EncodeToString(make([]byte, 31))) + require.ErrorContains(t, err, "exactly 32 bytes") +} + +// TestParsePositiveChannelAmount keeps channel creation's public input to one +// positive amount instead of exposing internal funding-policy switches. +func TestParsePositiveChannelAmount(t *testing.T) { + t.Parallel() + + amount, err := parsePositiveChannelAmount("200000") + require.NoError(t, err) + require.EqualValues(t, 200_000, amount) + + for _, value := range []string{"0", "-1", "one"} { + _, err := parsePositiveChannelAmount(value) + require.ErrorContains(t, err, "positive integer") + } +} + +// TestChannelMoneyCommandsRequireConfirmation verifies every command that +// changes wallet or channel balances stops before dialing without approval. +func TestChannelMoneyCommandsRequireConfirmation(t *testing.T) { + previous := stdinIsTTY + stdinIsTTY = func(*cobra.Command) bool { return false } + t.Cleanup(func() { + stdinIsTTY = previous + }) + + id := hex.EncodeToString(make([]byte, 32)) + tests := []struct { + name string + cmd *cobra.Command + args []string + }{ + { + name: "create", + cmd: newChannelCreateCmd(), + args: []string{ + "1000", + }, + }, + { + name: "pay", + cmd: newChannelPayCmd(), + args: []string{ + "lnbc1test", + }, + }, + { + name: "refresh", + cmd: newChannelRefreshCmd(), + args: []string{ + id, + }, + }, + { + name: "force close", + cmd: newChannelForceCloseCmd(), + args: []string{ + id, + }, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + test.cmd.SetIn(strings.NewReader("")) + err := test.cmd.RunE(test.cmd, test.args) + require.Error(t, err) + require.Equal( + t, ExitConfirmationRequired, ExitCodeFor(err), + ) + }) + } +} + +// TestChannelCommandRecoveryFlags verifies the create retry key, listing +// command, removed demo commands, and conservative fee default. +func TestChannelCommandRecoveryFlags(t *testing.T) { + t.Parallel() + + create := newChannelCreateCmd() + require.NotNil(t, create.Flags().Lookup("idempotency-key")) + require.NotNil(t, create.Flags().Lookup("yes")) + + root := newChannelCmd() + list, _, err := root.Find([]string{"list"}) + require.NoError(t, err) + require.Equal(t, "list", list.Name()) + refresh, _, err := root.Find([]string{"refresh"}) + require.NoError(t, err) + require.Equal(t, "refresh", refresh.Name()) + _, _, err = root.Find([]string{"close"}) + require.ErrorContains(t, err, "unknown command") + + for _, method := range []string{"send", "receive"} { + _, _, err := root.Find([]string{method}) + require.ErrorContains(t, err, "unknown command") + } + + pay := newChannelPayCmd() + maxFee, err := pay.Flags().GetUint64("max-fee-sat") + require.NoError(t, err) + require.Equal(t, uint64(1_000), maxFee) +} + +// TestNewChannelCreateKey verifies the default CLI path always supplies a +// compact non-empty daemon idempotency key. +func TestNewChannelCreateKey(t *testing.T) { + t.Parallel() + + first, err := newChannelCreateKey() + require.NoError(t, err) + second, err := newChannelCreateKey() + require.NoError(t, err) + require.True(t, strings.HasPrefix(first, channelCreateKeyPrefix)) + require.LessOrEqual(t, len(first), 128) + require.NotEqual(t, first, second) +} + +// TestPromoteVTXOWithRetryReusesRequest verifies a timed-out funding call is +// resumed with the exact same logical intent instead of minting another +// channel. +func TestPromoteVTXOWithRetryReusesRequest(t *testing.T) { + t.Parallel() + + client := &retryArkChannelClient{errors: []error{ + status.Error(codes.DeadlineExceeded, "still activating"), + }} + request := &arkchannelrpc.PromoteVTXORequest{ + AmountSat: 100_000, IdempotencyKey: "create-42", + } + response, err := promoteVTXOWithRetry( + &cobra.Command{}, client, request, + ) + require.NoError(t, err) + require.NotNil(t, response) + require.Len(t, client.requests, 2) + require.Same(t, client.requests[0], client.requests[1]) +} + +// TestPromoteVTXOWithRetryHonorsCancellation verifies an interrupted command +// returns its caller's cancellation instead of starting another RPC attempt. +func TestPromoteVTXOWithRetryHonorsCancellation(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithCancel(t.Context()) + cancel() + cmd := &cobra.Command{} + cmd.SetContext(ctx) + client := &retryArkChannelClient{errors: []error{ + status.Error(codes.Unavailable, "operator offline"), + }} + _, err := promoteVTXOWithRetry( + cmd, client, &arkchannelrpc.PromoteVTXORequest{ + AmountSat: 100_000, IdempotencyKey: "create-43", + }, + ) + require.ErrorIs(t, err, context.Canceled) +} diff --git a/cmd/wavecli/waveclicommands/devrpc/registry_generated.go b/cmd/wavecli/waveclicommands/devrpc/registry_generated.go index d5e59033c..a9485c7ff 100644 --- a/cmd/wavecli/waveclicommands/devrpc/registry_generated.go +++ b/cmd/wavecli/waveclicommands/devrpc/registry_generated.go @@ -135,6 +135,13 @@ func generatedRegistry() []serviceSpec { Output: "waverpc.GetIndexedOORSessionByTxidResponse", Comments: "GetIndexedOORSessionByTxid queries the authoritative indexer for one\nOOR session using a spent script proof and deterministic session txid.", }, + { + Name: "ExportOORRecoveryPackage", + Aliases: []string{"export-oor-recovery-package"}, + Input: "waverpc.ExportOORRecoveryPackageRequest", + Output: "waverpc.ExportOORRecoveryPackageResponse", + Comments: "ExportOORRecoveryPackage returns the immutable local OOR package and\nround ancestry for one exact output. The caller must already know the\noutput tuple; the daemon verifies it against its finalized artifacts.", + }, { Name: "SendVTXO", Aliases: []string{"send-vtxo"}, diff --git a/cmd/wavecli/waveclicommands/root.go b/cmd/wavecli/waveclicommands/root.go index 6a846ce57..2db51b283 100644 --- a/cmd/wavecli/waveclicommands/root.go +++ b/cmd/wavecli/waveclicommands/root.go @@ -25,8 +25,8 @@ const ( groupIntrospection = "introspection" groupAdvanced = "advanced" - // devModeEnvVar, when set to "1", reveals the advanced subtrees - // (ark / dev / recovery) under an Advanced group in --help. It only + // devModeEnvVar, when set to "1", reveals the advanced subtrees (ark / + // channel / dev / recovery) under an Advanced group in --help. It only // changes visibility; it never gates execution. devModeEnvVar = "WAVELENGTH_DEV" ) @@ -35,9 +35,9 @@ const ( // flags (--rpcserver, --timeout, --tlscertpath, --macaroonpath, --no-tls) are // registered here and made available to all subcommands via PersistentFlags. // -// The advanced subtrees (ark / dev / recovery) are hidden from the default -// --help unless WAVELENGTH_DEV=1 is set; execution is never gated on the env -// var. +// The advanced subtrees (ark / channel / dev / recovery) are hidden from the +// default --help unless WAVELENGTH_DEV=1 is set; execution is never gated on +// the env var. func NewRootCmd() *cobra.Command { return newRootCmd(os.Getenv(devModeEnvVar) == "1") } @@ -158,6 +158,7 @@ func newRootCmd(devMode bool) *cobra.Command { // on a GroupID naming a group that was never registered. advancedCmds := []*cobra.Command{ newArkCmd(), + newChannelCmd(), newRecoveryCmd(), devrpc.NewDevCmd( devrpc.Config{ diff --git a/cmd/wavecli/waveclicommands/root_groups_test.go b/cmd/wavecli/waveclicommands/root_groups_test.go index ddfb9b408..788c33f19 100644 --- a/cmd/wavecli/waveclicommands/root_groups_test.go +++ b/cmd/wavecli/waveclicommands/root_groups_test.go @@ -94,7 +94,7 @@ func TestAdvancedCommandsHiddenByDefault(t *testing.T) { t.Parallel() root := newRootCmd(false) - for _, name := range []string{"ark", "dev", "recovery"} { + for _, name := range []string{"ark", "channel", "dev", "recovery"} { sub := findRootCommand(t, root, name) require.Truef(t, sub.Hidden, "%q should be hidden", name) require.Emptyf( @@ -113,7 +113,7 @@ func TestAdvancedCommandsGroupedUnderDevMode(t *testing.T) { root := newRootCmd(true) require.Contains(t, rootGroupIDs(root), groupAdvanced) - for _, name := range []string{"ark", "dev", "recovery"} { + for _, name := range []string{"ark", "channel", "dev", "recovery"} { sub := findRootCommand(t, root, name) require.Falsef(t, sub.Hidden, "%q should be visible", name) require.Equalf( diff --git a/cmd/waved/main.go b/cmd/waved/main.go index 35457c721..e4875dd41 100644 --- a/cmd/waved/main.go +++ b/cmd/waved/main.go @@ -478,6 +478,15 @@ func registerSwapRuntimeFlags(f *pflag.FlagSet, cfg *waved.Config) { "swap.maxactivereceiveswaps", cfg.Swap.MaxActiveReceiveSwaps, "maximum accumulated receive workers in swapruntime builds", ) + f.Bool( + "swap.arkchannelsenabled", cfg.Swap.ArkChannelsEnabled, + "permit explicit Ark channel open, pay and receive operations", + ) + f.Bool( + "swap.disablearkchannelruntime", + cfg.Swap.SuppressArkChannelRuntime, + "disable Ark channel recovery (requires an empty inventory)", + ) f.Bool( "swap.vhtlcrecovery.autoescalate", cfg.Swap.VHTLCRecovery.AutoEscalate, "automatically "+ diff --git a/cmd/waved/main_test.go b/cmd/waved/main_test.go index 4dab4887c..e3e1ac88b 100644 --- a/cmd/waved/main_test.go +++ b/cmd/waved/main_test.go @@ -58,6 +58,61 @@ func TestReadConfigFileLoadsProperties(t *testing.T) { } } +// TestArkChannelReceiveFlagIsOptIn verifies direct channel receives stay off by +// default and can be enabled through the daemon's public flag surface. +func TestArkChannelReceiveFlagIsOptIn(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + flagValue string + want bool + }{ + { + name: "default disabled", + }, + { + name: "explicitly enabled", + flagValue: "true", + want: true, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + cfg := waved.DefaultConfig() + v := viper.New() + flags := pflag.NewFlagSet( + "waved-test", pflag.ContinueOnError, + ) + registerSwapRuntimeFlags(flags, cfg) + if err := v.BindPFlags(flags); err != nil { + t.Fatalf("bind swap flags: %v", err) + } + if test.flagValue != "" { + if err := flags.Set( + "swap.arkchannelsenabled", + test.flagValue, + ); err != nil { + + t.Fatalf("set channel receive flag: %v", + err) + } + } + if err := v.Unmarshal(cfg); err != nil { + t.Fatalf("unmarshal config: %v", err) + } + if cfg.Swap.ArkChannelsEnabled != test.want { + t.Fatalf("want channel receive "+ + "enabled=%v, got %v", test.want, + cfg.Swap.ArkChannelsEnabled) + } + }) + } +} + // TestReadConfigFileIgnoresMissingDefault checks that a missing default config // file does not block first startup. func TestReadConfigFileIgnoresMissingDefault(t *testing.T) { diff --git a/docs/daemon_cli_guide.md b/docs/daemon_cli_guide.md index 9a044ec70..1376b3e1a 100644 --- a/docs/daemon_cli_guide.md +++ b/docs/daemon_cli_guide.md @@ -153,6 +153,8 @@ waved \ | `--swap.serveraddress` | network default | Swap server address override for swapruntime builds | | `--swap.servertransport` | `grpc` | Swap server transport: `grpc` or `rest` | | `--maxpaymentcltv` | `480` in swap-enabled builds | Largest total Lightning payment CLTV reserved by automatic VTXO refresh; `0` disables the payment reserve | +| `--swap.arkchannelsenabled` | `false` | Permit explicit channel open and pay; ordinary send and receive are unchanged | +| `--swap.disablearkchannelruntime` | `false` | Disable protection only if the local recovery inventory is readable and empty | Empty Ark and swap addresses resolve from the selected network and transport. See [signet.md](signet.md) for the testnet3, testnet4, and signet endpoints and @@ -322,11 +324,10 @@ alias wave='wavecli --no-tls --no-macaroons' ### Command tree The everyday wallet verbs and daemon introspection make up the default -`--help` face. The advanced `ark`, `recovery`, and `dev` subtrees are +`--help` face. The advanced `ark`, `channel`, `recovery`, and `dev` subtrees are hidden from `--help` (set `WAVELENGTH_DEV=1` to reveal them under an "Advanced" -group) but stay fully runnable in every build — `wavecli ark …` works -with or without the env var. `WAVELENGTH_DEV` only changes visibility; it never -gates execution. +group) but stay fully runnable in every build. `WAVELENGTH_DEV` only changes +visibility; it never gates execution. The `swap` subtree was retired — `send`/`recv --offchain` and `activity` cover it, and a stale `wavecli swap …` fails with a hint toward @@ -355,6 +356,10 @@ wavecli │ ├── sweep [list] — broadcast requires approval │ ├── fees {estimate|history} │ └── listtransactions +├── channel — Ark-backed native Lightning channels (hidden) +│ ├── create / get +│ ├── send / receive / pay +│ └── close / force-close ├── recovery {list|status|escalate|cancel} — daemon-owned vHTLC recovery rows (hidden) └── dev — generated low-level RPC (hidden; no wavewalletrpc) └── daemon — call any waverpc.DaemonService method @@ -513,6 +518,28 @@ claimed. Retrying returns the same claim. wavecli dev daemon claim-asset-deposit --request-id alice-1 ``` +### `channel` (development) + +Promote wallet VTXO value into an unpublished native Lightning channel, use it +for public Lightning payments, and either refresh it inside Ark or materialize +and force-close it on chain. +Creation intentionally takes only the desired channel capacity; the daemon +owns OOR preparation, backing reserve, private-channel policy, and activation. +Channel IDs accept either the base64 value printed by protobuf JSON or 32-byte +hex. + +```bash +wavecli channel create 100000 +wavecli channel get +wavecli channel pay --max-fee-sat 1000 +wavecli channel refresh +wavecli channel force-close +``` + +Opening a channel and paying through it require `--swap.arkchannelsenabled`. +An ordinary `recv --offchain --amt ` settles into the wallet and +does not open a channel. To fund one, use `wavecli channel create `. + ### `ark board` / `dev daemon Board` Trigger the client to join the next round with any confirmed boarding diff --git a/go.mod b/go.mod index 39ddde8c6..ed6606eae 100644 --- a/go.mod +++ b/go.mod @@ -17,6 +17,7 @@ require ( github.com/btcsuite/btcd/psbt/v2 v2.0.0 github.com/btcsuite/btcd/txscript/v2 v2.0.0 github.com/btcsuite/btcd/wire/v2 v2.0.0 + github.com/btcsuite/btclog v1.0.0 github.com/btcsuite/btclog/v2 v2.0.1-0.20250728225537-6090e87c6c5b github.com/btcsuite/btcwallet v0.18.1 github.com/btcsuite/btcwallet/wallet/txrules v1.3.0 @@ -87,7 +88,6 @@ require ( github.com/beorn7/perks v1.0.1 // indirect github.com/btcsuite/btcd/btcutil v1.2.0 // indirect github.com/btcsuite/btcd/v2transport v1.0.1 // indirect - github.com/btcsuite/btclog v1.0.0 // indirect github.com/btcsuite/btcwallet/wallet/txauthor v1.4.0 // indirect github.com/btcsuite/btcwallet/wallet/txsizes v1.3.0 // indirect github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd // indirect diff --git a/harness/AGENTS.md b/harness/AGENTS.md index 194cfb624..c00642215 100644 --- a/harness/AGENTS.md +++ b/harness/AGENTS.md @@ -68,6 +68,10 @@ helpers for end-to-end tests. branches, incomplete custom-account reconstruction, and spending restored default-account coins. The custom fixture is watch-only because the pinned image predates native custom-account creation. +- `SetupChannelBetween` explicitly opens announced channels + (`Private: false`). Multi-node tests need the link in the public graph, + and spelling out the setting prevents an lnd default change from making + those routes private. - Container teardown (`Stop`) is guarded by `sync.Once`; a signal handler also calls `Stop` as a safety net against orphaned containers. - `Stop` kills and then removes every harness container, including diff --git a/harness/CLAUDE.md b/harness/CLAUDE.md index 194cfb624..c00642215 100644 --- a/harness/CLAUDE.md +++ b/harness/CLAUDE.md @@ -68,6 +68,10 @@ helpers for end-to-end tests. branches, incomplete custom-account reconstruction, and spending restored default-account coins. The custom fixture is watch-only because the pinned image predates native custom-account creation. +- `SetupChannelBetween` explicitly opens announced channels + (`Private: false`). Multi-node tests need the link in the public graph, + and spelling out the setting prevents an lnd default change from making + those routes private. - Container teardown (`Stop`) is guarded by `sync.Once`; a signal handler also calls `Stop` as a safety net against orphaned containers. - `Stop` kills and then removes every harness container, including diff --git a/harness/harness.go b/harness/harness.go index a77c78da6..5bd73431b 100644 --- a/harness/harness.go +++ b/harness/harness.go @@ -324,6 +324,10 @@ type Options struct { // Additional nodes continue to use LNDImage. PrimaryLNDImage string + // PrimaryLNDExtraArgs configures only the primary node, for cases + // that depend on an opt-in lnd capability. + PrimaryLNDExtraArgs []string + // LNDRequireInterceptor, when true, starts the main lnd node with // --requireinterceptor so held HTLCs are retained on interceptor // disconnect and replayed on reconnect, rather than resumed and failed. @@ -2353,9 +2357,9 @@ func (h *Harness) bitcoindSendToAddress(address string, amount float64) string { // startLND launches an lnd container and waits until its gRPC is responsive // and TLS cert and admin macaroon are available. func (h *Harness) startLND() *LndInstance { - inst := h.startLNDInstance( + inst := h.startLNDInstanceWithOptions( "lnd", h.lndDataDir, h.opts.LNDRequireInterceptor, - LNDChainBackendBitcoind, + LNDChainBackendBitcoind, false, h.opts.PrimaryLNDExtraArgs, ) h.lnd = inst.Resource h.LNDGRPCPort = inst.GRPCPort @@ -2366,14 +2370,6 @@ func (h *Harness) startLND() *LndInstance { return inst } -func (h *Harness) startLNDInstance(name, dataDir string, - requireInterceptor bool, chainBackend string) *LndInstance { - - return h.startLNDInstanceWithOptions( - name, dataDir, requireInterceptor, chainBackend, false, nil, - ) -} - // startLNDInstanceWithOptions starts an lnd container whose wallet can either // use the harness's automatic seed or be initialized explicitly by the caller. func (h *Harness) startLNDInstanceWithOptions(name, dataDir string, @@ -2865,6 +2861,7 @@ func (h *Harness) SetupChannelBetween(local *LndInstance, peer *LndInstance, NodePubkey: peerInfo.IdentityPubkey[:], LocalFundingAmount: capacitySat, PushSat: pushAmt, + Private: false, }) require.NoError( t, err, "OpenChannel failed for %s -> %s", local.Name, diff --git a/rpc/restclient/clients.go b/rpc/restclient/clients.go index 908cb6f23..441209286 100644 --- a/rpc/restclient/clients.go +++ b/rpc/restclient/clients.go @@ -547,6 +547,20 @@ func (c *DaemonServiceClient) GetIndexedOORSessionByTxid(ctx context.Context, return out, err } +// ExportOORRecoveryPackage returns immutable recovery data for one exact OOR +// output created by this daemon. +func (c *DaemonServiceClient) ExportOORRecoveryPackage(ctx context.Context, + in *waverpc.ExportOORRecoveryPackageRequest, _ ...grpc.CallOption) ( + *waverpc.ExportOORRecoveryPackageResponse, error) { + + out := new(waverpc.ExportOORRecoveryPackageResponse) + err := c.client.Post( + ctx, "/v1/daemon/export-oor-recovery-package", in, out, + ) + + return out, err +} + // SendVTXO initiates an in-round VTXO transfer. func (c *DaemonServiceClient) SendVTXO(ctx context.Context, in *waverpc.SendVTXORequest, _ ...grpc.CallOption) ( diff --git a/sample-waved.conf b/sample-waved.conf index e01c8223e..46c66f442 100644 --- a/sample-waved.conf +++ b/sample-waved.conf @@ -298,6 +298,13 @@ # Maximum accumulated receive-swap workers, including restart recovery. # swap.maxactivereceiveswaps=128 +# Permit explicit channel open, pay and receive. Ordinary send and receive +# never select this rail. A fresh wallet stays idle until an explicit open. +# swap.arkchannelsenabled=false + +# Disable channel protection only with an empty, readable inventory. +# swap.disablearkchannelruntime=false + # Automatically escalate armed vHTLC recovery after the grace/deadline policy # says cooperative retry is no longer safe or useful. The default is false: # recovery is armed durably, but an operator must run a manual escalation command diff --git a/swapclientserver/service.go b/swapclientserver/service.go index 1a5985029..2e488817f 100644 --- a/swapclientserver/service.go +++ b/swapclientserver/service.go @@ -731,9 +731,13 @@ func newSwapClientService(ctx context.Context, rpcServer *waved.RPCServer, workerRetryDelay: defaultWorkerRetryDelay, } service.pendingReceiveSet = make(map[string]struct{}) + releaseArkChannelMailbox := bindArkChannelMailbox( + cfg, swapClients.mailbox, + ) cleanup := func() { service.stopWorkers() + releaseArkChannelMailbox() _ = arkClient.Close() _ = swapClients.server.Close() _ = swapClients.cleanup() @@ -743,6 +747,21 @@ func newSwapClientService(ctx context.Context, rpcServer *waved.RPCServer, return service, cleanup, nil } +// bindArkChannelMailbox publishes the authenticated swap-server transport for +// the daemon-owned channel process and returns its matching release function. +func bindArkChannelMailbox(cfg *waved.SwapConfig, + client mailboxpb.MailboxServiceClient) func() { + + if cfg.SuppressArkChannelRuntime { + client = nil + } + cfg.ArkChannelMailbox = client + + return func() { + cfg.ArkChannelMailbox = nil + } +} + // swapStoreDatabasePath returns the daemon-owned swap store path. By default it // follows the network-scoped daemon DB directory so a network DB reset also // clears wallet activity derived from persisted swap sessions. diff --git a/swapclientserver/service_test.go b/swapclientserver/service_test.go index 2d2653a99..8342dd9bb 100644 --- a/swapclientserver/service_test.go +++ b/swapclientserver/service_test.go @@ -1348,6 +1348,20 @@ func TestNewSwapClientServiceRequiresRecoveryPreimageRegistry(t *testing.T) { require.Nil(t, cleanup) } +// TestBindArkChannelMailbox verifies the swap subserver publishes its +// authenticated mailbox for the channel process for exactly its own lifetime. +func TestBindArkChannelMailbox(t *testing.T) { + t.Parallel() + + cfg := &waved.SwapConfig{} + client := mailboxpb.NewMailboxServiceClient(nil) + release := bindArkChannelMailbox(cfg, client) + require.Equal(t, client, cfg.ArkChannelMailbox) + + release() + require.Nil(t, cfg.ArkChannelMailbox) +} + // TestDaemonWithLiveOperatorKeyUsesLiveFetcher verifies the daemon-hosted swap // runtime bypasses the Ark SDK facade's cached operator key. func TestDaemonWithLiveOperatorKeyUsesLiveFetcher(t *testing.T) { diff --git a/waved/AGENTS.md b/waved/AGENTS.md index 2675f89d4..0eb27cb17 100644 --- a/waved/AGENTS.md +++ b/waved/AGENTS.md @@ -18,7 +18,9 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/waved.= + defaultArkChannelPrePONRTimeout +} diff --git a/waved/ark_channel_expiry_test.go b/waved/ark_channel_expiry_test.go new file mode 100644 index 000000000..6d59ebb24 --- /dev/null +++ b/waved/ark_channel_expiry_test.go @@ -0,0 +1,225 @@ +package waved + +import ( + "bytes" + "context" + "testing" + "time" + + "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/btcsuite/btclog/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/arkchannel/oorbridge" + "github.com/lightninglabs/wavelength/db" + "github.com/lightningnetwork/lnd/clock" + "github.com/lightningnetwork/lnd/lnwire" + "github.com/stretchr/testify/require" +) + +// testPrePONROORController returns one configured abort result. +type testPrePONROORController struct { + aborts int + result oorbridge.TerminalResult +} + +// ValidatePreparedOOR accepts a fixture already validated by the FSM. +func (*testPrePONROORController) ValidatePreparedOOR(context.Context, + arkchannel.Terms, arkchannel.VTXOBinding) error { + + return nil +} + +// AbortPreparedOORResult records one definitive pre-PONR abort. +func (c *testPrePONROORController) AbortPreparedOORResult(context.Context, + arkchannel.ID, arkchannel.Terms, arkchannel.VTXOBinding, string) ( + oorbridge.TerminalResult, error) { + + c.aborts++ + + return c.result, nil +} + +// TestMaintainPrePONRExpiresAbsentPreparation proves an armed request releases +// its durable FSM reservation without selecting replacement wallet inputs. +func TestMaintainPrePONRExpiresAbsentPreparation(t *testing.T) { + t.Parallel() + + now := time.Unix(10_000, 0).UTC() + controller, coordinator, terms, closeStore := testPrePONRController( + t, now, oorbridge.PreparationLookup{ + Status: oorbridge.PreparationAbsent, + }, + ) + defer closeStore() + + record, err := coordinator.Request(t.Context(), terms) + require.NoError(t, err) + _, _, err = coordinator.Apply( + t.Context(), terms.ID, &arkchannel.OORPreparationStarted{}, + ) + require.NoError(t, err) + require.True(t, record.PrePONRStartedAt.IsZero()) + + err = controller.maintainPrePONRChannels( + t.Context(), nil, now.Add(defaultArkChannelPrePONRTimeout), + ) + require.NoError(t, err) + record, err = coordinator.Get(t.Context(), terms.ID) + require.NoError(t, err) + require.Equal(t, arkchannel.PhaseFailed, record.Snapshot.Phase) + require.Equal(t, arkChannelPrePONRExpiryReason, + record.Snapshot.Failure) +} + +// TestMaintainPrePONRRecoversThenAbortsPreparedOOR proves restart maintenance +// binds the deterministic winner before recording its authoritative abort. +func TestMaintainPrePONRRecoversThenAbortsPreparedOOR(t *testing.T) { + t.Parallel() + + now := time.Unix(20_000, 0).UTC() + terms := testPrePONRTerms(t) + binding := testPrePONRBinding(t, terms) + controller, coordinator, _, closeStore := testPrePONRController( + t, now, oorbridge.PreparationLookup{ + Status: oorbridge.PreparationPrepared, Binding: binding, + }, + ) + defer closeStore() + resultController, ok := + controller.prePONROOR.(*testPrePONROORController) + require.True(t, ok) + + _, err := coordinator.Request(t.Context(), terms) + require.NoError(t, err) + _, _, err = coordinator.Apply( + t.Context(), terms.ID, &arkchannel.OORPreparationStarted{}, + ) + require.NoError(t, err) + + err = controller.maintainPrePONRChannels( + t.Context(), nil, now.Add(defaultArkChannelPrePONRTimeout), + ) + require.NoError(t, err) + record, err := coordinator.Get(t.Context(), terms.ID) + require.NoError(t, err) + require.Equal(t, arkchannel.PhaseCancelling, record.Snapshot.Phase) + require.NotNil(t, record.Snapshot.Source) + require.True(t, record.Snapshot.OORAborted) + require.Equal(t, 1, resultController.aborts) +} + +// testPrePONRController constructs a SQL-backed coordinator at a stable time. +func testPrePONRController(t *testing.T, now time.Time, + lookup oorbridge.PreparationLookup) (*NativeArkChannelController, + *arkchannel.Coordinator, arkchannel.Terms, func()) { + + t.Helper() + raw, err := db.NewStoreFromConfig( + db.DefaultConfig( + t.TempDir(), + ), + btclog.Disabled, + ) + require.NoError(t, err) + testClock := clock.NewTestClock(now) + channelStore := raw.NewArkChannelStore(testClock) + coordinator, err := arkchannel.NewCoordinator(channelStore) + require.NoError(t, err) + resultController := &testPrePONROORController{ + result: oorbridge.TerminalResult{ + Aborted: true, Reason: arkChannelPrePONRExpiryReason, + }, + } + controller := &NativeArkChannelController{ + party: arkchannel.PartyClient, + prePONROOR: resultController, + cfg: ArkChannelControllerConfig{ + LookupOOR: func(context.Context, arkchannel.Terms, + btcutil.Amount) (oorbridge.PreparationLookup, + error) { + + return lookup, nil + }, + Clock: testClock, Log: btclog.Disabled, + }, + coordinator: coordinator, + } + + return controller, coordinator, testPrePONRTerms(t), func() { + require.NoError(t, raw.Close()) + } +} + +// testPrePONRTerms creates valid client-funded promotion terms. +func testPrePONRTerms(t *testing.T) arkchannel.Terms { + t.Helper() + + newKey := func() [33]byte { + privateKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + var key [33]byte + copy(key[:], privateKey.PubKey().SerializeCompressed()) + + return key + } + + return 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_000, TxIndex: 1, + }.ToUint64(), + Capacity: 100_000, + ClientNodeKey: newKey(), + HubNodeKey: newKey(), + VTXO: arkchannel.VTXOTerms{ + ClientArkKey: newKey(), HubArkKey: newKey(), + ArkOperatorKey: newKey(), ClientChannelKey: newKey(), + HubChannelKey: newKey(), FunderKey: newKey(), + ChannelDelay: 144, FunderDelay: 576, MinExitDelay: 144, + }, + } +} + +// testPrePONRBinding creates the exact prepared channel-policy output. +func testPrePONRBinding(t *testing.T, + terms arkchannel.Terms) arkchannel.VTXOBinding { + + t.Helper() + policy, pkScript, err := terms.VTXO.Artifacts() + require.NoError(t, err) + tx := wire.NewMsgTx(2) + tx.AddTxIn(&wire.TxIn{PreviousOutPoint: wire.OutPoint{ + Hash: chainhash.Hash{10}, + }}) + tx.AddTxOut(&wire.TxOut{Value: int64( + terms.Capacity + arkchannel.DefaultBackingFee, + ), PkScript: pkScript}) + var raw bytes.Buffer + require.NoError(t, tx.Serialize(&raw)) + sessionID := [32]byte(tx.TxHash()) + + return arkchannel.VTXOBinding{ + OORSessionID: sessionID, + OutPoint: wire.OutPoint{ + Hash: chainhash.Hash(sessionID), + }, + Amount: terms.Capacity + arkchannel.DefaultBackingFee, + ArkTransaction: raw.Bytes(), PolicyTemplate: policy, + PkScript: pkScript, + } +} + +var _ prePONRResultController = (*testPrePONROORController)(nil) diff --git a/waved/ark_channel_funding_admission.go b/waved/ark_channel_funding_admission.go new file mode 100644 index 000000000..6b1bbf882 --- /dev/null +++ b/waved/ark_channel_funding_admission.go @@ -0,0 +1,125 @@ +package waved + +import ( + "context" + "fmt" + "maps" + "slices" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/lib/recovery" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" + "github.com/lightninglabs/wavelength/oor" + "github.com/lightninglabs/wavelength/unroll" +) + +// validatePreparedChannelSource bounds the negotiated exit before committing +// wallet inputs. Witnesses are installed later; signatures cannot change +// these transactions' outpoints, sequences or lock times. +func (s *Server) validatePreparedChannelSource(ctx context.Context, + terms arkchannel.Terms, source arkchannel.VTXOBinding, + prepared *oor.Prepared) error { + + height, err := s.channelSourceAdmissionHeight( + ctx, terms, prepared.TransferInputs, + ) + if err != nil { + return err + } + if s.channelFundingProofs == nil { + return fmt.Errorf("channel funding proof assembler unavailable") + } + proof, err := projectChannelFundingProof( + ctx, s.channelFundingProofs, source.OutPoint, + terms.VTXO.ChannelDelay, prepared, + ) + if err != nil { + return err + } + if err := validateArkChannelRecoveryWindow( + proof, terms.VTXO.FunderDelay, height, + ); err != nil { + return fmt.Errorf("%w: %w", arkchannel.ErrSourceInadmissible, + err) + } + + return nil +} + +// projectChannelFundingProof extends the wallet inputs' existing recovery +// proofs with the exact prepared checkpoints and the policy output. It never +// stores an unsigned projection as exit material. +func projectChannelFundingProof(ctx context.Context, + assembler unroll.ProofAssembler, target wire.OutPoint, delay uint32, + prepared *oor.Prepared) (*recovery.Proof, error) { + + pkg, err := oortx.ValidateSubmitPackage( + prepared.ArkPSBT, prepared.CheckpointPSBTs, + ) + if err != nil { + return nil, fmt.Errorf("invalid prepared channel transfer: %w", + err) + } + if pkg.ArkTxid != target.Hash { + return nil, fmt.Errorf("prepared transfer does not create " + + "channel source") + } + selected := make( + map[wire.OutPoint]struct{}, len(prepared.TransferInputs), + ) + for _, input := range prepared.TransferInputs { + if input.VTXO == nil { + return nil, fmt.Errorf("missing channel funding input") + } + selected[input.VTXO.Outpoint] = struct{}{} + } + nodes := make(map[chainhash.Hash]*recovery.Node) + for _, checkpoint := range prepared.CheckpointPSBTs { + tx := checkpoint.UnsignedTx + for _, in := range tx.TxIn { + out := in.PreviousOutPoint + if _, ok := selected[out]; !ok { + return nil, fmt.Errorf("unexpected channel "+ + "funding input %s", out) + } + delete(selected, out) + proof, err := assembler.EnsureProof(ctx, out) + if err != nil { + return nil, fmt.Errorf("resolve funding input "+ + "%s: %w", out, err) + } + for _, layer := range proof.Layers() { + for _, id := range layer { + nodes[id], _ = proof.Node(id) + } + } + } + nodes[tx.TxHash()] = &recovery.Node{ + Kind: recovery.NodeKindCheckpoint, + Tx: tx, + } + } + if len(selected) != 0 { + return nil, fmt.Errorf("prepared checkpoints omit channel " + + "funding inputs") + } + nodes[target.Hash] = &recovery.Node{ + Kind: recovery.NodeKindArk, + Tx: prepared.ArkPSBT.UnsignedTx, + } + + projected, err := recovery.NewProof( + target, delay, slices.Collect(maps.Values(nodes))..., + ) + if err != nil { + + // The complete set of immutable inputs was available. Retrying + // this same transfer cannot change a structural proof limit. + return nil, fmt.Errorf("%w: %w", + arkchannel.ErrSourceInadmissible, err) + } + + return projected, nil +} diff --git a/waved/ark_channel_oor.go b/waved/ark_channel_oor.go new file mode 100644 index 000000000..e5bbb7498 --- /dev/null +++ b/waved/ark_channel_oor.go @@ -0,0 +1,402 @@ +package waved + +import ( + "context" + "errors" + "fmt" + "math" + "time" + + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/arkchannel/oorbridge" + "github.com/lightninglabs/wavelength/lib/arkscript" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" + "github.com/lightninglabs/wavelength/oor" + "github.com/lightninglabs/wavelength/wallet" +) + +// newArkChannelOORController binds live source admission to every daemon-owned +// funding controller. Post-commit reconciliation does not invoke the guard. +func (s *Server) newArkChannelOORController() (*oorbridge.Controller, error) { + controller, err := oorbridge.New(s.actorSystem) + if err != nil { + return nil, err + } + controller.SetPreparedSourceValidator( + s.validatePreparedChannelSource, + ) + + return controller, nil +} + +// lookupArkChannelOOR reconciles one deterministic channel transfer without +// selecting or locking fresh VTXOs. Startup maintenance must use this path. +func (s *Server) lookupArkChannelOOR(ctx context.Context, + terms arkchannel.Terms, backingFee btcutil.Amount) ( + oorbridge.PreparationLookup, error) { + + controller, err := s.newArkChannelOORController() + if err != nil { + return oorbridge.PreparationLookup{}, err + } + + return controller.LookupChannelPreparation(ctx, terms, backingFee) +} + +// prepareArkChannelOOR reserves ordinary wallet VTXOs and prepares the exact +// transfer that creates one channel-policy VTXO. The channel FSM commits or +// aborts the prepared OOR after native lnd funding reaches its durable gate. +// +//nolint:funlen // Reservation cleanup stays paired with funding admission. +func (s *Server) prepareArkChannelOOR(ctx context.Context, + terms arkchannel.Terms, backingFee btcutil.Amount) ( + arkchannel.VTXOBinding, error) { + + if !s.walletRef.IsSome() { + return arkchannel.VTXOBinding{}, fmt.Errorf("Ark channel " + + "wallet actor is not initialized") + } + if s.vtxoStore == nil { + return arkchannel.VTXOBinding{}, fmt.Errorf("Ark channel " + + "VTXO store is not initialized") + } + if backingFee <= 0 || terms.Capacity > + btcutil.Amount(math.MaxInt64)-backingFee { + return arkchannel.VTXOBinding{}, fmt.Errorf("invalid Ark " + + "channel backing amount") + } + controller, err := s.newArkChannelOORController() + if err != nil { + return arkchannel.VTXOBinding{}, err + } + recovered, found, err := controller.LookupPreparedChannel( + ctx, terms, backingFee, + ) + if err != nil { + return arkchannel.VTXOBinding{}, err + } + if found { + return recovered, nil + } + operatorTerms, err := s.fetchOperatorTerms(ctx) + if err != nil { + return arkchannel.VTXOBinding{}, err + } + target := terms.Capacity + backingFee + walletRef := s.walletRef.UnsafeFromSome() + result := walletRef.Ask(ctx, &wallet.SelectAndLockVTXOsRequest{ + TargetAmount: target, + MinChangeAmount: operatorTerms.MinVTXOAmountFloor(), + }).Await(ctx) + response, err := result.Unpack() + if err != nil { + return arkchannel.VTXOBinding{}, fmt.Errorf("select Ark "+ + "channel VTXOs: %w", err) + } + locked, ok := response.(*wallet.SelectAndLockVTXOsResponse) + if !ok { + return arkchannel.VTXOBinding{}, fmt.Errorf("unexpected VTXO "+ + "selection response %T", response) + } + rpcServer := &RPCServer{server: s} + fail := func(err error) (arkchannel.VTXOBinding, error) { + unlockArkChannelSelectedVTXOs(ctx, rpcServer, locked) + + return arkchannel.VTXOBinding{}, err + } + + outpoints := make([]wire.OutPoint, 0, len(locked.SelectedVTXOs)) + reserveEpochs := make( + map[wire.OutPoint]uint64, len(locked.SelectedVTXOs), + ) + for _, selected := range locked.SelectedVTXOs { + outpoints = append(outpoints, selected.Outpoint) + reserveEpochs[selected.Outpoint] = selected.ReserveEpoch + } + inputs, err := BuildTransferInputs(ctx, s.vtxoStore, outpoints) + if err != nil { + return fail(fmt.Errorf("build Ark channel inputs: %w", err)) + } + // A replayed abort must name this selection's reservation, not release + // a newer owner that reserved the same outpoint after a failed commit. + applyReserveEpochs(inputs, reserveEpochs) + + if err := s.validateArkChannelSourceLifetime( + ctx, terms, inputs, + ); err != nil { + return fail(err) + } + inputTotal, err := sumOORInputAmounts(inputs) + if err != nil { + return fail(fmt.Errorf("sum Ark channel inputs: %w", err)) + } + if inputTotal < target { + return fail( + fmt.Errorf("selected Ark channel inputs total "+ + "%d, need %d", inputTotal, target), + ) + } + + var changeOutput *oortx.RecipientOutput + change := inputTotal - target + if change > 0 { + if change < operatorTerms.MinVTXOAmountFloor() { + return fail( + fmt.Errorf("Ark channel change %d is below "+ + "the VTXO floor", change), + ) + } + output, err := rpcServer.buildOORChangeRecipient( + ctx, operatorTerms.PubKey, operatorTerms.VTXOExitDelay, + change, + ) + if err != nil { + return fail(err) + } + changeOutput = &output + } + + prepared, err := controller.PrepareChannel( + ctx, oorbridge.PrepareRequest{ + Terms: terms, + CheckpointPolicy: arkscript.CheckpointPolicy{ + OperatorKey: operatorTerms.PubKey, + CSVDelay: operatorTerms.VTXOExitDelay, + }, + Inputs: inputs, + BackingFee: backingFee, + ChangeOutput: changeOutput, + }, + ) + if err != nil { + if errors.Is(err, arkchannel.ErrOORPreparationAmbiguous) { + lookupCtx, cancel := context.WithTimeout( + context.WithoutCancel(ctx), + submittedOORUnlockTimeout, + ) + lookup, lookupErr := + controller.LookupChannelPreparation( + lookupCtx, terms, backingFee, + ) + cancel() + if lookupErr != nil { + s.reconcileArkChannelPreparation( + ctx, controller, terms, backingFee, + locked, outpoints, + ) + + return arkchannel.VTXOBinding{}, errors.Join( + err, lookupErr, + ) + } + + switch lookup.Status { + case oorbridge.PreparationAbsent: + return fail(err) + + case oorbridge.PreparationPrepared: + if !sameChannelPreparationInputs( + lookup.InputOutpoints, outpoints, + ) { + + unlockArkChannelSelectedVTXOs( + ctx, rpcServer, locked, + ) + } + + return lookup.Binding, nil + + case oorbridge.PreparationPending: + s.reconcileArkChannelPreparation( + ctx, controller, terms, backingFee, + locked, outpoints, + ) + + return arkchannel.VTXOBinding{}, err + + case oorbridge.PreparationAccepted: + if len(lookup.InputOutpoints) > 0 && + !sameChannelPreparationInputs( + lookup.InputOutpoints, + outpoints, + ) { + + unlockArkChannelSelectedVTXOs( + ctx, rpcServer, locked, + ) + } + + return arkchannel.VTXOBinding{}, err + } + } + + return fail(err) + } + if prepared.Existing { + unlockArkChannelSelectedVTXOs(ctx, rpcServer, locked) + } + + return prepared.Binding, nil +} + +// validateArkChannelSourceLifetime admits only inputs whose earliest batch +// expiry leaves the native runtime's full materialization allowance and safety +// margin. Durable signing snapshots omit batch expiry, so admission reloads +// each exact input from the VTXO store and reads the current backend tip. +func (s *Server) validateArkChannelSourceLifetime(ctx context.Context, + terms arkchannel.Terms, inputs []oor.TransferInput) error { + + _, err := s.channelSourceAdmissionHeight(ctx, terms, inputs) + + return err +} + +// channelSourceAdmissionHeight uses the same tip for source expiry and the +// projected exit's absolute timelocks. +func (s *Server) channelSourceAdmissionHeight(ctx context.Context, + terms arkchannel.Terms, inputs []oor.TransferInput) (int32, error) { + + if len(inputs) == 0 { + return 0, fmt.Errorf("Ark channel source inputs are required") + } + if s.vtxoStore == nil { + return 0, fmt.Errorf("Ark channel source VTXO store is " + + "required") + } + expiry := int32(math.MaxInt32) + for _, input := range inputs { + if input.VTXO == nil { + return 0, fmt.Errorf("Ark channel source VTXO is " + + "required") + } + saved, err := s.vtxoStore.GetVTXO(ctx, input.VTXO.Outpoint) + if err != nil { + return 0, fmt.Errorf("load Ark channel source %s: %w", + input.VTXO.Outpoint, err) + } + expiry = min(expiry, saved.BatchExpiry) + } + if s.chainBackend == nil { + return 0, fmt.Errorf("Ark channel source chain backend is " + + "required") + } + height, _, err := s.chainBackend.BestBlock(ctx) + if err != nil { + return 0, fmt.Errorf("Ark channel source best block: %w", err) + } + if err := arkchannel.ValidateSourceLifetime( + expiry, height, terms.VTXO.FunderDelay, + ); err != nil { + return 0, fmt.Errorf("Ark channel source lifetime: %w", err) + } + + return height, nil +} + +// unlockArkChannelSelectedVTXOs releases a losing selection even after the +// request that created it has been canceled. +func unlockArkChannelSelectedVTXOs(ctx context.Context, rpcServer *RPCServer, + locked *wallet.SelectAndLockVTXOsResponse) { + + unlockCtx, cancel := context.WithTimeout( + context.WithoutCancel(ctx), submittedOORUnlockTimeout, + ) + defer cancel() + + rpcServer.unlockSelectedVTXOsBestEffort(unlockCtx, locked) +} + +// reconcileArkChannelPreparation owns a canceled caller's selected locks until +// the registry proves either a durable owner or a failed/no-session admission. +func (s *Server) reconcileArkChannelPreparation(ctx context.Context, + controller *oorbridge.Controller, terms arkchannel.Terms, + backingFee btcutil.Amount, locked *wallet.SelectAndLockVTXOsResponse, + selected []wire.OutPoint) { + + rpcServer := &RPCServer{server: s} + unlockVTXOs := rpcServer.unlockSelectedVTXOsBestEffort + cleanupCtx, cancel := context.WithTimeout( + context.WithoutCancel(ctx), submittedOORCleanupTimeout, + ) + go func() { + defer cancel() + + ticker := time.NewTicker(50 * time.Millisecond) + defer ticker.Stop() + for { + lookup, err := controller.LookupChannelPreparation( + cleanupCtx, terms, backingFee, + ) + if err == nil { + switch lookup.Status { + case oorbridge.PreparationAbsent: + unlockVTXOs( + cleanupCtx, locked, + ) + + return + + case oorbridge.PreparationPending: + // The accepted registry request may + // still create the durable session that + // owns these locks. + + case oorbridge.PreparationPrepared: + if !sameChannelPreparationInputs( + lookup.InputOutpoints, selected, + ) { + + unlockVTXOs( + cleanupCtx, locked, + ) + } + + return + + case oorbridge.PreparationAccepted: + if len(lookup.InputOutpoints) > 0 && + !sameChannelPreparationInputs( + lookup.InputOutpoints, + selected, + ) { + + unlockVTXOs( + cleanupCtx, locked, + ) + } + + return + } + } + + select { + case <-cleanupCtx.Done(): + return + + case <-ticker.C: + } + } + }() +} + +// sameChannelPreparationInputs compares selections as sets so an idempotent +// winner with different inputs cannot retain a retry's fresh wallet locks. +func sameChannelPreparationInputs(first, second []wire.OutPoint) bool { + if len(first) != len(second) { + return false + } + counts := make(map[wire.OutPoint]int, len(first)) + for _, outpoint := range first { + counts[outpoint]++ + } + for _, outpoint := range second { + if counts[outpoint] == 0 { + return false + } + counts[outpoint]-- + } + + return true +} diff --git a/waved/ark_channel_oor_lifetime_test.go b/waved/ark_channel_oor_lifetime_test.go new file mode 100644 index 000000000..d5fca3d3b --- /dev/null +++ b/waved/ark_channel_oor_lifetime_test.go @@ -0,0 +1,395 @@ +package waved + +import ( + "bytes" + "context" + "fmt" + "math" + "slices" + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/chainsource" + "github.com/lightninglabs/wavelength/lib/arkscript" + "github.com/lightninglabs/wavelength/lib/recovery" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" + "github.com/lightninglabs/wavelength/oor" + "github.com/lightninglabs/wavelength/vtxo" + "github.com/stretchr/testify/require" +) + +// sourceLifetimeBackend returns a live tip independently of serialized inputs. +type sourceLifetimeBackend struct { + chainsource.ChainBackend + height int32 + err error + calls int +} + +// BestBlock records each admission's fresh backend query. +func (b *sourceLifetimeBackend) BestBlock(context.Context) (int32, + chainhash.Hash, error) { + + b.calls++ + + return b.height, chainhash.Hash{}, b.err +} + +// sourceLifetimeFixture holds saved metadata and truncated durable inputs. +type sourceLifetimeFixture struct { + server *Server + terms arkchannel.Terms + backend *sourceLifetimeBackend + operator *btcec.PublicKey + inputs []oor.TransferInput +} + +// fundingProofs supplies the already-held wallet lineage, not an unsigned +// substitute for the new policy output's eventual recovery package. +type fundingProofs map[wire.OutPoint]*recovery.Proof + +// EnsureProof returns only a proof for the requested wallet input. +func (p fundingProofs) EnsureProof(_ context.Context, out wire.OutPoint) ( + *recovery.Proof, error) { + + if proof, ok := p[out]; ok { + return proof, nil + } + + return nil, fmt.Errorf("wallet lineage unavailable for %s", out) +} + +// TestPreparedFundingRecoveryWindow includes the unsigned checkpoint and Ark +// transaction before commit and uses the channel CSV, not the input's CSV. +func TestPreparedFundingRecoveryWindow(t *testing.T) { + t.Parallel() + + fixture := newSourceLifetimeFixture(t, 1000) + desc := fixture.inputs[0].VTXO + parent := linkedTx(wire.OutPoint{Hash: chainhash.Hash{9}}) + parent.TxOut[0] = wire.NewTxOut(int64(desc.Amount), desc.PkScript) + desc.Outpoint = outpointOf(t, parent) + proof, err := recovery.NewProof( + desc.Outpoint, 900, &recovery.Node{ + Tx: parent, + }, + ) + require.NoError(t, err) + proofs := fundingProofs{desc.Outpoint: proof} + session, _, err := oor.NewPreparedSessionWithIdempotencyKey( + t.Context(), arkscript.CheckpointPolicy{ + OperatorKey: fixture.operator, CSVDelay: 10, + }, fixture.inputs, []oortx.RecipientOutput{{ + PkScript: desc.PkScript, Value: desc.Amount, + VTXOPolicyTemplate: desc.PolicyTemplate, + }}, "funding-depth", oor.EnvConfig{}, + ) + require.NoError(t, err) + t.Cleanup(session.FSM.Stop) + state, err := session.FSM.CurrentState() + require.NoError(t, err) + prepared, ok := state.(*oor.Prepared) + require.True(t, ok) + target := wire.OutPoint{Hash: chainhash.Hash(session.ID)} + projected, err := projectChannelFundingProof( + t.Context(), proofs, target, 10, prepared, + ) + require.NoError(t, err) + require.Len(t, projected.Layers(), 3) + require.NoError(t, validateArkChannelRecoveryWindow(projected, 14, 100)) + require.ErrorContains( + t, validateArkChannelRecoveryWindow(projected, 13, 100), + "needs 14", + ) + _, err = projectChannelFundingProof( + t.Context(), proofs, target, recovery.MaxCSVDelay+1, prepared, + ) + require.ErrorIs(t, err, arkchannel.ErrSourceInadmissible) + + delete(proofs, desc.Outpoint) + _, err = projectChannelFundingProof( + t.Context(), proofs, target, 10, prepared, + ) + require.ErrorContains(t, err, "wallet lineage unavailable") + require.NotErrorIs(t, err, arkchannel.ErrSourceInadmissible) +} + +// newSourceLifetimeFixture uses the production store and durable request codec +// so admission cannot accidentally rely on metadata absent after serialization. +func newSourceLifetimeFixture(t *testing.T, + expiry int32) *sourceLifetimeFixture { + + t.Helper() + store, _, _, _, _ := newSendOORTestStores(t) + operator, err := btcec.NewPrivateKey() + require.NoError(t, err) + desc, _ := newSendOORTestVTXO(t, operator.PubKey(), 61, 100_000) + desc.BatchExpiry = expiry + require.NoError(t, store.SaveVTXO(t.Context(), desc)) + inputs, err := BuildTransferInputs( + t.Context(), store, []wire.OutPoint{desc.Outpoint}, + ) + require.NoError(t, err) + backend := &sourceLifetimeBackend{height: 859} + + return &sourceLifetimeFixture{ + server: &Server{ + vtxoStore: store, + chainBackend: backend, + }, + terms: arkchannel.Terms{ + VTXO: arkchannel.VTXOTerms{ + FunderDelay: 100, + }, + }, + backend: backend, operator: operator.PubKey(), + inputs: durableSourceLifetimeInputs( + t, operator.PubKey(), inputs, + ), + } +} + +// durableSourceLifetimeInputs reproduces the signing-only descriptor seen by +// prepared commit after the ordinary durable actor message serialization. +func durableSourceLifetimeInputs(t *testing.T, operator *btcec.PublicKey, + inputs []oor.TransferInput) []oor.TransferInput { + + t.Helper() + request := &oor.StartTransferRequest{ + Policy: arkscript.CheckpointPolicy{ + OperatorKey: operator, CSVDelay: 10, + }, + Inputs: inputs, PrepareOnly: true, + } + var raw bytes.Buffer + require.NoError(t, request.Encode(&raw)) + var decoded oor.StartTransferRequest + require.NoError(t, decoded.Decode(&raw)) + require.Len(t, decoded.Inputs, len(inputs)) + for _, input := range decoded.Inputs { + require.Zero(t, input.VTXO.BatchExpiry) + } + + return decoded.Inputs +} + +// TestArkChannelSourceLifetimeRestoredSnapshot checks the canonical outgoing +// signing snapshot codec, not just the initial durable request. The original +// input has expiry, but a decoded snapshot must reload it from the VTXO store. +func TestArkChannelSourceLifetimeRestoredSnapshot(t *testing.T) { + t.Parallel() + + fixture := newSourceLifetimeFixture(t, 1000) + outpoint := fixture.inputs[0].VTXO.Outpoint + inputs, err := BuildTransferInputs( + t.Context(), fixture.server.vtxoStore, + []wire.OutPoint{outpoint}, + ) + require.NoError(t, err) + desc := inputs[0].VTXO + require.Equal(t, int32(1000), desc.BatchExpiry) + policy := arkscript.CheckpointPolicy{ + OperatorKey: fixture.operator, CSVDelay: 10, + } + session, _, err := oor.NewPreparedSessionWithIdempotencyKey( + t.Context(), policy, inputs, []oortx.RecipientOutput{{ + PkScript: desc.PkScript, Value: desc.Amount, + VTXOPolicyTemplate: desc.PolicyTemplate, + }}, "source-lifetime-snapshot", oor.EnvConfig{}, + ) + require.NoError(t, err) + t.Cleanup(session.FSM.Stop) + state, err := session.FSM.CurrentState() + require.NoError(t, err) + outgoing, ok := state.(oor.State) + require.True(t, ok) + snapshot, err := oor.NewOutgoingSnapshot(session.ID, outgoing) + require.NoError(t, err) + request := &oor.RestoreSessionRequest{Snapshot: snapshot} + var raw bytes.Buffer + require.NoError(t, request.Encode(&raw)) + var decoded oor.RestoreSessionRequest + require.NoError(t, decoded.Decode(&raw)) + require.Empty(t, decoded.Snapshot.TransferInputs) + restored, err := oor.OutgoingStateFromSnapshot(decoded.Snapshot) + require.NoError(t, err) + prepared, ok := restored.(*oor.Prepared) + require.True(t, ok) + require.Len(t, prepared.TransferInputs, 1) + durable := prepared.TransferInputs[0].VTXO + require.Equal(t, outpoint, durable.Outpoint) + require.Zero(t, durable.BatchExpiry) + require.NoError( + t, + fixture.server.validateArkChannelSourceLifetime( + t.Context(), fixture.terms, prepared.TransferInputs, + ), + ) +} + +// TestArkChannelSourceLifetimeUsesSavedExpiry admits truncated durable inputs +// only when the saved expiry is safe, ignoring both absent and spoofed +// metadata. +func TestArkChannelSourceLifetimeUsesSavedExpiry(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + savedExpiry int32 + claimedExpiry int32 + height int32 + wantErr string + }{ + { + name: "durable expiry omitted", savedExpiry: 1000, + height: 859, + }, + { + name: "stale input metadata", savedExpiry: 1000, + claimedExpiry: 1, height: 859, + }, + { + name: "deadline", savedExpiry: 1000, + claimedExpiry: math.MaxInt32, height: 860, + wantErr: "lifetime exhausted", + }, + { + name: "expired", savedExpiry: 1000, + claimedExpiry: math.MaxInt32, height: 1000, + wantErr: "lifetime exhausted", + }, + { + name: "missing saved expiry", + claimedExpiry: math.MaxInt32, height: 1, + wantErr: "batch expiry must be positive", + }, + { + name: "invalid saved expiry", savedExpiry: -1, + claimedExpiry: math.MaxInt32, height: 1, + wantErr: "batch expiry must be positive", + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + fixture := newSourceLifetimeFixture(t, test.savedExpiry) + fixture.backend.height = test.height + input := fixture.inputs[0].VTXO + input.BatchExpiry = test.claimedExpiry + err := fixture.server.validateArkChannelSourceLifetime( + t.Context(), fixture.terms, fixture.inputs, + ) + if test.wantErr != "" { + require.ErrorContains(t, err, test.wantErr) + } else { + require.NoError(t, err) + } + require.Equal(t, 1, fixture.backend.calls) + }) + } +} + +// TestArkChannelSourceLifetimeUsesExactInputs checks every selected outpoint, +// including different outputs of the same transaction, in either input order. +func TestArkChannelSourceLifetimeUsesExactInputs(t *testing.T) { + t.Parallel() + + for _, reverse := range []bool{false, true} { + t.Run(fmt.Sprintf("reverse=%t", reverse), func(t *testing.T) { + t.Parallel() + + fixture := newSourceLifetimeFixture(t, 1000) + first := fixture.inputs[0].VTXO.Outpoint + second, _ := newSendOORTestVTXO( + t, fixture.operator, 62, 100_000, + ) + second.Outpoint.Hash = first.Hash + second.BatchExpiry = 900 + store := fixture.server.vtxoStore + require.NoError(t, store.SaveVTXO(t.Context(), second)) + selected := []wire.OutPoint{first, second.Outpoint} + if reverse { + slices.Reverse(selected) + } + inputs, err := BuildTransferInputs( + t.Context(), store, selected, + ) + require.NoError(t, err) + inputs = durableSourceLifetimeInputs( + t, fixture.operator, inputs, + ) + fixture.backend.height = 760 + err = fixture.server.validateArkChannelSourceLifetime( + t.Context(), fixture.terms, inputs, + ) + require.ErrorContains(t, err, "batch expiry 900") + fixture.backend.height-- + require.NoError( + t, + fixture.server.validateArkChannelSourceLifetime( + t.Context(), fixture.terms, inputs, + ), + ) + require.Equal(t, 2, fixture.backend.calls) + }) + } +} + +// TestArkChannelSourceLifetimeFailsClosed never substitutes serialized expiry +// when the authoritative row, store, descriptor, or live chain tip is missing. +func TestArkChannelSourceLifetimeFailsClosed(t *testing.T) { + t.Parallel() + + for _, scenario := range []string{ + "missing row", "missing store", "missing backend", + "backend error", "negative height", "zero allowance", + "no inputs", "nil descriptor", + } { + t.Run(scenario, func(t *testing.T) { + t.Parallel() + + fixture := newSourceLifetimeFixture(t, 1000) + fixture.inputs[0].VTXO.BatchExpiry = math.MaxInt32 + switch scenario { + case "missing row": + fixture.inputs[0].VTXO.Outpoint.Index++ + + case "missing store": + fixture.server.vtxoStore = nil + + case "missing backend": + fixture.server.chainBackend = nil + + case "backend error": + fixture.backend.err = fmt.Errorf("backend " + + "unavailable") + + case "negative height": + fixture.backend.height = -1 + + case "zero allowance": + fixture.terms.VTXO.FunderDelay = 0 + + case "no inputs": + fixture.inputs = nil + + case "nil descriptor": + fixture.inputs[0].VTXO = nil + } + err := fixture.server.validateArkChannelSourceLifetime( + t.Context(), fixture.terms, fixture.inputs, + ) + require.Error(t, err) + if scenario == "missing row" { + require.ErrorIs(t, err, vtxo.ErrVTXONotFound) + } + if scenario == "backend error" { + require.ErrorIs(t, err, fixture.backend.err) + } + }) + } +} diff --git a/waved/ark_channel_oor_reservation_test.go b/waved/ark_channel_oor_reservation_test.go new file mode 100644 index 000000000..c49fac63f --- /dev/null +++ b/waved/ark_channel_oor_reservation_test.go @@ -0,0 +1,158 @@ +package waved + +import ( + "bytes" + "context" + "testing" + "time" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chaincfg/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/btcsuite/btclog/v2" + "github.com/lightninglabs/wavelength/arkrpc" + "github.com/lightninglabs/wavelength/baselib/actor" + "github.com/lightninglabs/wavelength/chainsource" + "github.com/lightninglabs/wavelength/oor" + "github.com/lightninglabs/wavelength/wallet" + fn "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/input" + "github.com/stretchr/testify/require" +) + +// channelReservationBackend supplies a fixed tip when source admission is +// enabled, without depending on separate channel-lifetime test fixtures. +type channelReservationBackend struct { + chainsource.ChainBackend +} + +// BestBlock returns a tip safely below the selected source expiries. +func (*channelReservationBackend) BestBlock(context.Context) (int32, + chainhash.Hash, error) { + + return 500, chainhash.Hash{}, nil +} + +// TestPrepareArkChannelOORPreservesReservationEpochs follows selected wallet +// epochs through channel preparation, its durable mailbox and snapshot codec. +func TestPrepareArkChannelOORPreservesReservationEpochs(t *testing.T) { + t.Parallel() + + ctx := t.Context() + terms := testPrePONRTerms(t) + operator, err := btcec.NewPrivateKey() + require.NoError(t, err) + copy( + terms.VTXO.ArkOperatorKey[:], + operator.PubKey().SerializeCompressed(), + ) + const backingFee btcutil.Amount = 1_000 + coins, deliveries, sessions, packages, reservations := + newSendOORTestStores(t) + first, firstKey := newSendOORTestVTXO( + t, operator.PubKey(), 0x85, 40_000, + ) + second, secondKey := newSendOORTestVTXO( + t, operator.PubKey(), 0x86, + terms.Capacity+backingFee-first.Amount, + ) + second.Outpoint.Hash = first.Outpoint.Hash + second.Outpoint.Index = first.Outpoint.Index + 1 + first.BatchExpiry = 10_000 + second.BatchExpiry = 10_000 + require.NoError(t, coins.SaveVTXO(ctx, first)) + require.NoError(t, coins.SaveVTXO(ctx, second)) + selectedA := selectedVTXOFromDescriptor(first) + selectedA.ReserveEpoch = 41 + selectedB := selectedVTXOFromDescriptor(second) + selectedB.ReserveEpoch = 73 + testWallet := &sendOORTestWallet{ + selections: [][]wallet.SelectedVTXO{ + { + selectedB, + selectedA, + }, + }, + } + system := actor.NewActorSystem() + t.Cleanup(func() { + stopCtx, cancel := context.WithTimeout( + context.Background(), 5*time.Second, + ) + defer cancel() + require.NoError(t, system.Shutdown(stopCtx)) + }) + walletKey := actor.NewServiceKey[wallet.WalletMsg, wallet.WalletResp]( + "channel-reservation-wallet", + ) + walletRef := walletKey.Spawn( + system, "channel-reservation-wallet", testWallet, + ) + registry, err := oor.NewOORRegistryActor(oor.OORRegistryConfig{ + Log: fn.Some[btclog.Logger](btclog.Disabled), + Signer: input.NewMockSigner( + []*btcec.PrivateKey{firstKey, secondKey}, nil, + ), + IncomingHandler: noopOORHandler{}, + RegistryStore: sessions, + DeliveryStore: deliveries, + ServerConn: &fakeOORServerConn{}, + PackageStore: packages, + ReservationStore: reservations, + ActorSystem: system, + }) + require.NoError(t, err) + t.Cleanup(registry.Stop) + server := &Server{ + cfg: &Config{}, log: btclog.Disabled, + chainParams: &chaincfg.RegressionNetParams, + serverConn: newBufconnClient(t, &fakeArkService{ + getInfoResponse: &arkrpc.GetInfoResponse{ + Pubkey: operator. + PubKey(). + SerializeCompressed(), + VtxoExitDelay: 10, DustLimit: 1, + }, + }), + actorSystem: system, vtxoStore: coins, + walletRef: fn.Some(walletRef), + oorSessionStore: sessions, + chainBackend: &channelReservationBackend{}, + } + server.arkProtocolVersion.Store(1) + binding, err := server.prepareArkChannelOOR(ctx, terms, backingFee) + require.NoError(t, err) + response, err := registry.Ref().Ask(ctx, &oor.GetStateRequest{ + SessionID: oor.SessionID(binding.OORSessionID), + }).Await(ctx).Unpack() + require.NoError(t, err) + stateResponse, ok := response.(*oor.GetStateResponse) + require.True(t, ok) + prepared, ok := stateResponse.State.(*oor.Prepared) + require.True(t, ok) + snapshot, err := oor.NewOutgoingSnapshot( + oor.SessionID(binding.OORSessionID), prepared, + ) + require.NoError(t, err) + var encoded bytes.Buffer + restore := &oor.RestoreSessionRequest{Snapshot: snapshot} + require.NoError(t, restore.Encode(&encoded)) + var decoded oor.RestoreSessionRequest + require.NoError(t, decoded.Decode(&encoded)) + restored, err := oor.OutgoingStateFromSnapshot(decoded.Snapshot) + require.NoError(t, err) + prepared, ok = restored.(*oor.Prepared) + require.True(t, ok) + epochs := make(map[wire.OutPoint]uint64) + for _, transferInput := range prepared.TransferInputs { + epochs[transferInput.VTXO.Outpoint] = transferInput.ReserveEpoch + } + require.Equal(t, map[wire.OutPoint]uint64{ + selectedA.Outpoint: selectedA.ReserveEpoch, + selectedB.Outpoint: selectedB.ReserveEpoch, + }, epochs) + require.Equal(t, 1, testWallet.selectCount()) + require.Empty(t, testWallet.unlockBatches()) +} diff --git a/waved/ark_channel_process.go b/waved/ark_channel_process.go new file mode 100644 index 000000000..1197e9400 --- /dev/null +++ b/waved/ark_channel_process.go @@ -0,0 +1,1033 @@ +package waved + +import ( + "context" + "errors" + "fmt" + "path/filepath" + "time" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chaincfg/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btclog/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/arkchannel/oorbridge" + "github.com/lightninglabs/wavelength/arkchannel/unrollbridge" + "github.com/lightninglabs/wavelength/chainbackends" + "github.com/lightninglabs/wavelength/chainfees" + "github.com/lightninglabs/wavelength/chainsource" + "github.com/lightninglabs/wavelength/db" + "github.com/lightninglabs/wavelength/lib/types" + "github.com/lightninglabs/wavelength/lnruntime" + "github.com/lightninglabs/wavelength/lwwallet" + mailboxrpc "github.com/lightninglabs/wavelength/mailbox/rpc" + "github.com/lightninglabs/wavelength/rpc/arkchannelrpc" + "github.com/lightninglabs/wavelength/serverconn" + "github.com/lightningnetwork/lnd/channeldb" + "github.com/lightningnetwork/lnd/clock" + fn "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/keychain" + "github.com/lightningnetwork/lnd/lntypes" + "github.com/lightningnetwork/lnd/lnwallet/chainfee" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +const arkChannelPeerIngressPrefix = "arkchannel-peer-ingress-" + +const arkChannelControllerPollInterval = 25 * time.Millisecond + +const arkChannelStartupRetryInterval = time.Second + +const arkChannelRefreshReceiveScriptLabel = "ark channel refresh" + +// ArkChannelLifecycleController owns channel creation, inspection, refresh, +// and on-chain close. +type ArkChannelLifecycleController interface { + PromoteVTXO(context.Context, btcutil.Amount, + string) (arkchannel.Record, error) + + MaterializeAndForceClose(context.Context, arkchannel.ID) ( + arkchannel.Record, chainhash.Hash, chainhash.Hash, error) + + RefreshChannel(context.Context, + arkchannel.ID) (arkchannel.Record, error) + + GetChannel(context.Context, arkchannel.ID) (arkchannel.Record, error) + + ListChannels(context.Context) ([]arkchannel.Record, error) + + ChannelBalance(context.Context, arkchannel.ID) (btcutil.Amount, + btcutil.Amount, error) + + PeerMessageHandler() lnruntime.PeerEventHandler + + Stop() error +} + +// ArkChannelPaymentController owns the private/public payment bridge surface. +type ArkChannelPaymentController interface { + PayLightningInvoice(context.Context, string, + btcutil.Amount) (LightningPaymentResult, error) + + PrepareIncomingPayment(context.Context, lntypes.Preimage, + btcutil.Amount) error + + RegisterIncomingPayment(context.Context, lntypes.Hash, btcutil.Amount, + uint64) (arkchannel.ID, uint32, error) + + WaitIncomingPayment(context.Context, + lntypes.Hash) (arkchannel.ID, error) + + SettleIncomingPayment(context.Context, lntypes.Preimage) error + + CancelIncomingPayment(context.Context, lntypes.Hash, string) error +} + +// ArkChannelController is the complete local process boundary exposed through +// the daemon's ArkChannelService. +type ArkChannelController interface { + ArkChannelLifecycleController + ArkChannelPaymentController +} + +// ArkChannelRecoveryController is the complete endpoint-local source archive, +// watcher, and unroll preparation boundary. +type ArkChannelRecoveryController interface { + lnruntime.ChannelRecoveryManager + arkchannel.ChannelEventSinkBinder + unrollbridge.SourcePreparer + + RestoreWatches(context.Context, []arkchannel.Record) error + + SourceExpiring(context.Context, arkchannel.Terms, + arkchannel.VTXOBinding, int32) (bool, error) + + Stop() +} + +// ArkChannelOORPreparer reserves wallet VTXOs and prepares the exact OOR +// transfer that creates a channel-policy VTXO. +type ArkChannelOORPreparer func(context.Context, arkchannel.Terms, + btcutil.Amount) (arkchannel.VTXOBinding, error) + +// ArkChannelOORLookup reconciles a deterministic channel OOR key without +// selecting or locking fresh wallet inputs. +type ArkChannelOORLookup func(context.Context, arkchannel.Terms, + btcutil.Amount) (oorbridge.PreparationLookup, error) + +// ArkChannelControllerConfig contains the process-owned dependencies supplied +// after wallet, database, and authenticated swap-server transport startup. +type ArkChannelControllerConfig struct { + Log btclog.Logger + Store *db.ArkChannelStoreDB + Peer lnruntime.ProcessCooperativeClosePeer + PeerRPC mailboxrpc.RPCClient + PeerSender lnruntime.PeerEventSender + Wallet *lwwallet.Wallet + ChainBackend chainsource.ChainBackend + ChainNotifier *chainbackends.BackendChainNotifier + FeeEstimator *chainfees.BackendEstimator + OOR *oorbridge.Controller + Materializer *unrollbridge.Controller + Recovery ArkChannelRecoveryController + OperatorTerms *types.OperatorTerms + // OperatorTermsSource reads the client's current negotiated policy. + // Hub controllers can use the explicit OperatorTerms snapshot instead. + OperatorTermsSource func() *types.OperatorTerms + // RegisterRefreshPolicy registers this wallet's payout script under + // current operator terms before those terms can be quoted for a close. + RegisterRefreshPolicy func(context.Context) ( + *types.OperatorTerms, error) + IdentityKey keychain.KeyDescriptor + OORDestination *btcec.PublicKey + KeyIndex uint32 + NetParams *chaincfg.Params + ChannelDataDir string + + // OpenChannelDB returns a database owned by this endpoint. Nil uses + // the application SQL backend, including persistent SQLite in WASM. + OpenChannelDB func(string) (*channeldb.DB, error) + PrepareOOR ArkChannelOORPreparer + LookupOOR ArkChannelOORLookup + Clock clock.Clock + RecordObserver arkchannel.RecordObserver + // SourceExpiryTip returns the shared hub tip and next wakeup. A + // standalone client subscribes directly to its own chain backend. + SourceExpiryTip func() (int32, <-chan struct{}) +} + +// arkChannelRPCServer exposes the configured controller on waved's existing +// authenticated local gRPC listener. +type arkChannelRPCServer struct { + arkchannelrpc.UnimplementedArkChannelServiceServer + + server *Server +} + +// PromoteVTXO creates an OOR-backed native channel from existing wallet +// liquidity using daemon-derived protocol parameters. +func (s *arkChannelRPCServer) PromoteVTXO(ctx context.Context, + req *arkchannelrpc.PromoteVTXORequest) ( + *arkchannelrpc.PromoteVTXOResponse, error) { + + amount, err := arkChannelAmount(req.GetAmountSat()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + if req.GetIdempotencyKey() == "" { + return nil, status.Error( + codes.InvalidArgument, "idempotency key is required", + ) + } + if len(req.GetIdempotencyKey()) > maxArkChannelIdempotencyKeyLength { + return nil, status.Errorf(codes.InvalidArgument, "idempotency "+ + "key exceeds %d bytes", + maxArkChannelIdempotencyKeyLength) + } + controller, err := s.server.channelActionController(ctx, true) + if err != nil { + return nil, err + } + record, err := controller.PromoteVTXO( + ctx, amount, req.GetIdempotencyKey(), + ) + if err != nil { + if ctx.Err() != nil { + return nil, status.FromContextError(ctx.Err()).Err() + } + switch status.Code(err) { + case codes.Aborted, codes.DeadlineExceeded, + codes.ResourceExhausted, codes.Unavailable: + return nil, status.Errorf(status.Code(err), "promote "+ + "VTXO: %v", err) + + default: + } + + return nil, status.Errorf(codes.FailedPrecondition, "promote "+ + "VTXO: %v", err) + } + + return &arkchannelrpc.PromoteVTXOResponse{ + Channel: arkChannelRecordToRPC(ctx, controller, record), + }, nil +} + +// PayLightningInvoice bridges a private source HTLC into the operator's +// public Lightning payment lifecycle with one shared payment hash. +func (s *arkChannelRPCServer) PayLightningInvoice(ctx context.Context, + req *arkchannelrpc.PayLightningInvoiceRequest) ( + *arkchannelrpc.PayLightningInvoiceResponse, error) { + + if req.GetPaymentRequest() == "" { + return nil, status.Error( + codes.InvalidArgument, "payment request is required", + ) + } + if req.GetMaxFeeSat() > uint64(btcutil.MaxSatoshi) { + return nil, status.Error( + codes.InvalidArgument, + "maximum fee exceeds maximum money", + ) + } + controller, err := s.server.channelActionController(ctx, false) + if err != nil { + return nil, err + } + result, err := controller.PayLightningInvoice( + ctx, req.GetPaymentRequest(), + btcutil.Amount( + req.GetMaxFeeSat(), + ), + ) + if err != nil { + return nil, status.Errorf(codes.FailedPrecondition, "pay "+ + "Lightning invoice: %v", err) + } + + return &arkchannelrpc.PayLightningInvoiceResponse{ + PaymentHash: result.PaymentHash[:], + Preimage: result.Preimage[:], + PrivateAmountSat: int64(result.PrivateAmount), + FeeSat: int64(result.Fee), + ChannelId: result.ChannelID[:], + }, nil +} + +// MaterializeAndForceClose publishes the Ark ancestry, signed backing, and +// latest native lnd commitment transaction. +func (s *arkChannelRPCServer) MaterializeAndForceClose(ctx context.Context, + req *arkchannelrpc.MaterializeAndForceCloseRequest) ( + *arkchannelrpc.MaterializeAndForceCloseResponse, error) { + + id, err := arkChannelID(req.GetChannelId()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + controller := s.server.getArkChannelController() + if controller == nil { + return nil, status.Error( + codes.Unavailable, "Ark channel runtime is not ready", + ) + } + record, backingTxID, commitmentTxID, err := + controller.MaterializeAndForceClose(ctx, id) + if err != nil { + return nil, status.Errorf(codes.FailedPrecondition, + "materialize and force close: %v", err) + } + + return &arkchannelrpc.MaterializeAndForceCloseResponse{ + Channel: lnruntime.ArkChannelRecordToRPC(record), + BackingTxid: backingTxID[:], + CommitmentTxid: commitmentTxID[:], + }, nil +} + +// RefreshChannel starts or resumes the client-owned in-Ark refresh process. +func (s *arkChannelRPCServer) RefreshChannel(ctx context.Context, + req *arkchannelrpc.RefreshChannelRequest) ( + *arkchannelrpc.RefreshChannelResponse, error) { + + id, err := arkChannelID(req.GetChannelId()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + controller := s.server.getArkChannelController() + if controller == nil { + return nil, status.Error( + codes.Unavailable, "Ark channel runtime is not ready", + ) + } + record, err := controller.RefreshChannel(ctx, id) + if err != nil { + return nil, status.Errorf(codes.FailedPrecondition, "refresh "+ + "channel in Ark: %v", err) + } + + return &arkchannelrpc.RefreshChannelResponse{ + Channel: lnruntime.ArkChannelRecordToRPC(record), + }, nil +} + +// GetChannel returns one local durable Ark channel summary. +func (s *arkChannelRPCServer) GetChannel(ctx context.Context, + req *arkchannelrpc.GetChannelRequest) ( + *arkchannelrpc.GetChannelResponse, error) { + + id, err := arkChannelID(req.GetChannelId()) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + controller := s.server.getArkChannelController() + var record arkchannel.Record + switch { + case controller != nil: + record, err = controller.GetChannel(ctx, id) + + case s.server.arkChannelStore != nil: + record, err = s.server.arkChannelStore.Get(ctx, id) + + default: + return nil, status.Error( + codes.Unavailable, "Ark channel runtime is not ready", + ) + } + if errors.Is(err, arkchannel.ErrNotFound) { + return nil, status.Error(codes.NotFound, err.Error()) + } + if err != nil { + return nil, status.Errorf(codes.Internal, "get Ark channel: %v", + err) + } + + return &arkchannelrpc.GetChannelResponse{ + Channel: arkChannelRecordToRPC(ctx, controller, record), + }, nil +} + +// ListChannels returns every locally recoverable channel in stable store +// order, including pending creations whose initiating RPC timed out. +func (s *arkChannelRPCServer) ListChannels(ctx context.Context, + _ *arkchannelrpc.ListChannelsRequest) ( + *arkchannelrpc.ListChannelsResponse, error) { + + controller := s.server.getArkChannelController() + var records []arkchannel.Record + var err error + switch { + case controller != nil: + records, err = controller.ListChannels(ctx) + + case s.server.arkChannelStore != nil: + records, err = s.server.arkChannelStore.ListNonTerminal(ctx) + + default: + return nil, status.Error( + codes.Unavailable, "Ark channel runtime is not ready", + ) + } + if err != nil { + return nil, status.Errorf(codes.Internal, "list Ark "+ + "channels: %v", err) + } + channels := make([]*arkchannelrpc.ArkChannel, 0, len(records)) + for _, record := range records { + channels = append( + channels, + arkChannelRecordToRPC(ctx, controller, record), + ) + } + + return &arkchannelrpc.ListChannelsResponse{Channels: channels}, nil +} + +// arkChannelRecordToRPC appends live lnd balances when an active endpoint is +// available without hiding durable state when it is not. +func arkChannelRecordToRPC(ctx context.Context, controller ArkChannelController, + record arkchannel.Record) *arkchannelrpc.ArkChannel { + + channel := lnruntime.ArkChannelRecordToRPC(record) + if controller == nil || + record.Snapshot.Phase != arkchannel.PhaseActive { + return channel + } + local, remote, err := controller.ChannelBalance( + ctx, record.Snapshot.Terms.ID, + ) + if err != nil { + channel.BalanceError = err.Error() + + return channel + } + channel.LocalBalanceSat = int64(local) + channel.RemoteBalanceSat = int64(remote) + channel.BalanceAvailable = true + + return channel +} + +// channelPeerTransport resolves the negotiated mailbox on each call. The +// native node can therefore restore chain protection before either remote +// service is reachable, without inventing a protocol version or accepting +// outgoing work into an unbound mailbox. +type channelPeerTransport struct { + server *Server +} + +// runtime returns only the fully attached transport. +func (p channelPeerTransport) runtime() (*serverconn.Runtime, error) { + p.server.arkChannelMu.RLock() + defer p.server.arkChannelMu.RUnlock() + if p.server.arkChannelMailboxRuntime == nil { + return nil, status.Error( + codes.Unavailable, "Ark channel peer is offline", + ) + } + + return p.server.arkChannelMailboxRuntime, nil +} + +// SendRPC forwards a request only after the peer transport is online. +func (p channelPeerTransport) SendRPC(ctx context.Context, + method mailboxrpc.ServiceMethod, req proto.Message, + opts mailboxrpc.RPCOptions) (mailboxrpc.SendResult, error) { + + rt, err := p.runtime() + if err != nil { + return mailboxrpc.SendResult{}, err + } + + return rt.Unary().SendRPC(ctx, method, req, opts) +} + +// AwaitRPC waits on the same daemon-owned unary response store. +func (p channelPeerTransport) AwaitRPC(ctx context.Context, id string, + resp proto.Message) error { + + rt, err := p.runtime() + if err != nil { + return err + } + + return rt.Unary().AwaitRPC(ctx, id, resp) +} + +// SendPeerEvent hands native traffic to the attached durable sender. +func (p channelPeerTransport) SendPeerEvent(ctx context.Context, + event lnruntime.PeerEvent) error { + + rt, err := p.runtime() + if err != nil { + return err + } + sender, err := lnruntime.NewServerConnPeerSender(rt.TellRef()) + if err != nil { + return err + } + + return sender.SendPeerEvent(ctx, event) +} + +// initLocalChannelController installs local chain recovery without a remote +// call. Startup and transport attachment have a single lifecycle owner. +func (s *Server) initLocalChannelController(ctx context.Context) error { + if s.getArkChannelController() != nil { + return nil + } + edge := channelPeerTransport{server: s} + peer, err := lnruntime.NewMailboxCooperativeClosePeer(edge) + if err != nil { + return err + } + controller, err := s.newClientArkChannelController( + ctx, s.loadClientKeyDesc(), peer, edge, edge, + ) + if err != nil { + return err + } + s.arkChannelMu.Lock() + s.arkChannelController = controller + s.arkChannelMu.Unlock() + //nolint:contextcheck // controller owns its process-lifetime context + controller.Start() + + return nil +} + +// initArkChannelProcess attaches the client node to its negotiated transport. +func (s *Server) initArkChannelProcess(ctx context.Context) error { + if s.cfg.Swap == nil || s.cfg.Swap.ArkChannelMailbox == nil { + return nil + } + identityDesc := s.loadClientKeyDesc() + if identityDesc.PubKey == nil { + return fmt.Errorf("Ark channel runtime requires client " + + "identity") + } + if s.arkChannelStore == nil { + return fmt.Errorf("Ark channel store is not initialized") + } + if err := s.initLocalChannelController(ctx); err != nil { + return err + } + controller := s.getArkChannelController() + + localMailbox := serverconn.PubKeyMailboxID(identityDesc.PubKey) + connCfg := s.arkChannelConnectorConfig(localMailbox) + + //nolint:contextcheck // Start binds the runtime to the process context. + runtime, err := serverconn.NewRuntime(connCfg) + if err != nil { + return fmt.Errorf("create Ark channel mailbox runtime: %w", err) + } + // The actor owns a process-lifetime context and is stopped by + // Server.Stop. + //nolint:contextcheck + peerIngress, err := lnruntime.NewPeerMessageIngress( + lnruntime.PeerMessageIngressConfig{ + ActorID: arkChannelPeerIngressPrefix + localMailbox, + Store: s.deliveryStore, + Handler: controller.PeerMessageHandler(), + Log: s.subLogger(Subsystem), + }, + ) + if err != nil { + runtime.Stop() + + return fmt.Errorf("create Ark channel peer ingress: %w", err) + } + connCfg.Dispatchers[lnruntime.PeerMessageRoute()] = + peerIngress.Dispatcher() + // Start workers only after every peer route is installed. A retried + // startup must not race an old egress worker on the same durable lane. + runtime.StartEgress() + if err := runtime.StartIngress(ctx); err != nil { + joinCtx := context.WithoutCancel(ctx) + + return errors.Join( + fmt.Errorf("start Ark channel mailbox ingress: %w", + err), + peerIngress.StopAndWait(joinCtx), + runtime.StopAndWait(joinCtx), + ) + } + + s.setArkChannelProcess(runtime, controller, peerIngress) + + return nil +} + +// arkChannelConnectorConfig binds the dedicated durable lane to the same +// identity on every start, using the swap edge rather than the operator edge. +func (s *Server) arkChannelConnectorConfig( + identity string) serverconn.ConnectorConfig { + + cfg := serverconn.DefaultConnectorConfig() + cfg.Edge = s.cfg.Swap.ArkChannelMailbox + cfg.LocalMailboxID = identity + cfg.ReplyMailboxID = lnruntime.ArkChannelClientMailboxID(identity) + cfg.RemoteMailboxID = lnruntime.ArkChannelHubMailboxID(identity) + cfg.ArkProtocolVersion = s.arkProtocolVersion.Load() + cfg.Store = s.deliveryStore + cfg.Dispatchers = make(serverconn.DispatcherMap) + cfg.Log = fn.Some(s.subLogger(serverconn.Subsystem)) + + return cfg +} + +// channelRecoveryRequired reads inventory even when the caller disables the +// runtime: unreadable state must never be treated as an empty wallet. +func channelRecoveryRequired(ctx context.Context, cfg *SwapConfig, + list func(context.Context) ([]arkchannel.Record, error)) (bool, error) { + + records, err := list(ctx) + if err != nil { + return false, fmt.Errorf("read recoverable Ark channels: %w", + err) + } + if len(records) == 0 { + return false, nil + } + if cfg != nil && cfg.SuppressArkChannelRuntime { + return false, fmt.Errorf("cannot disable Ark channel " + + "recovery with recoverable channels") + } + + return true, nil +} + +// armArkChannelStartup creates no workers for a fresh wallet, even if it +// permits explicit operations. Only recovery or an explicit open consumes +// the one-shot starter. Its workers belong to the daemon, not an RPC. +func (s *Server) armArkChannelStartup(ctx context.Context) { + if s.cfg.Swap == nil || s.cfg.Swap.SuppressArkChannelRuntime || + s.cfg.Swap.ArkChannelMailbox == nil { + return + } + + s.arkChannelMu.Lock() + defer s.arkChannelMu.Unlock() + s.arkChannelReady = make(chan struct{}) + s.arkChannelDone = ctx.Done() + if s.arkChannelRecoveryNeeded { + s.startArkChannelProcessSupervisor(ctx) + + return + } + s.arkChannelStart = func() { + s.startArkChannelProcessSupervisor(ctx) + } +} + +// channelActionController checks admission independently of recovery. +// Paying an invoice never creates a channel or initializes an empty wallet. +func (s *Server) channelActionController(ctx context.Context, open bool) ( + ArkChannelController, error) { + + if s.cfg == nil || s.cfg.Swap == nil || + !s.cfg.Swap.ArkChannelsEnabled || + s.cfg.Swap.SuppressArkChannelRuntime { + return nil, status.Error( + codes.FailedPrecondition, + "explicit Ark channel operations are disabled", + ) + } + s.arkChannelMu.Lock() + if open && s.arkChannelStart != nil { + s.arkChannelStart() + s.arkChannelStart = nil + } + controller := s.arkChannelController + if s.arkChannelMailboxRuntime == nil { + controller = nil + } + ready, done := s.arkChannelReady, s.arkChannelDone + s.arkChannelMu.Unlock() + if controller == nil && open && ready != nil { + select { + case <-ready: + controller = s.getArkChannelController() + + case <-done: + case <-ctx.Done(): + return nil, status.FromContextError(ctx.Err()).Err() + } + } + if controller == nil { + return nil, status.Error( + codes.Unavailable, "Ark channel runtime is not ready", + ) + } + + return controller, nil +} + +// startArkChannelProcessSupervisor starts the optional channel subsystem +// independently from ordinary wallet-ready services. A transient channel or +// indexer failure therefore cannot strand unrelated actors until restart. +func (s *Server) startArkChannelProcessSupervisor(ctx context.Context) { + if s.cfg.Swap == nil || s.cfg.Swap.ArkChannelMailbox == nil { + return + } + + s.arkChannelStartupWg.Add(1) + go func() { + defer s.arkChannelStartupWg.Done() + + runRetriedArkChannelStartup( + ctx, arkChannelStartupRetryInterval, + s.initArkChannelProcess, + func(err error) { + s.log.WarnS( + ctx, + "Ark channel startup incomplete; "+ + "retrying", + err, + ) + }, + ) + }() +} + +// runRetriedArkChannelStartup retries an idempotent channel startup function +// until it succeeds or the daemon context is canceled. +func runRetriedArkChannelStartup(ctx context.Context, + retryInterval time.Duration, start func(context.Context) error, + onFailure func(error)) { + + for { + if err := start(ctx); err == nil { + return + } else if ctx.Err() != nil { + return + } else if onFailure != nil { + onFailure(err) + } + + timer := time.NewTimer(retryInterval) + select { + case <-ctx.Done(): + if !timer.Stop() { + <-timer.C + } + + return + + case <-timer.C: + } + } +} + +// newClientArkChannelController composes the wallet, chain, OOR, and recovery +// dependencies behind the client channel controller. +func (s *Server) newClientArkChannelController(ctx context.Context, + identityDesc keychain.KeyDescriptor, + peer lnruntime.ProcessCooperativeClosePeer, + peerRPC mailboxrpc.RPCClient, peerSender lnruntime.PeerEventSender) ( + *NativeArkChannelController, error) { + + if !s.lwWallet.IsSome() { + return nil, fmt.Errorf("Ark channel runtime requires lwwallet") + } + if s.chainBackend == nil { + return nil, fmt.Errorf("Ark channel runtime requires a chain " + + "backend") + } + if !s.unrollRegistryRef.IsSome() { + return nil, fmt.Errorf("Ark channel runtime requires the " + + "unroller") + } + chainNotifier, err := chainbackends.NewBackendChainNotifier( + s.chainBackend, + ) + if err != nil { + return nil, err + } + feeEstimator, err := chainfees.NewBackendEstimator( + s.chainBackend, chainfee.FeePerKwFloor, + ) + if err != nil { + return nil, err + } + oorController, err := s.newArkChannelOORController() + if err != nil { + return nil, err + } + recovery, err := newArkChannelRecoveryArchive( + s.vtxoStore, (&RPCServer{server: s}).newLocalOORArtifactStore(), + s.chainBackend, s.subLogger(Subsystem), + ) + if err != nil { + return nil, err + } + materializer, err := unrollbridge.NewController( + s.unrollRegistryRef.UnsafeFromSome(), recovery, + ) + if err != nil { + return nil, err + } + controller, err := NewClientArkChannelController( + ctx, ArkChannelControllerConfig{ + Log: s.subLogger(Subsystem), + Store: s.arkChannelStore, + Peer: peer, + PeerRPC: peerRPC, + PeerSender: peerSender, + Wallet: s.lwWallet.UnsafeFromSome(), + ChainBackend: s.chainBackend, + ChainNotifier: chainNotifier, + FeeEstimator: feeEstimator, + OOR: oorController, + Materializer: materializer, + Recovery: recovery, + OperatorTermsSource: s.loadOperatorTerms, + RegisterRefreshPolicy: s.registerRefreshPolicy, + IdentityKey: identityDesc, + OORDestination: identityDesc.PubKey, + NetParams: s.chainParams, + ChannelDataDir: filepath.Join( + s.cfg.DataDir, "ark-channels", + ), + PrepareOOR: s.prepareArkChannelOOR, + LookupOOR: s.lookupArkChannelOOR, + }, + ) + if err != nil { + return nil, fmt.Errorf("construct Ark channel controller: %w", + err) + } + if controller == nil { + return nil, fmt.Errorf("Ark channel controller factory " + + "returned nil") + } + + return controller, nil +} + +// registerRefreshPolicy returns exactly the operator policy used +// for registration, not the policy that originally funded the channel. +func (s *Server) registerRefreshPolicy(ctx context.Context) ( + *types.OperatorTerms, error) { + + operatorTerms, err := s.fetchOperatorTerms(ctx) + if err != nil { + return nil, fmt.Errorf("fetch Ark channel refresh terms: %w", + err) + } + + if err := s.ensureArkChannelRefreshDelivery( + ctx, operatorTerms, + ); err != nil { + return nil, err + } + + return operatorTerms, nil +} + +// ensureArkChannelRefreshDelivery registers the durable identity-backed VTXO +// script before a refresh request can advertise it. The ordinary incoming OOR +// actor then owns materialization and fraud recovery for the replacement. +func (s *Server) ensureArkChannelRefreshDelivery(ctx context.Context, + operatorTerms *types.OperatorTerms) error { + + if s.indexer == nil { + return fmt.Errorf("Ark channel refresh requires the indexer") + } + if operatorTerms == nil || operatorTerms.PubKey == nil { + return fmt.Errorf("Ark channel refresh requires operator terms") + } + store, err := (&RPCServer{server: s}).newOORReceiveScriptStore() + if err != nil { + return fmt.Errorf("initialize Ark channel refresh receive "+ + "store: %w", err) + } + signerFactory, err := s.indexerProofSignerFactory() + if err != nil { + return fmt.Errorf("initialize Ark channel refresh signer: %w", + err) + } + identityDesc := s.loadClientKeyDesc() + _, err = RegisterOwnedOORReceiveScript( + ctx, s.indexer, store, identityDesc, signerFactory, + operatorTerms.PubKey, operatorTerms.VTXOExitDelay, + arkChannelRefreshReceiveScriptLabel, + ) + if err != nil { + return fmt.Errorf("register Ark channel refresh "+ + "destination: %w", err) + } + + return nil +} + +// setArkChannelProcess publishes the controller and its transport together. +func (s *Server) setArkChannelProcess(runtime *serverconn.Runtime, + controller ArkChannelController, + peerIngress *lnruntime.PeerMessageIngress) { + + s.arkChannelMu.Lock() + defer s.arkChannelMu.Unlock() + + s.arkChannelMailboxRuntime = runtime + s.arkChannelController = controller + s.arkChannelPeerIngress = peerIngress + if s.arkChannelReady != nil { + close(s.arkChannelReady) + s.arkChannelReady = nil + } +} + +// getArkChannelController returns the initialized local controller. +func (s *Server) getArkChannelController() ArkChannelController { + s.arkChannelMu.RLock() + defer s.arkChannelMu.RUnlock() + + return s.arkChannelController +} + +// stopArkChannelProcess joins channel workers before the swap registrar +// releases their borrowed transport or the daemon closes the backing store. +func (s *Server) stopArkChannelProcess(ctx context.Context) error { + s.arkChannelMu.Lock() + runtime := s.arkChannelMailboxRuntime + ingress := s.arkChannelPeerIngress + controller := s.arkChannelController + s.arkChannelMailboxRuntime = nil + s.arkChannelPeerIngress = nil + s.arkChannelController = nil + s.arkChannelMu.Unlock() + + if runtime != nil { + runtime.Connector().StopIngress() + } + err := ingress.StopAndWait(ctx) + if controller != nil { + err = errors.Join(err, controller.Stop()) + } + if runtime != nil { + err = errors.Join(err, runtime.StopAndWait(ctx)) + } + + return err +} + +// PrepareArkChannelIncomingPayment installs the deterministic native invoice +// before a public route hint is exposed. +func (r *RPCServer) PrepareArkChannelIncomingPayment(ctx context.Context, + preimage lntypes.Preimage, amount btcutil.Amount) error { + + controller, err := r.server.channelActionController(ctx, false) + if err != nil { + return err + } + + return controller.PrepareIncomingPayment(ctx, preimage, amount) +} + +// RegisterArkChannelIncomingPayment binds a public future SCID to the +// authenticated client endpoint after its private invoice is durable. It +// returns the minimum CLTV delta in blocks required by the private channel +// payment. +func (r *RPCServer) RegisterArkChannelIncomingPayment(ctx context.Context, + hash lntypes.Hash, amount btcutil.Amount, reservedSCID uint64) ( + arkchannel.ID, uint32, error) { + + controller, err := r.server.channelActionController(ctx, false) + if err != nil { + return arkchannel.ID{}, 0, err + } + + return controller.RegisterIncomingPayment( + ctx, hash, amount, reservedSCID, + ) +} + +// WaitArkChannelIncomingPayment waits on lnd's durable private invoice. +func (r *RPCServer) WaitArkChannelIncomingPayment(ctx context.Context, + hash lntypes.Hash) (arkchannel.ID, error) { + + controller, err := r.waitArkChannelController(ctx) + if err != nil { + return arkchannel.ID{}, err + } + + return controller.WaitIncomingPayment(ctx, hash) +} + +// SettleArkChannelIncomingPayment releases the private hold invoice only after +// the swap SDK durably records acceptance on the registered channel. +func (r *RPCServer) SettleArkChannelIncomingPayment(ctx context.Context, + preimage lntypes.Preimage) error { + + controller, err := r.waitArkChannelController(ctx) + if err != nil { + return err + } + + return controller.SettleIncomingPayment(ctx, preimage) +} + +// CancelArkChannelIncomingPayment cancels the registration and hold invoice. +func (r *RPCServer) CancelArkChannelIncomingPayment(ctx context.Context, + hash lntypes.Hash, reason string) error { + + controller, err := r.waitArkChannelController(ctx) + if err != nil { + return err + } + + return controller.CancelIncomingPayment(ctx, hash, reason) +} + +// waitArkChannelController bridges optional subserver construction, which +// occurs before the mailbox-backed channel process is published at startup. +func (r *RPCServer) waitArkChannelController(ctx context.Context) ( + ArkChannelController, error) { + + if r == nil || r.server == nil { + return nil, fmt.Errorf("Ark channel daemon is not initialized") + } + ticker := time.NewTicker(arkChannelControllerPollInterval) + defer ticker.Stop() + for { + controller := r.server.getArkChannelController() + if controller != nil { + return controller, nil + } + + select { + case <-ctx.Done(): + return nil, ctx.Err() + + case <-ticker.C: + } + } +} + +// arkChannelID parses one fixed-width durable channel identifier. +func arkChannelID(raw []byte) (arkchannel.ID, error) { + var id arkchannel.ID + if len(raw) != len(id) { + return id, fmt.Errorf("channel id must be %d bytes, got %d", + len(id), len(raw)) + } + copy(id[:], raw) + + return id, nil +} + +// arkChannelAmount parses a strictly positive channel amount. +func arkChannelAmount(value int64) (btcutil.Amount, error) { + if value <= 0 { + return 0, fmt.Errorf("amount must be positive") + } + + return btcutil.Amount(value), nil +} + +var _ arkchannelrpc.ArkChannelServiceServer = (*arkChannelRPCServer)(nil) diff --git a/waved/ark_channel_process_test.go b/waved/ark_channel_process_test.go new file mode 100644 index 000000000..bb1c9a7b9 --- /dev/null +++ b/waved/ark_channel_process_test.go @@ -0,0 +1,462 @@ +package waved + +import ( + "context" + "errors" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/lnruntime" + mailboxpb "github.com/lightninglabs/wavelength/mailbox/pb" + "github.com/lightninglabs/wavelength/rpc/arkchannelrpc" + "github.com/lightninglabs/wavelength/serverconn" + "github.com/lightningnetwork/lnd/clock" + "github.com/lightningnetwork/lnd/lntypes" + "github.com/lightningnetwork/lnd/lnwire" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// arkChannelControllerStub records local RPC calls and returns a configured +// durable channel record. +type arkChannelControllerStub struct { + record arkchannel.Record + records []arkchannel.Record + err error + id arkchannel.ID + localBalance btcutil.Amount + remoteBalance btcutil.Amount + balanceErr error +} + +// PromoteVTXO is not used by close RPC tests. +func (s *arkChannelControllerStub) PromoteVTXO(context.Context, btcutil.Amount, + string) (arkchannel.Record, error) { + + return s.record, s.err +} + +// ListChannels returns configured durable records. +func (s *arkChannelControllerStub) ListChannels(context.Context) ( + []arkchannel.Record, error) { + + return s.records, s.err +} + +// ChannelBalance returns configured live channel balances. +func (s *arkChannelControllerStub) ChannelBalance(context.Context, + arkchannel.ID) (btcutil.Amount, btcutil.Amount, error) { + + return s.localBalance, s.remoteBalance, s.balanceErr +} + +// PayLightningInvoice is not used by close RPC tests. +func (s *arkChannelControllerStub) PayLightningInvoice(context.Context, string, + btcutil.Amount) (LightningPaymentResult, error) { + + return LightningPaymentResult{}, s.err +} + +// PrepareIncomingPayment is not used by close RPC tests. +func (s *arkChannelControllerStub) PrepareIncomingPayment(context.Context, + lntypes.Preimage, btcutil.Amount) error { + + return s.err +} + +// RegisterIncomingPayment is not used by close RPC tests. +func (s *arkChannelControllerStub) RegisterIncomingPayment(context.Context, + lntypes.Hash, btcutil.Amount, uint64) (arkchannel.ID, uint32, error) { + + return arkchannel.ID{}, 0, s.err +} + +// WaitIncomingPayment is not used by close RPC tests. +func (s *arkChannelControllerStub) WaitIncomingPayment(context.Context, + lntypes.Hash) (arkchannel.ID, error) { + + return arkchannel.ID{}, s.err +} + +// SettleIncomingPayment is not used by lifecycle RPC tests. +func (s *arkChannelControllerStub) SettleIncomingPayment(context.Context, + lntypes.Preimage) error { + + return s.err +} + +// CancelIncomingPayment is not used by lifecycle RPC tests. +func (s *arkChannelControllerStub) CancelIncomingPayment(context.Context, + lntypes.Hash, string) error { + + return s.err +} + +// MaterializeAndForceClose is not used by refresh RPC tests. +func (s *arkChannelControllerStub) MaterializeAndForceClose(context.Context, + arkchannel.ID) (arkchannel.Record, chainhash.Hash, chainhash.Hash, + error) { + + return s.record, chainhash.Hash{}, chainhash.Hash{}, s.err +} + +// RefreshChannel records the parsed public request. +func (s *arkChannelControllerStub) RefreshChannel(_ context.Context, + id arkchannel.ID) (arkchannel.Record, error) { + + s.id = id + + return s.record, s.err +} + +// GetChannel returns the configured channel record. +func (s *arkChannelControllerStub) GetChannel(_ context.Context, + id arkchannel.ID) (arkchannel.Record, error) { + + s.id = id + + return s.record, s.err +} + +// PeerMessageHandler returns an inert native peer handler for RPC-only tests. +// +//nolint:ll // The concrete method name and interface type are both significant. +func (*arkChannelControllerStub) PeerMessageHandler() lnruntime.PeerEventHandler { + return func(context.Context, lnwire.Message) error { + return nil + } +} + +// Stop is inert for the RPC-only controller stub. +func (*arkChannelControllerStub) Stop() error { + return nil +} + +// TestArkChannelRPCRefreshChannel verifies fixed-width ID parsing and +// controller dispatch on the local authenticated RPC surface. +func TestArkChannelRPCRefreshChannel(t *testing.T) { + t.Parallel() + + id := arkchannel.ID{1, 2, 3} + controller := &arkChannelControllerStub{ + record: arkchannel.Record{ + Snapshot: arkchannel.Snapshot{ + Terms: arkchannel.Terms{ + ID: id, + }, + Phase: arkchannel.PhaseCoopClosing, + }, + Revision: 4, + }, + } + server := &Server{arkChannelController: controller} + rpcServer := &arkChannelRPCServer{server: server} + + response, err := rpcServer.RefreshChannel( + t.Context(), &arkchannelrpc.RefreshChannelRequest{ + ChannelId: id[:], + }, + ) + require.NoError(t, err) + require.Equal(t, id, controller.id) + require.Equal(t, id[:], response.GetChannel().GetChannelId()) + require.Equal(t, uint64(4), response.GetChannel().GetRevision()) + + _, err = rpcServer.RefreshChannel( + t.Context(), &arkchannelrpc.RefreshChannelRequest{ + ChannelId: []byte{1}, + }, + ) + require.Equal(t, codes.InvalidArgument, status.Code(err)) +} + +// TestArkChannelRPCUnavailable verifies the local service remains registered +// but fails explicitly when no compiled-in channel runtime was installed. +func TestArkChannelRPCUnavailable(t *testing.T) { + t.Parallel() + + id := arkchannel.ID{1} + rpcServer := &arkChannelRPCServer{server: &Server{}} + + _, err := rpcServer.GetChannel( + t.Context(), &arkchannelrpc.GetChannelRequest{ + ChannelId: id[:], + }, + ) + require.Equal(t, codes.Unavailable, status.Code(err)) +} + +// TestArkChannelRPCListIncludesBalances verifies durable listing remains the +// primary result while active lnd balances are included when available. +func TestArkChannelRPCListIncludesBalances(t *testing.T) { + t.Parallel() + + id := arkchannel.ID{4, 5, 6} + record := arkchannel.Record{ + Snapshot: arkchannel.Snapshot{ + Terms: arkchannel.Terms{ + ID: id, Capacity: 50_000, + }, + Phase: arkchannel.PhaseActive, + }, + } + controller := &arkChannelControllerStub{ + records: []arkchannel.Record{ + record, + }, + localBalance: 20_000, remoteBalance: 30_000, + } + rpcServer := &arkChannelRPCServer{server: &Server{ + arkChannelController: controller, + }} + + response, err := rpcServer.ListChannels( + t.Context(), &arkchannelrpc.ListChannelsRequest{}, + ) + require.NoError(t, err) + require.Len(t, response.GetChannels(), 1) + channel := response.GetChannels()[0] + require.Equal(t, id[:], channel.GetChannelId()) + require.True(t, channel.GetBalanceAvailable()) + require.EqualValues(t, 20_000, channel.GetLocalBalanceSat()) + require.EqualValues(t, 30_000, channel.GetRemoteBalanceSat()) +} + +// TestArkChannelRPCRejectsLongIdempotencyKey verifies malformed retry keys are +// rejected before channel startup or wallet selection. +func TestArkChannelRPCRejectsLongIdempotencyKey(t *testing.T) { + t.Parallel() + + rpcServer := &arkChannelRPCServer{server: &Server{}} + _, err := rpcServer.PromoteVTXO( + t.Context(), &arkchannelrpc.PromoteVTXORequest{ + AmountSat: 1_000, + IdempotencyKey: strings.Repeat("a", 129), + }, + ) + require.Equal(t, codes.InvalidArgument, status.Code(err)) +} + +// TestArkChannelRPCRequiresIdempotencyKey verifies every funding request has a +// stable recovery identity before the daemon can select wallet inputs. +func TestArkChannelRPCRequiresIdempotencyKey(t *testing.T) { + t.Parallel() + + rpcServer := &arkChannelRPCServer{server: &Server{}} + _, err := rpcServer.PromoteVTXO( + t.Context(), &arkchannelrpc.PromoteVTXORequest{ + AmountSat: 1_000, + }, + ) + require.Equal(t, codes.InvalidArgument, status.Code(err)) +} + +// TestArkChannelRPCPreservesRetryablePromotionStatus verifies the CLI can +// distinguish a resumable transport failure from a terminal funding error. +func TestArkChannelRPCPreservesRetryablePromotionStatus(t *testing.T) { + t.Parallel() + + controller := &arkChannelControllerStub{ + err: status.Error(codes.Unavailable, "operator offline"), + } + rpcServer := &arkChannelRPCServer{server: &Server{ + cfg: &Config{ + Swap: &SwapConfig{ + ArkChannelsEnabled: true, + }, + }, + arkChannelMailboxRuntime: &serverconn.Runtime{}, + arkChannelController: controller, + }} + _, err := rpcServer.PromoteVTXO( + t.Context(), &arkchannelrpc.PromoteVTXORequest{ + AmountSat: 1_000, IdempotencyKey: "create-44", + }, + ) + require.Equal(t, codes.Unavailable, status.Code(err)) +} + +// TestChannelAdmissionDoesNotStartRecovery verifies that permission alone, +// rejected opens and all pay attempts leave an empty wallet dormant. +func TestChannelAdmissionDoesNotStartRecovery(t *testing.T) { + for _, enabled := range []bool{false, true} { + s := &Server{cfg: &Config{Swap: &SwapConfig{ + ArkChannelsEnabled: enabled, + ArkChannelMailbox: mailboxpb.NewMailboxServiceClient( + nil, + ), + }}} + s.armArkChannelStartup(t.Context()) + require.NotNil(t, s.arkChannelStart) + require.Nil(t, s.arkChannelController) + calls := 0 + s.arkChannelStart = func() { + calls++ + s.arkChannelController = &arkChannelControllerStub{} + s.arkChannelMailboxRuntime = &serverconn.Runtime{} + } + _, err := s.channelActionController(t.Context(), false) + require.Error(t, err) + require.Zero(t, calls) + for range 2 { + _, err = s.channelActionController(t.Context(), true) + if enabled { + require.NoError(t, err) + require.Equal(t, 1, calls) + } else { + require.Equal( + t, codes.FailedPrecondition, + status.Code(err), + ) + require.Zero(t, calls) + } + } + } +} + +// TestChannelRecoveryInventory verifies that a read failure is not an empty +// inventory, and admission is irrelevant to protecting persisted channels. +func TestChannelRecoveryInventory(t *testing.T) { + readErr := errors.New("unreadable channel inventory") + for _, disabled := range []bool{false, true} { + cfg := &SwapConfig{SuppressArkChannelRuntime: disabled} + for _, live := range []bool{false, true} { + list := func(context.Context) ([]arkchannel.Record, + error) { + + if live { + return []arkchannel.Record{{}}, nil + } + + return nil, nil + } + needed, err := channelRecoveryRequired( + t.Context(), cfg, list, + ) + if live && disabled { + require.ErrorContains(t, err, "cannot disable") + } else { + require.NoError(t, err) + require.Equal(t, live, needed) + } + } + _, err := channelRecoveryRequired(t.Context(), cfg, + func(context.Context) ([]arkchannel.Record, error) { + return nil, readErr + }) + require.ErrorIs(t, err, readErr) + } +} + +// TestArkChannelInventoryWithoutController uses only durable storage, even +// after reopening the wallet with admission off and no peer transport. +func TestArkChannelInventoryWithoutController(t *testing.T) { + dir := t.TempDir() + raw, coordinator := testArkChannelResumeStore(t, dir) + record := testArkChannelResumeRecord(t, coordinator, false) + require.NoError(t, raw.Close()) + + raw, _ = testArkChannelResumeStore(t, dir) + store := raw.NewArkChannelStore(clock.NewDefaultClock()) + cfg := &SwapConfig{SuppressArkChannelRuntime: true} + _, err := channelRecoveryRequired( + t.Context(), cfg, store.ListNonTerminal, + ) + require.ErrorContains(t, err, "cannot disable") + + s := &Server{arkChannelStore: store} + rpc := &arkChannelRPCServer{server: s} + id := record.Snapshot.Terms.ID + req := &arkchannelrpc.GetChannelRequest{ChannelId: id[:]} + resp, err := rpc.GetChannel(t.Context(), req) + require.NoError(t, err) + require.Equal(t, id[:], resp.GetChannel().GetChannelId()) + require.Nil(t, s.getArkChannelController()) + + require.NoError(t, raw.Close()) + _, err = channelRecoveryRequired( + t.Context(), cfg, store.ListNonTerminal, + ) + require.ErrorContains(t, err, "read recoverable Ark channels") + _, err = rpc.GetChannel(t.Context(), req) + require.Equal(t, codes.Internal, status.Code(err)) +} + +// TestRunRetriedArkChannelStartupRecovers verifies a transient optional +// channel failure cannot permanently strand the process after wallet unlock. +func TestRunRetriedArkChannelStartupRecovers(t *testing.T) { + t.Parallel() + + var attempts atomic.Int32 + var failures atomic.Int32 + done := make(chan struct{}) + go func() { + defer close(done) + + runRetriedArkChannelStartup( + t.Context(), time.Millisecond, + func(context.Context) error { + if attempts.Add(1) == 1 { + return errors.New("indexer " + + "temporarily offline") + } + + return nil + }, + func(error) { + failures.Add(1) + }, + ) + }() + + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("channel startup did not recover") + } + require.EqualValues(t, 2, attempts.Load()) + require.EqualValues(t, 1, failures.Load()) +} + +// TestRunRetriedArkChannelStartupStops verifies shutdown interrupts the retry +// delay instead of racing daemon resource teardown. +func TestRunRetriedArkChannelStartupStops(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithCancel(t.Context()) + failed := make(chan struct{}) + done := make(chan struct{}) + go func() { + defer close(done) + + runRetriedArkChannelStartup( + ctx, time.Hour, + func(context.Context) error { + return errors.New("operator offline") + }, + func(error) { + close(failed) + }, + ) + }() + + select { + case <-failed: + case <-time.After(time.Second): + t.Fatal("channel startup did not attempt") + } + cancel() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("channel startup did not stop") + } +} + +var _ ArkChannelController = (*arkChannelControllerStub)(nil) diff --git a/waved/ark_channel_promotion_ready_test.go b/waved/ark_channel_promotion_ready_test.go new file mode 100644 index 000000000..9f3b97c18 --- /dev/null +++ b/waved/ark_channel_promotion_ready_test.go @@ -0,0 +1,218 @@ +package waved + +import ( + "context" + "errors" + "testing" + "testing/synctest" + + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/lnruntime" + mailboxrpc "github.com/lightninglabs/wavelength/mailbox/rpc" + "github.com/lightninglabs/wavelength/rpc/arkchannelrpc" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +// promotionLookupStore exposes only lookup; any economic write fails the test. +type promotionLookupStore struct { + arkchannel.Store + record arkchannel.Record +} + +// Get returns the existing channel only for the original promotion identity. +func (s *promotionLookupStore) Get(ctx context.Context, id arkchannel.ID) ( + arkchannel.Record, error) { + + if id != s.record.Snapshot.Terms.ID { + return arkchannel.Record{}, arkchannel.ErrNotFound + } + + return s.record, ctx.Err() +} + +type promotionStatusRPC struct { + t *testing.T + id arkchannel.ID + phase uint32 + reads int + probes int + readErr error + observe func() error +} + +// SendRPC allows only status requests for the expected funding point. +func (p *promotionStatusRPC) SendRPC(ctx context.Context, + method mailboxrpc.ServiceMethod, req proto.Message, + _ mailboxrpc.RPCOptions) (mailboxrpc.SendResult, error) { + + switch msg := req.(type) { + case *arkchannelrpc.GetFundingChannelRequest: + require.Equal(p.t, "GetFundingChannel", method.Method) + require.Equal(p.t, p.id[:], msg.GetChannelId()) + p.reads++ + + case *arkchannelrpc.FundingStatusRequest: + require.Equal(p.t, "ChannelActive", method.Method) + require.Equal(p.t, p.id[:], msg.GetTerms().GetChannelId()) + require.EqualValues( + p.t, 17, msg.GetBacking().GetChannelPointIndex(), + ) + p.probes++ + + default: + p.t.Fatalf("unexpected promotion side effect: %T", msg) + } + + return mailboxrpc.SendResult{CorrelationID: method.Method}, ctx.Err() +} + +// AwaitRPC distinguishes native readiness from the hub's durable phase. +func (p *promotionStatusRPC) AwaitRPC(ctx context.Context, _ string, + response proto.Message) error { + + switch msg := response.(type) { + case *arkchannelrpc.GetFundingChannelResponse: + msg.Terms = &arkchannelrpc.ChannelTerms{ChannelId: p.id[:]} + msg.Phase = p.phase + + return p.readErr + + case *arkchannelrpc.FundingStatusResponse: + msg.Ready = true + + return p.observe() + + default: + p.t.Fatalf("unexpected promotion reply: %T", msg) + + return ctx.Err() + } +} + +// TestPromotionWaitsForHubActivation exercises explicit promotion replay +// without a funding peer, payment bridge or writable store. +func TestPromotionWaitsForHubActivation(t *testing.T) { + t.Parallel() + synctest.Test(t, testPromotionWaitsForHubActivation) +} + +// testPromotionWaitsForHubActivation uses virtual time for the polling path. +func testPromotionWaitsForHubActivation(t *testing.T) { + c := &NativeArkChannelController{ + party: arkchannel.PartyClient, + cfg: ArkChannelControllerConfig{ + IdentityKey: testKeyDescriptor(t, 1), + }, + keys: nativeArkChannelKeys{ + ark: testKeyDescriptor(t, 2), + backing: testKeyDescriptor(t, 3), + funder: testKeyDescriptor(t, 4), + }, + node: &lnruntime.NativeNode{}, + } + const key = "replay" + id, pending, scid := c.promotionIdentifiers(key) + info := fundingPeerFromTerms(testPrePONRTerms(t)) + terms, err := c.newClientFundedTerms(id, pending, scid, 200_000, info) + require.NoError(t, err) + c.clientPeer.nodeKey = terms.HubNodeKey + store := &promotionLookupStore{record: arkchannel.Record{ + Snapshot: arkchannel.Snapshot{ + Phase: arkchannel.PhaseActive, Terms: terms, + Source: &arkchannel.VTXOBinding{}, + Backing: &arkchannel.Backing{}, + }, + }} + store.record.Snapshot.Backing.ChannelPoint.Index = 17 + c.coordinator, err = arkchannel.NewCoordinator(store) + require.NoError(t, err) + rejectAction := arkChannelResumeExecutor(func(_ context.Context, + _ arkchannel.ID, action arkchannel.Action) error { + + t.Fatalf("unexpected channel action on replay: %T", action) + + return nil + }) + c.service, err = arkchannel.NewService( + c.party, c.coordinator, rejectAction, + ) + require.NoError(t, err) + p := &promotionStatusRPC{ + t: t, id: id, phase: uint32(arkchannel.PhaseActivating), + } + c.cfg.PeerRPC = p + c.fundingPeer, err = lnruntime.NewMailboxFundingPeer(p) + require.NoError(t, err) + promote := func(ctx context.Context) (arkchannel.Record, error) { + return c.PromoteVTXO(ctx, terms.Capacity, key) + } + + offline := errors.New("peer unavailable") + p.readErr = offline + record, err := promote(t.Context()) + require.ErrorIs(t, err, offline) + require.Zero(t, record) + require.Zero(t, p.probes) + + p.readErr = nil + p.observe = func() error { return offline } + _, err = promote(t.Context()) + require.ErrorIs(t, err, offline) + require.Equal(t, 1, p.probes) + + // Even a positive native observation is not a durable phase read. + // Leave the hub activating and cancel before the next poll. + ctx, cancel := context.WithCancel(t.Context()) + p.observe = func() error { + cancel() + + return nil + } + _, err = promote(ctx) + require.ErrorIs(t, err, context.Canceled) + require.Equal(t, 2, p.probes) + + before := p.reads + p.observe = func() error { + p.phase = uint32(arkchannel.PhaseActive) + + return nil + } + record, err = promote(t.Context()) + require.NoError(t, err) + require.Equal(t, store.record, record) + require.Equal(t, before+2, p.reads) + require.Equal(t, 3, p.probes) + + // The hub can persist activation even if its reply is lost. + p.phase = uint32(arkchannel.PhaseActivating) + p.observe = func() error { + p.phase = uint32(arkchannel.PhaseActive) + + return offline + } + _, err = promote(t.Context()) + require.ErrorIs(t, err, offline) + before = p.reads + record, err = promote(t.Context()) + require.NoError(t, err) + require.Equal(t, store.record, record) + require.Equal(t, before+1, p.reads) + require.Equal(t, 4, p.probes) + + // A hub already closing cannot authorize a stale active response. + p.phase = uint32(arkchannel.PhaseCoopClosing) + _, err = promote(t.Context()) + require.ErrorContains(t, err, "hub channel is not active") + require.Equal(t, 4, p.probes) + + // Local post-creation lookups stay usable with the hub offline. + before = p.reads + p.readErr = offline + store.record.Snapshot.Phase = arkchannel.PhaseClosed + record, err = promote(t.Context()) + require.NoError(t, err) + require.Equal(t, store.record, record) + require.Equal(t, before, p.reads) +} diff --git a/waved/ark_channel_recovery_runtime.go b/waved/ark_channel_recovery_runtime.go new file mode 100644 index 000000000..739889819 --- /dev/null +++ b/waved/ark_channel_recovery_runtime.go @@ -0,0 +1,238 @@ +package waved + +import ( + "context" + "fmt" + "sync" + "time" + + "github.com/btcsuite/btclog/v2" + "github.com/lightninglabs/lndclient" + "github.com/lightninglabs/wavelength/arkchannel/unrollbridge" + "github.com/lightninglabs/wavelength/baselib/actor" + "github.com/lightninglabs/wavelength/chainsource" + "github.com/lightninglabs/wavelength/db" + "github.com/lightninglabs/wavelength/db/actordelivery" + "github.com/lightninglabs/wavelength/ledger" + "github.com/lightninglabs/wavelength/lndbackend" + "github.com/lightninglabs/wavelength/txconfirm" + "github.com/lightninglabs/wavelength/unroll" + "github.com/lightningnetwork/lnd/clock" + fn "github.com/lightningnetwork/lnd/fn/v2" +) + +// ArkChannelUnrollWallet is the fee-input and sweep wallet surface shared by +// txconfirm and the ordinary VTXO unroller. +type ArkChannelUnrollWallet interface { + txconfirm.Wallet + unroll.SweepWallet +} + +// NewLNDArkChannelUnrollWallet adapts swapd's existing LND wallet for channel +// source recovery and CPFP fee management. +func NewLNDArkChannelUnrollWallet(signer lndclient.SignerClient, + walletKit lndclient.WalletKitClient, + chainKit lndclient.ChainKitClient) ArkChannelUnrollWallet { + + return &lndUnrollWallet{ + ClientWallet: lndbackend.NewClientWallet(signer, walletKit), + boardingBackend: lndbackend.NewBoardingBackend( + walletKit, chainKit, + ), + } +} + +// ArkChannelRecoveryRuntimeConfig contains the process-wide durable store and +// process-owned chain dependencies needed by the common unroller. +type ArkChannelRecoveryRuntimeConfig struct { + Store *db.Store + ChannelStore *db.ArkChannelStoreDB + ChainBackend chainsource.ChainBackend + Wallet ArkChannelUnrollWallet + Log btclog.Logger +} + +// ArkChannelRecoveryRuntime owns the operator's unroll actors and expiry feed. +// Endpoint-specific watches deliver events only to their own channel service. +type ArkChannelRecoveryRuntime struct { + actorSystem *actor.ActorSystem + registry *unroll.UnrollRegistryActor + cfg ArkChannelRecoveryRuntimeConfig + tipMu sync.Mutex + height int32 + nextTip chan struct{} + stopTip context.CancelFunc + tipDone chan struct{} +} + +// NewArkChannelRecoveryRuntime composes the same unroller used by waved while +// leaving ownership of the database, chain backend, and wallet with swapd. +// +//nolint:contextcheck // recovery actors own lifecycle until runtime Stop +func NewArkChannelRecoveryRuntime(ctx context.Context, + cfg ArkChannelRecoveryRuntimeConfig) (*ArkChannelRecoveryRuntime, + error) { + + switch { + case cfg.Store == nil || cfg.ChannelStore == nil: + return nil, fmt.Errorf("Ark channel recovery store is required") + + case cfg.ChainBackend == nil: + return nil, fmt.Errorf("Ark channel recovery chain backend " + + "is required") + + case cfg.Wallet == nil: + return nil, fmt.Errorf("Ark channel recovery wallet is " + + "required") + } + log := cfg.Log + if log == nil { + log = btclog.Disabled + } + actorSystem := actor.NewActorSystemWithConfig(actor.SystemConfig{ + MailboxCapacity: 100, Log: fn.Some(log), + }) + cleanup := true + defer func() { + if cleanup { + shutdownCtx, cancel := context.WithTimeout( + context.Background(), 5*time.Second, + ) + defer cancel() + _ = actorSystem.Shutdown(shutdownCtx) + } + }() + chainActor := chainsource.NewChainSourceActor( + chainsource.ChainSourceConfig{ + Backend: cfg.ChainBackend, System: actorSystem, + FinalityDepth: chainsource.DefaultFinalityDepth, + }, + ) + chainSource := actor.RegisterWithSystem( + actorSystem, "ark-channel-chain-source", + chainsource.ChainSourceKey, chainActor, + ) + deliveryStore, err := actordelivery.NewTxAwareDeliveryStoreFromDB( + cfg.Store.DB(), cfg.Store.Backend(), clock.NewDefaultClock(), + log, + ) + if err != nil { + return nil, err + } + txConfirm := txconfirm.NewTxBroadcasterActor(txconfirm.Config{ + ChainSource: chainSource, Wallet: cfg.Wallet, + Log: fn.Some(log), + }) + txConfirmRef := actor.RegisterWithSystem( + actorSystem, txconfirm.ServiceKeyName, + txconfirm.NewServiceKey(), txConfirm, + ) + txConfirm.SetSelfRef(txConfirmRef) + vtxoStore := cfg.Store.NewVTXOStore(clock.NewDefaultClock()) + oorStore := cfg.Store.NewOORArtifactStore(clock.NewDefaultClock()) + registry := unroll.NewUnrollRegistryActor(unroll.RegistryConfig{ + Store: &unroll.DBRegistryStore{ + UEStore: cfg.Store.NewUnilateralExitStore( + clock.NewDefaultClock(), + ), + }, + DeliveryStore: deliveryStore, + ProofAssembler: &unroll.LocalProofAssembler{ + VTXOStore: vtxoStore, ArtifactStore: oorStore, + }, + VTXOStore: vtxoStore, TxConfirmRef: txConfirmRef, + ChainSource: chainSource, Wallet: cfg.Wallet, + LedgerSink: fn.None[ledger.Sink](), + Log: fn.Some(log), + ExitSpendPolicyResolver: unroll.PolicyResolvers{ + unrollbridge.Resolver{Channels: cfg.ChannelStore}, + }, + }) + if err := registry.RestoreNonTerminal(ctx); err != nil { + registry.Stop() + + return nil, fmt.Errorf("restore Ark channel unrolls: %w", err) + } + cleanup = false + + tipCtx, stopTip := context.WithCancel(ctx) + runtime := &ArkChannelRecoveryRuntime{ + actorSystem: actorSystem, registry: registry, + cfg: cfg, height: -1, nextTip: make(chan struct{}), + stopTip: stopTip, tipDone: make(chan struct{}), + } + go func() { + defer close(runtime.tipDone) + watchSourceExpiryTip( + tipCtx, cfg.ChainBackend, clock.NewDefaultClock(), log, + runtime.publishTip, + ) + }() + + return runtime, nil +} + +// publishTip wakes all endpoint guards without blocking on a slow peer. +func (r *ArkChannelRecoveryRuntime) publishTip(height int32) { + r.tipMu.Lock() + defer r.tipMu.Unlock() + r.height = height + close(r.nextTip) + r.nextTip = make(chan struct{}) +} + +// SourceExpiryTip captures the tip and subsequent wakeup atomically, so +// simultaneous registration and a threshold crossing cannot lose the block. +func (r *ArkChannelRecoveryRuntime) SourceExpiryTip() (int32, <-chan struct{}) { + r.tipMu.Lock() + defer r.tipMu.Unlock() + + return r.height, r.nextTip +} + +// NewEndpoint binds a peer's source observations to its own FSM. The actors, +// chain source, unroll jobs, and durable evidence belong to the hub process. +func (r *ArkChannelRecoveryRuntime) NewEndpoint() (ArkChannelRecoveryController, + *unrollbridge.Controller, error) { + + clk := clock.NewDefaultClock() + recovery, err := newArkChannelRecoveryArchive( + r.cfg.Store.NewVTXOStore(clk), + r.cfg.Store.NewOORArtifactStore(clk), r.cfg.ChainBackend, + r.cfg.Log, + ) + if err != nil { + return nil, nil, err + } + recovery.importOnly = true + materializer, err := unrollbridge.NewController( + r.registry.Ref(), recovery, + ) + if err != nil { + recovery.Stop() + + return nil, nil, err + } + + return recovery, materializer, nil +} + +// Stop releases watches and actors without stopping externally owned chain or +// wallet backends. +func (r *ArkChannelRecoveryRuntime) Stop() error { + if r == nil { + return nil + } + r.stopTip() + <-r.tipDone + if r.registry != nil { + r.registry.Stop() + } + if r.actorSystem == nil { + return nil + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + return r.actorSystem.Shutdown(ctx) +} diff --git a/waved/ark_channel_source.go b/waved/ark_channel_source.go new file mode 100644 index 000000000..ca8118c29 --- /dev/null +++ b/waved/ark_channel_source.go @@ -0,0 +1,834 @@ +package waved + +import ( + "bytes" + "context" + "errors" + "fmt" + "time" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "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/arkchannel/unrollbridge" + "github.com/lightninglabs/wavelength/arkrpc" + "github.com/lightninglabs/wavelength/chainsource" + "github.com/lightninglabs/wavelength/db" + "github.com/lightninglabs/wavelength/lib/recovery" + "github.com/lightninglabs/wavelength/lib/tx/psbtutil" + "github.com/lightninglabs/wavelength/unroll" + "github.com/lightninglabs/wavelength/vtxo" + "github.com/lightningnetwork/lnd/keychain" +) + +// arkChannelRecoveryArchive exports and installs the exact finalized source +// package. The channel-policy VTXO is recovery-only, so it never appears in +// wallet balance, coin selection, refresh, or ordinary VTXO actor recovery. +type arkChannelRecoveryArchive struct { + vtxos *db.VTXOPersistenceStore + packages *db.OORArtifactPersistenceStore + watcher *arkChannelSourceWatcher + // A dedicated hub archive imports all packages. Two clients may + // describe the same signed ancestor with opposite wallet directions. + importOnly bool +} + +// newArkChannelRecoveryArchive constructs one endpoint-local recovery store. +func newArkChannelRecoveryArchive(vtxos *db.VTXOPersistenceStore, + packages *db.OORArtifactPersistenceStore, + backend chainsource.ChainBackend, + log btclog.Logger) (*arkChannelRecoveryArchive, error) { + + switch { + case vtxos == nil: + return nil, fmt.Errorf("Ark channel VTXO store is required") + + case packages == nil: + return nil, fmt.Errorf("Ark channel OOR package store is " + + "required") + + case backend == nil: + return nil, fmt.Errorf("Ark channel chain backend is required") + } + + return &arkChannelRecoveryArchive{ + vtxos: vtxos, packages: packages, + watcher: newArkChannelSourceWatcher(backend, log), + }, nil +} + +// BindChannelEventSink connects confirmed ancestry spends to the channel FSM. +func (a *arkChannelRecoveryArchive) BindChannelEventSink( + sink arkchannel.ChannelEventSink) error { + + return a.watcher.BindChannelEventSink(sink) +} + +// ExportRecoveryPackage builds the endpoint-neutral package only after the +// funder's finalized OOR artifacts are durable. +func (a *arkChannelRecoveryArchive) ExportRecoveryPackage(ctx context.Context, + id arkchannel.ID, terms arkchannel.Terms, + source arkchannel.VTXOBinding) (arkchannel.RecoveryPackage, error) { + + if err := validateArkChannelRecoveryRequest( + id, terms, source, + ); err != nil { + return arkchannel.RecoveryPackage{}, err + } + recoverySource := arkchannel.OORRecoverySource{ + OutPoint: source.OutPoint, Amount: source.Amount, + PkScript: source.PkScript, + } + recovery, err := a.buildRecoveryPackage( + ctx, terms.VTXO.ArkOperatorKey, recoverySource, + ) + if err != nil { + return arkchannel.RecoveryPackage{}, err + } + desc, err := arkChannelRecoveryDescriptor( + terms, source, recovery.Descriptor, + ) + if err != nil { + return arkchannel.RecoveryPackage{}, err + } + if err := a.vtxos.SaveRecoveryOnlyVTXO(ctx, desc); err != nil { + return arkchannel.RecoveryPackage{}, fmt.Errorf("save Ark "+ + "channel recovery source: %w", err) + } + if err := a.packages.UpsertBinding( + ctx, source.OutPoint, source.OORSessionID, + source.OutPoint.Index, db.OORPackageLinkKindCreatedOutput, + ); err != nil { + return arkchannel.RecoveryPackage{}, fmt.Errorf("bind Ark "+ + "channel recovery source: %w", err) + } + if _, err := a.verifySourceLineage(ctx, source.OutPoint); err != nil { + return arkchannel.RecoveryPackage{}, fmt.Errorf("verify "+ + "exported Ark channel lineage: %w", err) + } + + return recovery, nil +} + +// ExportOORRecoveryPackage exports one exact sender-owned finalized OOR +// package. The expected operator key binds its round ancestry to the daemon's +// current Ark operator rather than to caller-provided channel terms. +func (a *arkChannelRecoveryArchive) ExportOORRecoveryPackage( + ctx context.Context, source arkchannel.OORRecoverySource, + operatorKey *btcec.PublicKey) (arkchannel.RecoveryPackage, error) { + + if err := source.Validate(); err != nil { + return arkchannel.RecoveryPackage{}, err + } + if operatorKey == nil { + return arkchannel.RecoveryPackage{}, fmt.Errorf("Ark " + + "operator key is required") + } + var serializedOperator [33]byte + copy(serializedOperator[:], operatorKey.SerializeCompressed()) + + return a.buildRecoveryPackage(ctx, serializedOperator, source) +} + +// buildRecoveryPackage resolves one sender-owned finalized OOR package and +// all locally known ancestors into endpoint-neutral recovery data. +func (a *arkChannelRecoveryArchive) buildRecoveryPackage(ctx context.Context, + expectedOperator [33]byte, source arkchannel.OORRecoverySource) ( + arkchannel.RecoveryPackage, error) { + + target, err := a.loadSourcePackage(ctx, source) + if err != nil { + return arkchannel.RecoveryPackage{}, err + } + roots, err := a.loadSourceRoots( + ctx, recoveryCheckpointInputs(target), + ) + if err != nil { + return arkchannel.RecoveryPackage{}, err + } + ancestry, err := recoveryAncestry(roots) + if err != nil { + return arkchannel.RecoveryPackage{}, err + } + roundID, commitmentTxID, batchExpiry, createdHeight := + recoveryRootMeta(roots) + if roundID == "" || commitmentTxID == ([32]byte{}) || + batchExpiry == 0 || createdHeight == 0 { + return arkchannel.RecoveryPackage{}, fmt.Errorf("Ark channel " + + "source root metadata incomplete") + } + if _, err := channelOperatorKey(expectedOperator, roots); err != nil { + return arkchannel.RecoveryPackage{}, err + } + // A sender persists the finalized package by session ID but does not + // normally own or bind the output it created for the recipient. Resolve + // from that immutable package identity before installing the output as + // shared recovery state. + resolved, err := a.packages.ResolveUnrollPackagesBySessionID( + ctx, source.OutPoint, source.OutPoint.Hash, + ) + if err != nil { + return arkchannel.RecoveryPackage{}, fmt.Errorf("resolve Ark "+ + "channel OOR lineage: %w", err) + } + if err := validateRecoveryPackageRoots( + ancestry, resolved.UnresolvedCheckpointInputs, + ); err != nil { + return arkchannel.RecoveryPackage{}, err + } + constructionVersion, err := recoveryConstructionVersion(roots) + if err != nil { + return arkchannel.RecoveryPackage{}, err + } + recovery := arkchannel.RecoveryPackage{ + Descriptor: arkchannel.RecoveryDescriptor{ + RoundID: roundID, CommitmentTxID: commitmentTxID, + BatchExpiry: batchExpiry, + ChainDepth: recoveryChainDepth( + roots, len(resolved.Packages), + ), + CreatedHeight: createdHeight, + ConstructionVersion: int32(constructionVersion), + }, + Packages: make( + []arkchannel.RecoveryOORPackage, 0, + len(resolved.Packages), + ), + } + for i := range ancestry { + treePath, err := db.SerializeTree(ancestry[i].TreePath) + if err != nil { + return arkchannel.RecoveryPackage{}, fmt.Errorf( + "serialize Ark channel ancestry %d: %w", i, err) + } + recovery.Descriptor.Ancestry = append( + recovery.Descriptor.Ancestry, + arkchannel.RecoveryAncestry{ + TreePath: treePath, + CommitmentTxID: ancestry[i].CommitmentTxID, + InputIndices: append( + []uint32(nil), + ancestry[i].InputIndices..., + ), + TreeDepth: ancestry[i].TreeDepth, + CommitmentHeight: ancestry[i].CommitmentHeight, + }, + ) + } + for i := range resolved.Packages { + entry, err := recoveryOORPackage(resolved.Packages[i]) + if err != nil { + return arkchannel.RecoveryPackage{}, fmt.Errorf( + "serialize Ark channel OOR package %d: %w", i, + err) + } + recovery.Packages = append(recovery.Packages, entry) + } + if err := recovery.ValidateOORSource(source); err != nil { + return arkchannel.RecoveryPackage{}, err + } + + return recovery, nil +} + +// InstallRecoveryPackage writes every artifact, validates local resolution, +// and arms all ancestry watches before returning the activation barrier. +func (a *arkChannelRecoveryArchive) InstallRecoveryPackage(ctx context.Context, + id arkchannel.ID, terms arkchannel.Terms, source arkchannel.VTXOBinding, + recovery arkchannel.RecoveryPackage) error { + + if err := validateArkChannelRecoveryRequest( + id, terms, source, + ); err != nil { + return err + } + if err := recovery.Validate(source); err != nil { + return err + } + desc, err := arkChannelRecoveryDescriptor( + terms, source, recovery.Descriptor, + ) + if err != nil { + return err + } + if err := validateArkChannelRecoveryProof( + ctx, desc, recovery, a.watcher.backend, + ); err != nil { + return fmt.Errorf("authenticate Ark channel recovery: %w", err) + } + for i := range recovery.Packages { + entry := recovery.Packages[i] + arkPSBT, checkpoints, err := parseRecoveryOORPackage(entry) + if err != nil { + return fmt.Errorf("parse Ark channel OOR package "+ + "%d: %w", i, err) + } + direction := db.OORPackageDirection(entry.Direction) + if a.importOnly { + direction = db.OORPackageDirectionIncoming + } + if err := a.packages.UpsertPackage( + ctx, direction, entry.SessionID, arkPSBT, checkpoints, + ); err != nil { + return fmt.Errorf("store Ark channel OOR package "+ + "%d: %w", i, err) + } + } + existing, err := a.vtxos.GetVTXO(ctx, source.OutPoint) + switch { + case err == nil: + // Recovery installation is replayable after a close path has + // selected its final CSV delay. Preserve that mutable field + // while SaveRecoveryOnlyVTXO verifies every immutable + // descriptor field. + desc.RelativeExpiry = existing.RelativeExpiry + + case !errors.Is(err, vtxo.ErrVTXONotFound): + return fmt.Errorf("load Ark channel recovery source: %w", err) + } + if err := a.vtxos.SaveRecoveryOnlyVTXO(ctx, desc); err != nil { + return fmt.Errorf("save Ark channel recovery source: %w", err) + } + if err := a.packages.UpsertBinding( + ctx, source.OutPoint, source.OORSessionID, + source.OutPoint.Index, db.OORPackageLinkKindCreatedOutput, + ); err != nil { + return fmt.Errorf("bind Ark channel OOR source: %w", err) + } + proof, err := a.verifySourceLineage(ctx, source.OutPoint) + if err != nil { + return fmt.Errorf("verify installed Ark channel lineage: %w", + err) + } + height, _, err := a.watcher.backend.BestBlock(ctx) + if err != nil { + return err + } + if err := validateArkChannelRecoveryWindow( + proof, terms.VTXO.FunderDelay, height, + ); err != nil { + return err + } + if err := a.watcher.Track(ctx, id, desc); err != nil { + return fmt.Errorf("watch Ark channel source: %w", err) + } + + return nil +} + +// RestoreWatches re-arms every channel whose Ark source still secures either +// an open channel or the replacement VTXOs from an in-Ark refresh. +func (a *arkChannelRecoveryArchive) RestoreWatches(ctx context.Context, + records []arkchannel.Record) error { + + return restoreArkChannelSourceWatches( + ctx, records, a.vtxos.GetVTXO, a.watcher.Track, + ) +} + +// SourceExpiring derives the exit deadline from authenticated, persisted +// evidence. Peer metadata and wall-clock time cannot extend a batch's life. +func (a *arkChannelRecoveryArchive) SourceExpiring(ctx context.Context, + terms arkchannel.Terms, source arkchannel.VTXOBinding, height int32) ( + bool, error) { + + desc, err := a.vtxos.GetVTXO(ctx, source.OutPoint) + if err != nil { + return false, err + } + deadline, err := arkchannel.SourceMaterializationHeight( + desc.BatchExpiry, terms.VTXO.FunderDelay, + ) + if err != nil { + return false, err + } + if height < 0 { + return false, fmt.Errorf("current chain height is unavailable") + } + + return height >= deadline, nil +} + +// arkChannelSourceWatchTracker arms source watches for one durable channel. +type arkChannelSourceWatchTracker func(context.Context, arkchannel.ID, + *vtxo.Descriptor) error + +// restoreArkChannelSourceWatches restores every eligible source independently +// so one damaged record cannot suppress protection for healthy channels. +func restoreArkChannelSourceWatches(ctx context.Context, + records []arkchannel.Record, + load func(context.Context, wire.OutPoint) (*vtxo.Descriptor, error), + track arkChannelSourceWatchTracker) error { + + failures := make([]arkchannel.ResumeFailure, 0) + for i := range records { + snapshot := records[i].Snapshot + if !shouldRestoreArkChannelSourceWatch(snapshot) { + continue + } + desc, err := load(ctx, snapshot.Source.OutPoint) + if err != nil { + failures = append(failures, arkchannel.ResumeFailure{ + ChannelID: snapshot.Terms.ID, + Err: fmt.Errorf( + "load recovery source: %w", err, + ), + }) + + continue + } + if err := track( + ctx, snapshot.Terms.ID, desc, + ); err != nil { + + failures = append(failures, arkchannel.ResumeFailure{ + ChannelID: snapshot.Terms.ID, + Err: fmt.Errorf( + "restore source watch: %w", err, + ), + }) + } + } + if len(failures) > 0 { + return &arkchannel.ResumeFailures{Failures: failures} + } + + return nil +} + +// shouldRestoreArkChannelSourceWatch reports whether confirmed ancestry can +// still require a durable channel action. Once conflict evidence is stored, +// Service.Resume owns retries and another chain registration is unnecessary. +func shouldRestoreArkChannelSourceWatch(snapshot arkchannel.Snapshot) bool { + if (!snapshot.ClientRecoveryReady && !snapshot.HubRecoveryReady) || + snapshot.Source == nil || + snapshot.SourceConflict != nil { + return false + } + if !snapshot.Phase.IsTerminal() { + return true + } + + return snapshot.Phase == arkchannel.PhaseClosed && + snapshot.CooperativeClose != nil +} + +// EnsureChannelSource selects the final-spend delay and verifies that the +// pre-activation recovery package remains complete for the common unroller. +func (a *arkChannelRecoveryArchive) EnsureChannelSource(ctx context.Context, + id arkchannel.ID, terms arkchannel.Terms, source arkchannel.VTXOBinding, + kind unroll.ExitPolicyKind) error { + + if err := validateArkChannelRecoveryRequest( + id, terms, source, + ); err != nil { + return err + } + csvDelay, err := channelSourceCSVDelay(terms, kind) + if err != nil { + return err + } + if err := a.vtxos.SetRecoveryOnlyVTXORelativeExpiry( + ctx, source.OutPoint, csvDelay, + ); err != nil { + return fmt.Errorf("set Ark channel recovery delay: %w", err) + } + if _, err := a.verifySourceLineage(ctx, source.OutPoint); err != nil { + return fmt.Errorf("verify Ark channel lineage: %w", err) + } + + return nil +} + +// verifySourceLineage runs the common production resolver against the exact +// recovery-only descriptor that a later unroll job will consume. +func (a *arkChannelRecoveryArchive) verifySourceLineage(ctx context.Context, + outpoint wire.OutPoint) (*recovery.Proof, error) { + + resolver := unroll.DescriptorLineageResolver{ + VTXOStore: a.vtxos, + ArtifactStore: a.packages, + } + material, err := resolver.ResolveLineage(ctx, outpoint) + if err != nil { + return nil, err + } + + return unroll.BuildProofFromMaterial(material) +} + +// WaitForChannelBacking distinguishes publication from a winning chain spend. +// An authorized refresh may still beat an unconfirmed backing, so native close +// and archival must not infer the winner from mempool presence alone. +func (a *arkChannelRecoveryArchive) WaitForChannelBacking(ctx context.Context, + id arkchannel.ID, backing arkchannel.Backing) error { + + tx := wire.NewMsgTx(2) + if err := tx.Deserialize( + bytes.NewReader(backing.Transaction), + ); err != nil { + return err + } + if uint64(backing.ChannelPoint.Index) >= uint64(len(tx.TxOut)) { + return fmt.Errorf("channel backing output is missing") + } + registration, err := a.watcher.backend.RegisterConf( + ctx, &backing.ChannelPoint.Hash, + tx.TxOut[backing.ChannelPoint.Index].PkScript, 1, 0, false, + ) + if err != nil { + return err + } + defer registration.Cancel() + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + for { + select { + case confirmation, ok := <-registration.Confirmed: + if !ok || confirmation == nil || + confirmation.Tx == nil || + confirmation.BlockHeight == 0 || + confirmation.Tx.TxHash() != backing. + ChannelPoint. + Hash { + return fmt.Errorf("channel backing " + + "confirmation is unavailable") + } + + return nil + + case <-ctx.Done(): + return ctx.Err() + + case <-ticker.C: + a.watcher.mu.Lock() + sink := a.watcher.sink + a.watcher.mu.Unlock() + reader, ok := sink.(interface { + GetChannel(context.Context, + arkchannel.ID) ( + arkchannel.Record, + error, + ) + }) + if !ok { + return fmt.Errorf("channel resolution reader " + + "is unavailable") + } + record, err := reader.GetChannel(ctx, id) + if err != nil { + return err + } + phase := record.Snapshot.Phase + if phase == arkchannel.PhaseCoopClosePublished || + phase == arkchannel.PhaseClosed { + return fmt.Errorf("channel already resolved " + + "through its cooperative payout") + } + } + } +} + +// validateRecoveryPackageRoots accepts package traversal endpoints only when +// the transported round ancestry supplies the transaction they spend. +func validateRecoveryPackageRoots(ancestry []vtxo.Ancestry, + unresolved []wire.OutPoint) error { + + if len(unresolved) == 0 { + return nil + } + treeOutputs := make(map[wire.OutPoint]struct{}) + for i := range ancestry { + fragment := ancestry[i] + if fragment.TreePath == nil || fragment.TreePath.Root == nil { + return fmt.Errorf("Ark channel ancestry %d has no tree", + i) + } + for node := range fragment.TreePath.Root.NodesIter() { + tx, err := node.ToTx() + if err != nil { + return fmt.Errorf("build Ark channel ancestry "+ + "%d: %w", i, err) + } + txID := tx.TxHash() + for outputIndex := range tx.TxOut { + treeOutputs[wire.OutPoint{ + Hash: txID, Index: uint32(outputIndex), + }] = struct{}{} + } + } + } + for _, outpoint := range unresolved { + if _, ok := treeOutputs[outpoint]; !ok { + return fmt.Errorf("Ark channel OOR lineage is "+ + "missing root %s", outpoint) + } + } + + return nil +} + +// Stop releases all passive source watches. +func (a *arkChannelRecoveryArchive) Stop() { + if a != nil && a.watcher != nil { + a.watcher.Stop() + } +} + +// loadSourcePackage verifies that the finalized target package creates the +// exact channel-policy output committed by the FSM. +func (a *arkChannelRecoveryArchive) loadSourcePackage(ctx context.Context, + source arkchannel.OORRecoverySource) (*db.OORPackageBundle, error) { + + pkg, err := a.packages.GetPackage(ctx, source.OutPoint.Hash) + if err != nil { + return nil, fmt.Errorf("load Ark channel OOR package: %w", err) + } + if pkg.ArkPSBT == nil || pkg.ArkPSBT.UnsignedTx == nil { + return nil, fmt.Errorf("Ark channel OOR package has no " + + "transaction") + } + tx := pkg.ArkPSBT.UnsignedTx + if pkg.SessionID != source.OutPoint.Hash || + tx.TxHash() != source.OutPoint.Hash { + return nil, fmt.Errorf("Ark channel OOR package ID mismatch") + } + if int(source.OutPoint.Index) >= len(tx.TxOut) { + return nil, fmt.Errorf("Ark channel OOR output is out of range") + } + output := tx.TxOut[source.OutPoint.Index] + if output.Value != int64(source.Amount) || + !bytes.Equal(output.PkScript, source.PkScript) { + return nil, fmt.Errorf("Ark channel OOR output mismatch") + } + if len(pkg.FinalCheckpointPSBTs) == 0 { + return nil, fmt.Errorf("Ark channel OOR package has no " + + "checkpoints") + } + + return pkg, nil +} + +// loadSourceRoots loads the wallet VTXOs consumed by the channel OOR package. +func (a *arkChannelRecoveryArchive) loadSourceRoots(ctx context.Context, + outpoints []wire.OutPoint) ([]*vtxo.Descriptor, error) { + + if len(outpoints) == 0 { + return nil, fmt.Errorf("Ark channel OOR package has no roots") + } + roots := make([]*vtxo.Descriptor, 0, len(outpoints)) + for _, outpoint := range outpoints { + desc, err := a.vtxos.GetVTXO(ctx, outpoint) + if err != nil { + return nil, fmt.Errorf("load Ark channel root %s: %w", + outpoint, err) + } + if len(desc.Ancestry) == 0 { + return nil, fmt.Errorf("Ark channel root %s has no "+ + "ancestry", outpoint) + } + roots = append(roots, desc) + } + + return roots, nil +} + +// channelOperatorKey verifies that the channel and all roots share one Ark +// operator under BIP-340 x-only key semantics. +func channelOperatorKey(expectedOperator [33]byte, + roots []*vtxo.Descriptor) (*btcec.PublicKey, error) { + + operatorKey, err := btcec.ParsePubKey(expectedOperator[:]) + if err != nil { + return nil, fmt.Errorf("parse Ark channel operator key: %w", + err) + } + rootOperatorKey, err := recoveryOperatorKey(roots) + if err != nil { + return nil, err + } + if !bytes.Equal( + schnorr.SerializePubKey(operatorKey), + schnorr.SerializePubKey(rootOperatorKey), + ) { + return nil, fmt.Errorf("Ark channel operator does not match " + + "roots") + } + + return operatorKey, nil +} + +// recoveryConstructionVersion requires every contributing root to use the +// same Ark construction rules. +func recoveryConstructionVersion(roots []*vtxo.Descriptor) ( + arkrpc.ConstructionVersion, error) { + + if len(roots) == 0 || roots[0] == nil { + return 0, fmt.Errorf("Ark channel recovery roots are empty") + } + version := roots[0].ConstructionVersion + for i := 1; i < len(roots); i++ { + if roots[i] == nil || roots[i].ConstructionVersion != version { + return 0, fmt.Errorf("Ark channel roots use multiple " + + "construction versions") + } + } + + return version, nil +} + +// recoveryOORPackage serializes one persisted OOR package for transport. +func recoveryOORPackage(pkg *db.OORPackageBundle) ( + arkchannel.RecoveryOORPackage, error) { + + if pkg == nil || pkg.ArkPSBT == nil { + return arkchannel.RecoveryOORPackage{}, fmt.Errorf("package " + + "is nil") + } + arkPSBT, err := psbtutil.Serialize(pkg.ArkPSBT) + if err != nil { + return arkchannel.RecoveryOORPackage{}, err + } + entry := arkchannel.RecoveryOORPackage{ + SessionID: pkg.SessionID, Direction: int32(pkg.Direction), + ArkPSBT: arkPSBT, + Checkpoints: make([][]byte, len(pkg.FinalCheckpointPSBTs)), + } + for i := range pkg.FinalCheckpointPSBTs { + entry.Checkpoints[i], err = psbtutil.Serialize( + pkg.FinalCheckpointPSBTs[i], + ) + if err != nil { + return arkchannel.RecoveryOORPackage{}, err + } + } + + return entry, nil +} + +// parseRecoveryOORPackage decodes and verifies one transported package. +func parseRecoveryOORPackage(entry arkchannel.RecoveryOORPackage) (*psbt.Packet, + []*psbt.Packet, error) { + + arkPSBT, err := psbt.NewFromRawBytes( + bytes.NewReader(entry.ArkPSBT), false, + ) + if err != nil { + return nil, nil, err + } + if arkPSBT.UnsignedTx == nil || + arkPSBT.UnsignedTx.TxHash() != entry.SessionID { + return nil, nil, fmt.Errorf("OOR session ID does not match " + + "Ark tx") + } + checkpoints := make([]*psbt.Packet, len(entry.Checkpoints)) + for i := range entry.Checkpoints { + checkpoints[i], err = psbt.NewFromRawBytes( + bytes.NewReader(entry.Checkpoints[i]), false, + ) + if err != nil { + return nil, nil, fmt.Errorf("checkpoint %d: %w", i, err) + } + if checkpoints[i].UnsignedTx == nil { + return nil, nil, fmt.Errorf("checkpoint %d has no tx", + i) + } + } + + return arkPSBT, checkpoints, nil +} + +// arkChannelRecoveryDescriptor reconstructs a channel recovery-only VTXO. +func arkChannelRecoveryDescriptor(terms arkchannel.Terms, + source arkchannel.VTXOBinding, + recovery arkchannel.RecoveryDescriptor) (*vtxo.Descriptor, error) { + + clientKey, err := btcec.ParsePubKey(terms.VTXO.ClientArkKey[:]) + if err != nil { + return nil, err + } + operatorKey, err := btcec.ParsePubKey(terms.VTXO.ArkOperatorKey[:]) + if err != nil { + return nil, err + } + ancestry := make([]vtxo.Ancestry, len(recovery.Ancestry)) + for i := range recovery.Ancestry { + entry := recovery.Ancestry[i] + treePath, err := db.DeserializeTree( + recovery.Ancestry[i].TreePath, + ) + if err != nil { + return nil, fmt.Errorf("decode Ark channel ancestry "+ + "%d: %w", i, err) + } + ancestry[i] = vtxo.Ancestry{ + TreePath: treePath, + CommitmentTxID: entry.CommitmentTxID, + InputIndices: append( + []uint32(nil), + recovery.Ancestry[i].InputIndices..., + ), + TreeDepth: entry.TreeDepth, + CommitmentHeight: entry.CommitmentHeight, + CommitmentSweepDelay: treePath.SweepDelay, + CommitmentSweepKey: treePath.SweepKey, + } + } + + return &vtxo.Descriptor{ + Outpoint: source.OutPoint, Amount: source.Amount, + PolicyTemplate: append([]byte(nil), source.PolicyTemplate...), + PkScript: append([]byte(nil), source.PkScript...), + ClientKey: keychain.KeyDescriptor{ + PubKey: clientKey, + }, + OperatorKey: operatorKey, Ancestry: ancestry, + RoundID: recovery.RoundID, + CommitmentTxID: recovery.CommitmentTxID, + BatchExpiry: recovery.BatchExpiry, + // The non-interactive fallback is the pre-signed client+hub + // channel path. Persist its delay before watches are armed so a + // confirmed ancestor cannot race proof assembly against a later + // mutable update. In-Ark refresh uses the ordinary OOR actor + // and never enters the unroller. + RelativeExpiry: terms.VTXO.ChannelDelay, + ChainDepth: recovery.ChainDepth, + CreatedHeight: recovery.CreatedHeight, + Status: vtxo.VTXOStatusRecoveryOnly, + ConstructionVersion: arkrpc.ConstructionVersion( + recovery.ConstructionVersion, + ), + }, nil +} + +// validateArkChannelRecoveryRequest binds all archive operations to one FSM. +func validateArkChannelRecoveryRequest(id arkchannel.ID, terms arkchannel.Terms, + source arkchannel.VTXOBinding) error { + + if id != terms.ID { + return fmt.Errorf("Ark channel ID does not match terms") + } + if err := terms.Validate(); err != nil { + return err + } + + return source.Validate(terms) +} + +// channelSourceCSVDelay selects the delay of the exact final spend policy. +func channelSourceCSVDelay(terms arkchannel.Terms, + kind unroll.ExitPolicyKind) (uint32, error) { + + if kind != unrollbridge.ExitPolicyKind { + return 0, fmt.Errorf("unsupported Ark channel exit policy %q", + kind) + } + + return terms.VTXO.ChannelDelay, nil +} + +var _ unrollbridge.SourcePreparer = (*arkChannelRecoveryArchive)(nil) +var _ arkchannel.ChannelEventSinkBinder = (*arkChannelRecoveryArchive)(nil) diff --git a/waved/ark_channel_source_expiry.go b/waved/ark_channel_source_expiry.go new file mode 100644 index 000000000..7f59d725f --- /dev/null +++ b/waved/ark_channel_source_expiry.go @@ -0,0 +1,282 @@ +package waved + +import ( + "context" + "fmt" + + "github.com/btcsuite/btclog/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/chainsource" + "github.com/lightningnetwork/lnd/clock" +) + +// runSourceExpiryGuard reconciles the current tip after registration and every +// wakeup. A closed or overflowing block stream is re-registered, so missed +// heights and restarts cannot move an authenticated recovery deadline. +func (c *NativeArkChannelController) runSourceExpiryGuard(ctx context.Context, + service *arkchannel.Service, node arkChannelForceCloseResumer) { + + protect := func(height int32) { + err := c.protectExpiringSources(ctx, service, node, height) + _ = tolerateNativeArkChannelFailures( + ctx, err, c.cfg.Log, + "Ark channel source expiry protection failed", + ) + } + if tip := c.cfg.SourceExpiryTip; tip != nil { + for ctx.Err() == nil { + height, next := tip() + if height >= 0 { + protect(height) + } + select { + case <-ctx.Done(): + return + + case <-next: + } + } + + return + } + watchSourceExpiryTip( + ctx, c.cfg.ChainBackend, c.cfg.Clock, c.cfg.Log, protect, + ) +} + +// watchSourceExpiryTip reads the authoritative height on registration and +// wakeup. A dropped notification is not proof that the deadline is distant. +func watchSourceExpiryTip(ctx context.Context, backend chainsource.ChainBackend, + clk clock.Clock, log btclog.Logger, notify func(int32)) { + + refresh := func() { + height, _, err := backend.BestBlock(ctx) + if err == nil { + notify(height) + } + } + warned := false + for ctx.Err() == nil { + registration, err := backend.RegisterBlocks(ctx) + if err != nil && !warned && log != nil { + log.WarnS(ctx, "Ark channel expiry watch unavailable", + err, + ) + warned = true + } + if err != nil { + // A broken notification stream need not imply a broken + // tip query. Reconcile even while re-registering. + refresh() + } else { + warned = false + for ctx.Err() == nil { + refresh() + select { + case <-ctx.Done(): + registration.Cancel() + + return + + case _, ok := <-registration.Epochs: + if !ok { + registration.Cancel() + goto retry + } + + case <-clk.TickAfter( + defaultArkChannelPrePONRScanInterval, + ): + // Retry store/backend failures even if + // no new block follows the threshold + // crossing. + } + } + registration.Cancel() + } + + retry: + select { + case <-ctx.Done(): + return + + case <-clk.TickAfter( + defaultArkChannelClientRetryInterval, + ): + } + } +} + +// protectExpiringSources persists each handoff before starting its existing +// replay worker. Waiting for CSV or CPFP never blocks another channel's guard. +func (c *NativeArkChannelController) protectExpiringSources(ctx context.Context, + service *arkchannel.Service, node arkChannelForceCloseResumer, + height int32) error { + + records, err := service.ListChannels(ctx) + if err != nil { + return err + } + failures := make([]arkchannel.ResumeFailure, 0) + for _, record := range records { + snapshot := record.Snapshot + //nolint:contextcheck // controller-owned observation + c.watchExpiringPayout(service, snapshot) + if !needsSourceExpiryProtection(snapshot) { + continue + } + expiring, err := c.cfg.Recovery.SourceExpiring( + ctx, snapshot.Terms, *snapshot.Source, height, + ) + if err == nil && expiring { + var protected arkchannel.Record + protected, _, err = c.coordinator.Apply( + ctx, snapshot.Terms.ID, + &arkchannel.SourceExpiring{}, + ) + if err == nil { + //nolint:contextcheck // owned + c.watchExpiringPayout( + service, protected.Snapshot, + ) + //nolint:contextcheck // owned + c.startNativeArkChannelResume( + service, node, + []arkchannel.ID{snapshot.Terms.ID}, + ) + } + } + if err != nil { + failures = append(failures, arkchannel.ResumeFailure{ + ChannelID: snapshot.Terms.ID, + Err: fmt.Errorf("protect source expiry: "+ + "%w", err), + }) + } + } + if len(failures) != 0 { + return &arkchannel.ResumeFailures{Failures: failures} + } + + return nil +} + +// needsSourceExpiryProtection excludes completed, already-published, and +// already-handed-off channels. Their existing recovery worker owns retries. +func needsSourceExpiryProtection(snapshot arkchannel.Snapshot) bool { + if snapshot.Source == nil || !snapshot.OORFinalized || + (!snapshot.ClientRecoveryReady && !snapshot.HubRecoveryReady) { + return false + } + switch snapshot.Phase { + case arkchannel.PhaseBackingReady, arkchannel.PhaseActivating, + arkchannel.PhaseActive, arkchannel.PhaseCoopClosing, + arkchannel.PhaseCoopCloseSigned: + return true + + default: + return false + } +} + +// watchExpiringPayout retains both resolution candidates after expiry wins +// the phase race. Its in-memory deduplication is rebuilt from durable state on +// restart; it never authorizes a payout or consumes a pending control request. +func (c *NativeArkChannelController) watchExpiringPayout( + service *arkchannel.Service, snapshot arkchannel.Snapshot) { + + if snapshot.CooperativeClose == nil || + (snapshot.Phase != arkchannel.PhaseMaterializing && + snapshot.Phase != arkchannel.PhaseOnChain) { + return + } + if _, exists := c.expiryPayoutWatches.LoadOrStore( + snapshot.Terms.ID, struct{}{}, + ); exists { + return + } + c.startLifecycleWorker(func(ctx context.Context) { + defer c.expiryPayoutWatches.Delete(snapshot.Terms.ID) + c.observeExpiringPayout(ctx, service, snapshot) + }) +} + +// observeExpiringPayout accepts only local confirmation of the exact agreed +// transaction. A peer's OOR-finalized receipt cannot prove a competing backing +// lost and therefore cannot retire native watchers after expiry protection. +func (c *NativeArkChannelController) observeExpiringPayout(ctx context.Context, + service *arkchannel.Service, snapshot arkchannel.Snapshot) { + + settlement := snapshot.CooperativeClose + template, err := arkchannel.NewCooperativeCloseTemplate( + snapshot.Terms, *snapshot.Source, + *snapshot.CooperativeCloseRequest, + settlement.Proposal.ClientBalance, + settlement.Proposal.HubBalance, + settlement.Proposal.CommitmentHeight, + ) + if err != nil { + return + } + script := template.ArkTransaction().TxOut[0].PkScript + for ctx.Err() == nil { + registration, err := c.cfg.ChainBackend.RegisterConf( + ctx, &settlement.TxID, script, 1, 0, false, + ) + if err == nil { + select { + case confirmation, ok := <-registration.Confirmed: + event := &arkchannel.CooperativeCloseObserved{ + TxID: settlement.TxID, + } + valid := ok && confirmation != nil && + confirmation.Tx != nil && + confirmation.BlockHeight > 0 + if valid { + valid = confirmation.Tx.TxHash() == + settlement.TxID + } + if valid { + _, err = service.ApplyLocalEvent( + ctx, snapshot.Terms.ID, event, + ) + registration.Cancel() + if err == nil { + return + } + } else { + registration.Cancel() + } + + case <-ctx.Done(): + registration.Cancel() + + return + + case <-c.cfg.Clock.TickAfter( + defaultArkChannelPrePONRScanInterval, + ): + registration.Cancel() + record, err := service.GetChannel( + ctx, snapshot.Terms.ID, + ) + phase := record.Snapshot.Phase + settled := record.Snapshot.CooperativeClose == + nil + resolved := settled || + phase == arkchannel.PhaseClosed + if err == nil && resolved { + return + } + } + } + select { + case <-ctx.Done(): + return + + case <-c.cfg.Clock.TickAfter( + defaultArkChannelClientRetryInterval, + ): + } + } +} diff --git a/waved/ark_channel_source_expiry_test.go b/waved/ark_channel_source_expiry_test.go new file mode 100644 index 000000000..97db86429 --- /dev/null +++ b/waved/ark_channel_source_expiry_test.go @@ -0,0 +1,327 @@ +package waved + +import ( + "context" + "fmt" + "runtime" + "sync" + "testing" + "time" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btclog/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/chainsource" + "github.com/lightninglabs/wavelength/db" + "github.com/lightningnetwork/lnd/clock" + "github.com/stretchr/testify/require" +) + +// sourceExpiryBackend allows tip jumps, dropped subscriptions, and registration +// failures without changing the persisted channel lifecycle. +type sourceExpiryBackend struct { + chainsource.ChainBackend + mu sync.Mutex + height int32 + registrations []chan *chainsource.BlockEpoch +} + +// offlineEpochBackend supplies an authoritative tip but no notification feed. +type offlineEpochBackend struct{ *sourceExpiryBackend } + +// RegisterBlocks simulates a disconnected subscription independently of RPC. +func (offlineEpochBackend) RegisterBlocks(context.Context) ( + *chainsource.BlockRegistration, error) { + + return nil, fmt.Errorf("stream offline") +} + +// TestExpiryTipWithoutStream ensures a failed subscription cannot suppress +// catch-up when the backend can still answer an authoritative tip query. +func TestExpiryTipWithoutStream(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + backend := offlineEpochBackend{&sourceExpiryBackend{height: 701}} + var tip int32 + watchSourceExpiryTip( + ctx, backend, clock.NewDefaultClock(), btclog.Disabled, + func(height int32) { + tip = height + cancel() + }, + ) + require.EqualValues(t, 701, tip) +} + +// TestHubRecoverySharedExpiry verifies that endpoint recovery views have one +// height subscription and still observe a missed-height jump. Idle endpoint +// counts are diagnostic; the subscription count is a correctness assertion. +func TestHubRecoverySharedExpiry(t *testing.T) { + raw, _ := testArkChannelResumeStore(t, t.TempDir()) + t.Cleanup(func() { require.NoError(t, raw.Close()) }) + backend := &sourceExpiryBackend{height: 100} + hub, err := NewArkChannelRecoveryRuntime( + t.Context(), ArkChannelRecoveryRuntimeConfig{ + Store: raw, + ChannelStore: raw.NewArkChannelStore( + clock.NewDefaultClock(), + ), + Wallet: struct{ ArkChannelUnrollWallet }{}, + ChainBackend: backend, + Log: btclog.Disabled, + }, + ) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, hub.Stop()) }) + require.Eventually(t, func() bool { + height, _ := hub.SourceExpiryTip() + + return height == 100 + }, time.Second, time.Millisecond) + _, firstWake := hub.SourceExpiryTip() + for n := 1; n <= 100; n++ { + view, _, err := hub.NewEndpoint() + require.NoError(t, err) + t.Cleanup(view.Stop) + _, next := hub.SourceExpiryTip() + require.Equal(t, firstWake, next) + if n == 1 || n == 100 { + t.Logf( + "%d idle recovery views: %d process "+ + "goroutines, %d open SQL connections", + n, runtime.NumGoroutine(), + raw.DB().Stats().OpenConnections, + ) + } + } + backend.mu.Lock() + count := len(backend.registrations) + backend.height = 120 + stream := backend.registrations[0] + backend.mu.Unlock() + require.Equal(t, 1, count) + stream <- &chainsource.BlockEpoch{Height: 120} + select { + case <-firstWake: + case <-time.After(time.Second): + t.Fatal("shared tip did not wake recovery views") + } + height, _ := hub.SourceExpiryTip() + require.EqualValues(t, 120, height) +} + +// BestBlock returns the independently observed test tip. +func (b *sourceExpiryBackend) BestBlock(context.Context) (int32, chainhash.Hash, + error) { + + b.mu.Lock() + defer b.mu.Unlock() + + return b.height, chainhash.Hash{}, nil +} + +// RegisterBlocks records a process-owned subscription. +func (b *sourceExpiryBackend) RegisterBlocks(context.Context) ( + *chainsource.BlockRegistration, error) { + + b.mu.Lock() + defer b.mu.Unlock() + stream := make(chan *chainsource.BlockEpoch, 1) + b.registrations = append(b.registrations, stream) + + return &chainsource.BlockRegistration{ + Epochs: stream, Cancel: func() {}, + }, nil +} + +// sourceExpiryRecovery isolates the deadline query from materialization. The +// archive's descriptor validation is exercised in its recovery tests. +type sourceExpiryRecovery struct { + ArkChannelRecoveryController + expiry int32 +} + +// Stop leaves the test-owned deadline fixture intact. +func (r sourceExpiryRecovery) Stop() {} + +// SourceExpiring uses the production deadline arithmetic over persisted data. +func (r sourceExpiryRecovery) SourceExpiring(_ context.Context, + terms arkchannel.Terms, _ arkchannel.VTXOBinding, height int32) (bool, + error) { + + deadline, err := arkchannel.SourceMaterializationHeight( + r.expiry, terms.VTXO.FunderDelay, + ) + + return height >= deadline, err +} + +// TestSourceExpiryArchiveSurvivesRestart derives the guard from the exact +// recovery-only descriptor after reopening the production SQL store. +func TestSourceExpiryArchiveSurvivesRestart(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + raw, coordinator := testArkChannelResumeStore(t, dir) + initial := testArkChannelResumeRecord(t, coordinator, false) + terms := initial.Snapshot.Terms + source := *initial.Snapshot.Source + desc, err := arkChannelRecoveryDescriptor( + terms, source, arkchannel.RecoveryDescriptor{ + RoundID: "expiry-round", BatchExpiry: 1_000, + CreatedHeight: 100, + CommitmentTxID: chainhash.Hash{1}, + }, + ) + require.NoError(t, err) + require.NoError( + t, + raw.NewVTXOStore( + clock.NewDefaultClock()). + SaveRecoveryOnlyVTXO(t.Context(), + desc, + ), + ) + require.NoError(t, raw.Close()) + raw, err = db.NewStoreFromConfig(db.DefaultConfig(dir), btclog.Disabled) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, raw.Close()) }) + archive := &arkChannelRecoveryArchive{ + vtxos: raw.NewVTXOStore(clock.NewDefaultClock()), + } + deadline, err := arkchannel.SourceMaterializationHeight( + 1_000, terms.VTXO.FunderDelay, + ) + require.NoError(t, err) + for _, height := range []int32{deadline - 1, deadline, 1_001} { + expiring, err := archive.SourceExpiring( + t.Context(), terms, source, height, + ) + require.NoError(t, err) + require.Equal(t, height >= deadline, expiring) + } + _, err = archive.SourceExpiring(t.Context(), terms, source, -1) + require.Error(t, err) +} + +// TestSourceExpiryGuardCatchesMissedBlocks proves a lost stream is replaced, +// its queued heights are not trusted, and recovery starts without a new block +// after reconnect. The SQL transition precedes a blocking materializer. +func TestSourceExpiryGuardCatchesMissedBlocks(t *testing.T) { + t.Parallel() + + raw, coordinator := testArkChannelResumeStore(t, t.TempDir()) + t.Cleanup(func() { require.NoError(t, raw.Close()) }) + initial := testArkChannelResumeRecord(t, coordinator, false) + deadline, err := arkchannel.SourceMaterializationHeight( + 1_000, initial.Snapshot.Terms.VTXO.FunderDelay, + ) + require.NoError(t, err) + backend := &sourceExpiryBackend{height: deadline - 1} + started := make(chan struct{}, 1) + service, err := arkchannel.NewService( + arkchannel.PartyHub, coordinator, + arkChannelResumeExecutor(func(ctx context.Context, + _ arkchannel.ID, action arkchannel.Action) error { + + if _, ok := action.(*arkchannel.PublishChannel); !ok { + return fmt.Errorf("unexpected expiry action %T", + action) + } + started <- struct{}{} + <-ctx.Done() + + return ctx.Err() + }), + ) + require.NoError(t, err) + controller := testArkChannelResumeController(t) + controller.coordinator = coordinator + controller.cfg.ChainBackend = backend + controller.cfg.Recovery = sourceExpiryRecovery{expiry: 1_000} + testClock := clock.NewTestClock(time.Now()) + controller.cfg.Clock = testClock + controller.startLifecycleWorker(func(ctx context.Context) { + controller.runSourceExpiryGuard(ctx, service, nil) + }) + require.Eventually(t, func() bool { + backend.mu.Lock() + defer backend.mu.Unlock() + + return len(backend.registrations) == 1 + }, time.Second, time.Millisecond) + record, err := coordinator.Get(t.Context(), initial.Snapshot.Terms.ID) + require.NoError(t, err) + require.Equal(t, arkchannel.PhaseActive, record.Snapshot.Phase) + select { + case <-started: + t.Fatal("source materialized before its deadline") + + default: + } + backend.mu.Lock() + backend.height = deadline + 5 + close(backend.registrations[0]) + backend.mu.Unlock() + require.Eventually(t, func() bool { + testClock.SetTime(testClock.Now().Add(time.Second)) + backend.mu.Lock() + defer backend.mu.Unlock() + + return len(backend.registrations) >= 2 + }, time.Second, time.Millisecond) + select { + case <-started: + case <-time.After(5 * time.Second): + t.Fatal("source deadline was lost with the block stream") + } + record, err = coordinator.Get(t.Context(), initial.Snapshot.Terms.ID) + require.NoError(t, err) + require.Equal(t, arkchannel.PhaseMaterializing, record.Snapshot.Phase) + require.Nil(t, record.Snapshot.SourceConflict) + _, err = arkchannel.PendingAction(record.Snapshot) + require.NoError(t, err) + controller.Quiesce() +} + +// TestSourceExpiryGuardStartupCatchup proves startup does not wait for the +// next block when the persisted source deadline passed while offline. +func TestSourceExpiryGuardStartupCatchup(t *testing.T) { + t.Parallel() + + raw, coordinator := testArkChannelResumeStore(t, t.TempDir()) + t.Cleanup(func() { require.NoError(t, raw.Close()) }) + initial := testArkChannelResumeRecord(t, coordinator, false) + started := make(chan struct{}, 1) + service, err := arkchannel.NewService( + arkchannel.PartyHub, coordinator, + arkChannelResumeExecutor(func(ctx context.Context, + _ arkchannel.ID, _ arkchannel.Action) error { + + started <- struct{}{} + <-ctx.Done() + + return ctx.Err() + }), + ) + require.NoError(t, err) + controller := testArkChannelResumeController(t) + controller.coordinator = coordinator + controller.cfg.ChainBackend = &sourceExpiryBackend{height: 500} + controller.cfg.Recovery = sourceExpiryRecovery{expiry: 1_000} + controller.startLifecycleWorker(func(ctx context.Context) { + controller.runSourceExpiryGuard(ctx, service, nil) + }) + select { + case <-started: + case <-time.After(5 * time.Second): + t.Fatal( + "startup waited for a future block to protect the " + + "source", + ) + } + record, err := coordinator.Get(t.Context(), initial.Snapshot.Terms.ID) + require.NoError(t, err) + require.Equal(t, arkchannel.PhaseMaterializing, record.Snapshot.Phase) + controller.Quiesce() +} diff --git a/waved/ark_channel_source_test.go b/waved/ark_channel_source_test.go new file mode 100644 index 000000000..471bbb3ad --- /dev/null +++ b/waved/ark_channel_source_test.go @@ -0,0 +1,296 @@ +package waved + +import ( + "context" + "errors" + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/arkchannel/unrollbridge" + "github.com/lightninglabs/wavelength/db" + "github.com/lightninglabs/wavelength/vtxo" + "github.com/stretchr/testify/require" +) + +// TestValidateRecoveryPackageRoots distinguishes an expected package boundary +// at a transported round tree from an actually missing OOR ancestor. +func TestValidateRecoveryPackageRoots(t *testing.T) { + t.Parallel() + + treePath, treeOutput := sourceWatcherTree(t, 42) + ancestry := []vtxo.Ancestry{ + { + TreePath: treePath, + }, + } + require.NoError( + t, + validateRecoveryPackageRoots( + ancestry, []wire.OutPoint{treeOutput}, + ), + ) + wrongIndex := treeOutput + wrongIndex.Index++ + require.ErrorContains( + t, + validateRecoveryPackageRoots( + ancestry, []wire.OutPoint{wrongIndex}, + ), + "missing root", + ) + require.ErrorContains( + t, + validateRecoveryPackageRoots( + ancestry, []wire.OutPoint{sourceWatcherOutpoint(43)}, + ), + "missing root", + ) +} + +// TestRecoveryDescriptorUsesBackingDelay proves a parent spend cannot race +// recovery proof assembly against selection of the pre-signed channel path. +func TestRecoveryDescriptorUsesBackingDelay(t *testing.T) { + t.Parallel() + + clientKey := testKeyDescriptor(t, 31) + operatorKey := testKeyDescriptor(t, 32) + terms := arkchannel.Terms{ + VTXO: arkchannel.VTXOTerms{ + ChannelDelay: 144, + }, + } + copy( + terms.VTXO.ClientArkKey[:], + clientKey.PubKey.SerializeCompressed(), + ) + copy( + terms.VTXO.ArkOperatorKey[:], + operatorKey.PubKey.SerializeCompressed(), + ) + treePath, target := sourceWatcherTree(t, 33) + rawTree, err := db.SerializeTree(treePath) + require.NoError(t, err) + + desc, err := arkChannelRecoveryDescriptor( + terms, arkchannel.VTXOBinding{ + OutPoint: target, + Amount: 100_000, + }, arkchannel.RecoveryDescriptor{ + Ancestry: []arkchannel.RecoveryAncestry{ + {TreePath: rawTree}, + }, + }, + ) + require.NoError(t, err) + require.Equal(t, terms.VTXO.ChannelDelay, desc.RelativeExpiry) + require.Equal(t, vtxo.VTXOStatusRecoveryOnly, desc.Status) + + backingDelay, err := channelSourceCSVDelay( + terms, unrollbridge.ExitPolicyKind, + ) + require.NoError(t, err) + require.Equal(t, terms.VTXO.ChannelDelay, backingDelay) + _, err = channelSourceCSVDelay(terms, "cooperative_close") + require.ErrorContains(t, err, "unsupported") +} + +// TestShouldRestoreArkChannelSourceWatch verifies an in-Ark refresh remains +// protected after its lnd channel has been archived. +func TestShouldRestoreArkChannelSourceWatch(t *testing.T) { + t.Parallel() + + source := &arkchannel.VTXOBinding{ + OutPoint: wire.OutPoint{ + Index: 1, + }, + } + cooperativeClose := &arkchannel.CooperativeClose{} + tests := []struct { + name string + snapshot arkchannel.Snapshot + restore bool + }{ + { + name: "active", + snapshot: arkchannel.Snapshot{ + Phase: arkchannel.PhaseActive, Source: source, + ClientRecoveryReady: true, + HubRecoveryReady: true, + }, + restore: true, + }, + { + name: "cooperatively closed", + snapshot: arkchannel.Snapshot{ + Phase: arkchannel.PhaseClosed, Source: source, + ClientRecoveryReady: true, + HubRecoveryReady: true, + CooperativeClose: cooperativeClose, + }, + restore: true, + }, + { + name: "ordinary closed", + snapshot: arkchannel.Snapshot{ + Phase: arkchannel.PhaseClosed, Source: source, + ClientRecoveryReady: true, + HubRecoveryReady: true, + }, + }, + { + name: "conflict already durable", + snapshot: arkchannel.Snapshot{ + Phase: arkchannel.PhaseClosed, Source: source, + ClientRecoveryReady: true, + HubRecoveryReady: true, + CooperativeClose: cooperativeClose, + SourceConflict: &arkchannel.SourceConflict{ + OutPoint: wire.OutPoint{ + Index: 2, + }, + }, + }, + }, + { + name: "recovery not installed", + snapshot: arkchannel.Snapshot{ + Phase: arkchannel.PhaseActive, Source: source, + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + require.Equal( + t, test.restore, + shouldRestoreArkChannelSourceWatch( + test.snapshot, + ), + ) + }) + } +} + +// TestRestoreArkChannelSourceWatchesIsolatesFailures proves a corrupt source +// does not prevent later channels from restoring their chain protection. +func TestRestoreArkChannelSourceWatchesIsolatesFailures(t *testing.T) { + t.Parallel() + + firstID := arkchannel.ID{1} + secondID := arkchannel.ID{2} + records := []arkchannel.Record{ + { + Snapshot: arkchannel.Snapshot{ + Terms: arkchannel.Terms{ + ID: firstID, + }, + Phase: arkchannel.PhaseActive, + Source: &arkchannel.VTXOBinding{ + OutPoint: wire.OutPoint{ + Index: 1, + }, + }, + ClientRecoveryReady: true, + HubRecoveryReady: true, + }, + }, + { + Snapshot: arkchannel.Snapshot{ + Terms: arkchannel.Terms{ + ID: secondID, + }, + Phase: arkchannel.PhaseActive, + Source: &arkchannel.VTXOBinding{ + OutPoint: wire.OutPoint{ + Index: 2, + }, + }, + ClientRecoveryReady: true, + HubRecoveryReady: true, + }, + }, + } + tracked := make([]arkchannel.ID, 0, 1) + err := restoreArkChannelSourceWatches( + t.Context(), records, + func(_ context.Context, outpoint wire.OutPoint) ( + *vtxo.Descriptor, error) { + + if outpoint.Index == 1 { + return nil, errors.New("corrupt source") + } + + return &vtxo.Descriptor{}, nil + }, + func(_ context.Context, id arkchannel.ID, + _ *vtxo.Descriptor) error { + + tracked = append(tracked, id) + + return nil + }, + ) + + var failures *arkchannel.ResumeFailures + require.ErrorAs(t, err, &failures) + require.Len(t, failures.Failures, 1) + require.Equal(t, firstID, failures.Failures[0].ChannelID) + require.Equal(t, []arkchannel.ID{secondID}, tracked) +} + +// TestChannelOperatorKeyAcceptsOppositeParity verifies that Ark operator +// identity follows the x-only script key rather than compressed-key parity. +func TestChannelOperatorKeyAcceptsOppositeParity(t *testing.T) { + privKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + + terms := arkchannel.Terms{} + copy( + terms.VTXO.ArkOperatorKey[:], + privKey.PubKey().SerializeCompressed(), + ) + + oppositeBytes := privKey.PubKey().SerializeCompressed() + if oppositeBytes[0] == 0x02 { + oppositeBytes[0] = 0x03 + } else { + oppositeBytes[0] = 0x02 + } + oppositeKey, err := btcec.ParsePubKey(oppositeBytes) + require.NoError(t, err) + require.False(t, privKey.PubKey().IsEqual(oppositeKey)) + + operatorKey, err := channelOperatorKey( + terms.VTXO.ArkOperatorKey, []*vtxo.Descriptor{ + {OperatorKey: oppositeKey}, + }, + ) + require.NoError(t, err) + require.True(t, operatorKey.IsEqual(privKey.PubKey())) +} + +// TestChannelOperatorKeyRejectsDifferentKey verifies that unrelated Ark +// operator keys cannot reuse the persisted ancestry. +func TestChannelOperatorKeyRejectsDifferentKey(t *testing.T) { + operatorKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + rootKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + + terms := arkchannel.Terms{} + copy( + terms.VTXO.ArkOperatorKey[:], + operatorKey.PubKey().SerializeCompressed(), + ) + + _, err = channelOperatorKey( + terms.VTXO.ArkOperatorKey, []*vtxo.Descriptor{ + {OperatorKey: rootKey.PubKey()}, + }, + ) + require.ErrorContains(t, err, "operator does not match roots") +} diff --git a/waved/ark_channel_source_validation.go b/waved/ark_channel_source_validation.go new file mode 100644 index 000000000..cbf45c151 --- /dev/null +++ b/waved/ark_channel_source_validation.go @@ -0,0 +1,185 @@ +package waved + +import ( + "context" + "fmt" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/arkrpc" + "github.com/lightninglabs/wavelength/chainsource" + "github.com/lightninglabs/wavelength/lib/recovery" + "github.com/lightninglabs/wavelength/vtxo" +) + +// validateArkChannelRecoveryProof applies the ordinary wallet receive boundary +// before accepting a hub's recovery package. Structural resolvability alone +// cannot authorize releasing an invoice preimage. +func validateArkChannelRecoveryProof(ctx context.Context, desc *vtxo.Descriptor, + recovery arkchannel.RecoveryPackage, + backend chainsource.ChainBackend) error { + + candidate := &arkrpc.VTXO{ + Outpoint: &arkrpc.OutPoint{ + Txid: desc.Outpoint.Hash[:], Vout: desc.Outpoint.Index, + }, + ValueSat: uint64(desc.Amount), PkScript: desc.PkScript, + } + for _, fragment := range desc.Ancestry { + path, err := arkrpc.AncestryPathFromTree( + fragment.TreePath, fragment.CommitmentTxID, + fragment.InputIndices, + ) + if err != nil { + return err + } + path.TreeDepth = fragment.TreeDepth + path.CommitmentHeight = fragment.CommitmentHeight + path.CommitmentSweepDelay = fragment.CommitmentSweepDelay + if fragment.CommitmentSweepKey != nil { + path.CommitmentSweepKey = fragment.CommitmentSweepKey. + SerializeCompressed() + } + candidate.AncestryPaths = append(candidate.AncestryPaths, path) + } + for _, pkg := range recovery.Packages { + candidate.AncestryPackages = append( + candidate.AncestryPackages, &arkrpc.OORSessionPackage{ + ArkPsbt: pkg.ArkPSBT, + CheckpointPsbts: pkg.Checkpoints, + }, + ) + } + ancestry, err := vtxo.IndexedAncestryFromRPC(candidate) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(ctx, expiryAuthenticationTimeout) + defer cancel() + heights := make(map[chainhash.Hash]int32) + evidence, err := vtxo.AuthenticateBatchEvidence( + ctx, ancestry, + func(ctx context.Context, txid chainhash.Hash, pkScript []byte, + heightHint uint32) (vtxo.CommitmentConfirmation, + error) { + + var empty vtxo.CommitmentConfirmation + registration, err := backend.RegisterConf( + ctx, &txid, pkScript, 1, heightHint, false, + ) + if err != nil { + return empty, err + } + defer registration.Cancel() + select { + case confirmation, ok := <-registration.Confirmed: + if !ok || confirmation == nil { + return empty, fmt.Errorf( + "confirmation watch closed " + + "without a transaction") + } + + heights[txid] = int32(confirmation.BlockHeight) + + return vtxo.CommitmentConfirmation{ + Tx: confirmation.Tx, + BlockHeight: int32( + confirmation.BlockHeight, + ), + }, nil + + case <-ctx.Done(): + return empty, ctx.Err() + } + }, + ) + if err != nil { + return err + } + for i := range ancestry { + fragment := &ancestry[i] + fragment.CommitmentHeight = heights[fragment.CommitmentTxID] + } + desc.Ancestry = ancestry + desc.BatchExpiry = evidence.BatchExpiry + + return nil +} + +// validateArkChannelRecoveryWindow bounds the actual signed dependency graph, +// including relative and absolute height locks, by the allowance used for +// native broadcast timing. Fee-market delays remain the caller's reaction +// margin; accepting arbitrarily long or time-locked ancestry is not safe. +func validateArkChannelRecoveryWindow(proof *recovery.Proof, allowance uint32, + height int32) error { + + if height < 0 || allowance == 0 { + return fmt.Errorf("channel recovery window is unavailable") + } + ready := make(map[chainhash.Hash]uint64) + for _, layer := range proof.Layers() { + for _, txid := range layer { + node, ok := proof.Node(txid) + if !ok { + return fmt.Errorf("missing recovery " + + "transaction") + } + tx := node.Tx + var earliest uint64 + lockActive := false + for _, input := range tx.TxIn { + sequence := input.Sequence + lockActive = lockActive || + sequence != wire.MaxTxInSequenceNum + delay, err := recoverySequenceBlocks( + tx.Version, sequence, + ) + if err != nil { + return err + } + earliest = max( + earliest, + ready[input.PreviousOutPoint.Hash]+ + delay, + ) + } + if lockActive && tx.LockTime != 0 { + if tx.LockTime >= txscript.LockTimeThreshold { + return fmt.Errorf("time-based " + + "recovery lock") + } + if tx.LockTime >= uint32(height) { + earliest = max( + earliest, uint64(tx.LockTime)- + uint64(height)+ + 1, + ) + } + } + ready[txid] = earliest + } + } + needed := ready[proof.TargetOutpoint().Hash] + + uint64(proof.CSVDelay()) + 1 + if needed > uint64(allowance) { + return fmt.Errorf("source recovery needs %d blocks, "+ + "allowance %d", needed, allowance) + } + + return nil +} + +// recoverySequenceBlocks reserves a confirmation per dependency even when no +// relative lock is active. Time-mode locks have no bounded block allowance. +func recoverySequenceBlocks(version int32, sequence uint32) (uint64, error) { + if version < 2 || sequence&wire.SequenceLockTimeDisabled != 0 { + return 1, nil + } + if sequence&wire.SequenceLockTimeIsSeconds != 0 { + return 0, fmt.Errorf("time-based recovery lock") + } + + return max(1, uint64(sequence&wire.SequenceLockTimeMask)), nil +} diff --git a/waved/ark_channel_source_validation_test.go b/waved/ark_channel_source_validation_test.go new file mode 100644 index 000000000..d07e4cbc9 --- /dev/null +++ b/waved/ark_channel_source_validation_test.go @@ -0,0 +1,179 @@ +package waved + +import ( + "context" + "fmt" + "testing" + + "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/chainsource" + "github.com/lightninglabs/wavelength/internal/expiryfixture" + "github.com/lightninglabs/wavelength/lib/recovery" + "github.com/lightninglabs/wavelength/vtxo" + "github.com/stretchr/testify/require" +) + +// TestArkChannelRecoveryAuthenticatesFunding rejects structurally resolvable +// but unauthorized funding and requires confirmation evidence from our chain +// source rather than the peer's expiry claim. +func TestArkChannelRecoveryAuthenticatesFunding(t *testing.T) { + t.Parallel() + type confirmation = chainsource.TxConfirmation + + for _, scenario := range []string{ + "valid", "wrong value", "wrong script", "unconfirmed", + "wrong anchor", + } { + t.Run(scenario, func(t *testing.T) { + t.Parallel() + candidate, commitment := expiryfixture.Round( + t, 100_000, []byte{0x51}, 200, 100, 73, + ) + ancestry, err := vtxo.AncestryFromRPC( + candidate.AncestryPaths, + ) + require.NoError(t, err) + ancestry[0].CommitmentHeight = 1_000_000 + var target chainhash.Hash + copy(target[:], candidate.Outpoint.Txid) + desc := &vtxo.Descriptor{ + Amount: btcutil.Amount(candidate.ValueSat), + PkScript: candidate.PkScript, + Ancestry: ancestry, + BatchExpiry: 1_000_000, + } + desc.Outpoint.Hash = target + desc.Outpoint.Index = candidate.Outpoint.Vout + if scenario == "wrong value" { + desc.Amount++ + } + if scenario == "wrong script" { + desc.PkScript = []byte{0x52} + } + lookups, cancellations := 0, 0 + backend := &laterHeightBackend{ + register: func(context.Context, *chainhash.Hash, + []byte, uint32, uint32, bool) ( + *chainsource.ConfRegistration, error) { + + lookups++ + if scenario == "unconfirmed" { + return nil, fmt.Errorf( + "not confirmed") + } + confirmed := commitment.Copy() + if scenario == "wrong anchor" { + confirmed.TxOut[0].Value++ + } + ch := make(chan *confirmation, 1) + ch <- &chainsource.TxConfirmation{ + Tx: confirmed, BlockHeight: 100, + } + + return &chainsource.ConfRegistration{ + Confirmed: ch, + Cancel: func() { + cancellations++ + }, + }, nil + }, + } + err = validateArkChannelRecoveryProof( + t.Context(), desc, arkchannel.RecoveryPackage{}, + backend, + ) + if scenario == "valid" { + require.NoError(t, err) + require.Equal(t, int32(300), desc.BatchExpiry) + require.Equal( + t, int32(100), + desc.Ancestry[0].CommitmentHeight, + ) + require.Equal(t, 1, cancellations) + + return + } + require.Error(t, err) + switch scenario { + case "wrong value", "wrong script": + require.Zero(t, lookups) + } + }) + } +} + +// TestArkChannelRecoveryWindow rejects real transaction dependencies that +// cannot materialize within the allowance used by native HTLC publication. +func TestArkChannelRecoveryWindow(t *testing.T) { + t.Parallel() + timeFlag := uint32(wire.SequenceLockTimeIsSeconds) + for _, scenario := range []string{ + "exact", "short", "relative lock", "absolute lock", "time lock", + } { + t.Run(scenario, func(t *testing.T) { + t.Parallel() + root := wire.NewMsgTx(2) + root.AddTxIn( + &wire.TxIn{ + PreviousOutPoint: wire.OutPoint{ + Hash: chainhash.Hash{7}, + }, + Sequence: wire.MaxTxInSequenceNum, + }, + ) + root.AddTxOut( + &wire.TxOut{ + Value: 100, + PkScript: []byte{0x51}, + }, + ) + target := wire.NewMsgTx(2) + target.AddTxIn( + &wire.TxIn{ + PreviousOutPoint: wire.OutPoint{ + Hash: root.TxHash(), + }, + Sequence: 1, + }, + ) + target.AddTxOut(root.TxOut[0]) + allowance := uint32(13) + switch scenario { + case "short": + allowance-- + + case "relative lock": + target.TxIn[0].Sequence = 20 + + case "absolute lock": + target.LockTime = 200 + + case "time lock": + target.TxIn[0].Sequence |= timeFlag + } + proof, err := recovery.NewProof( + wire.OutPoint{ + Hash: target.TxHash(), + }, + 10, &recovery.Node{ + Tx: root, + }, &recovery.Node{ + Tx: target, + }, + ) + require.NoError(t, err) + err = validateArkChannelRecoveryWindow( + proof, allowance, 100, + ) + if scenario == "exact" { + require.NoError(t, err) + + return + } + require.Error(t, err) + }) + } +} diff --git a/waved/ark_channel_source_watcher.go b/waved/ark_channel_source_watcher.go new file mode 100644 index 000000000..0df311f6a --- /dev/null +++ b/waved/ark_channel_source_watcher.go @@ -0,0 +1,236 @@ +package waved + +import ( + "context" + "fmt" + "sync" + "time" + + "github.com/btcsuite/btclog/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/chainsource" + "github.com/lightninglabs/wavelength/fraud" + "github.com/lightninglabs/wavelength/vtxo" +) + +// arkChannelSourceWatcher passively watches every on-path source ancestor and +// turns the first confirmed spend into a durable channel event. +type arkChannelSourceWatcher struct { + backend chainsource.ChainBackend + log btclog.Logger + ctx context.Context //nolint:containedctx // owned until Stop + cancel context.CancelFunc + + mu sync.Mutex + sink arkchannel.ChannelEventSink + registrations map[arkchannel.ID][]*chainsource.SpendRegistration + retryDelay time.Duration + wg sync.WaitGroup +} + +// newArkChannelSourceWatcher constructs an endpoint-local passive watcher. +func newArkChannelSourceWatcher(backend chainsource.ChainBackend, + log btclog.Logger) *arkChannelSourceWatcher { + + ctx, cancel := context.WithCancel(context.Background()) + if log == nil { + log = btclog.Disabled + } + + return &arkChannelSourceWatcher{ + backend: backend, log: log, ctx: ctx, cancel: cancel, + registrations: make( + map[arkchannel.ID][]*chainsource.SpendRegistration, + ), + retryDelay: time.Second, + } +} + +// BindChannelEventSink attaches the durable channel service. +func (w *arkChannelSourceWatcher) BindChannelEventSink( + sink arkchannel.ChannelEventSink) error { + + if sink == nil { + return fmt.Errorf("channel event sink is required") + } + w.mu.Lock() + defer w.mu.Unlock() + if w.sink == nil { + w.sink = sink + } + + return nil +} + +// Track atomically arms all watches for one channel. A duplicate install is +// idempotent and reuses the already active registrations. +func (w *arkChannelSourceWatcher) Track(ctx context.Context, id arkchannel.ID, + desc *vtxo.Descriptor) error { + + plan, err := fraud.BuildWatchPlan(desc) + if err != nil { + return err + } + w.mu.Lock() + if w.sink == nil { + w.mu.Unlock() + + return fmt.Errorf("channel event sink is not bound") + } + if _, ok := w.registrations[id]; ok { + w.mu.Unlock() + + return nil + } + w.mu.Unlock() + + registrations := make( + []*chainsource.SpendRegistration, 0, len(plan.Watches), + ) + for i := range plan.Watches { + watch := plan.Watches[i] + outpoint := watch.Outpoint + //nolint:contextcheck // watcher root owns registration lifetime + registration, err := w.backend.RegisterSpend( + w.ctx, &outpoint, watch.PkScript, watch.HeightHint, + ) + if err != nil { + cancelSpendRegistrations(registrations) + + return fmt.Errorf("register channel source spend "+ + "%s: %w", outpoint, err) + } + registrations = append(registrations, registration) + } + + w.mu.Lock() + if _, ok := w.registrations[id]; ok { + w.mu.Unlock() + cancelSpendRegistrations(registrations) + + return nil + } + w.registrations[id] = registrations + w.mu.Unlock() + + for i := range registrations { + w.wg.Add(1) + go w.waitForSpend(id, registrations[i]) + } + + return nil +} + +// waitForSpend waits for one confirmed ancestor spend or shutdown. +func (w *arkChannelSourceWatcher) waitForSpend(id arkchannel.ID, + registration *chainsource.SpendRegistration) { + + defer w.wg.Done() + select { + case detail, ok := <-registration.Spend: + if !ok || detail == nil || detail.SpentOutPoint == nil || + detail.SpenderTxHash == nil { + return + } + w.handleSpend(id, &arkchannel.SourceSpent{ + OutPoint: *detail.SpentOutPoint, + SpendingTxID: *detail.SpenderTxHash, + }) + + case <-registration.Done: + case <-w.ctx.Done(): + } +} + +// handleSpend cancels sibling watches and retries the durable event until the +// FSM accepts it. The chain notifier delivers a confirmed spend once, so a +// transient database or side-effect failure must not discard that evidence. +func (w *arkChannelSourceWatcher) handleSpend(id arkchannel.ID, + event *arkchannel.SourceSpent) { + + w.mu.Lock() + registrations, ok := w.registrations[id] + if ok { + delete(w.registrations, id) + } + sink := w.sink + w.mu.Unlock() + if !ok || sink == nil { + return + } + cancelSpendRegistrations(registrations) + attempts := 0 + for { + _, err := sink.ApplyLocalEvent(w.ctx, id, event) + if err == nil { + if attempts > 0 { + w.log.InfoS( + w.ctx, + "Recovered Ark channel after source "+ + "spend", + btclog.Fmt("channel_id", "%x", id[:]), + btclog.Fmt("attempts", + "%d", attempts+1), + ) + } + + return + } + attempts++ + if attempts == 1 || attempts%30 == 0 { + w.log.WarnS( + w.ctx, + "Failed to recover Ark channel after source "+ + "spend", + err, + btclog.Fmt("channel_id", "%x", id[:]), + btclog.Fmt( + "spent_outpoint", "%v", event.OutPoint, + ), + btclog.Fmt( + "spending_txid", "%v", + event.SpendingTxID, + ), + btclog.Fmt("attempts", "%d", attempts), + ) + } + + timer := time.NewTimer(w.retryDelay) + select { + case <-timer.C: + case <-w.ctx.Done(): + if !timer.Stop() { + select { + case <-timer.C: + default: + } + } + + return + } + } +} + +// Stop cancels all registrations and waits for their goroutines. +func (w *arkChannelSourceWatcher) Stop() { + if w == nil { + return + } + w.cancel() + w.mu.Lock() + for id, registrations := range w.registrations { + cancelSpendRegistrations(registrations) + delete(w.registrations, id) + } + w.mu.Unlock() + w.wg.Wait() +} + +// cancelSpendRegistrations releases backend resources for a watch set. +func cancelSpendRegistrations(registrations []*chainsource.SpendRegistration) { + for _, registration := range registrations { + if registration != nil && registration.Cancel != nil { + registration.Cancel() + } + } +} diff --git a/waved/ark_channel_source_watcher_test.go b/waved/ark_channel_source_watcher_test.go new file mode 100644 index 000000000..fee1ba422 --- /dev/null +++ b/waved/ark_channel_source_watcher_test.go @@ -0,0 +1,226 @@ +package waved + +import ( + "context" + "fmt" + "sync" + "testing" + "time" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/btcsuite/btclog/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/chainsource" + "github.com/lightninglabs/wavelength/fraud" + "github.com/lightninglabs/wavelength/lib/tree" + "github.com/lightninglabs/wavelength/vtxo" + "github.com/stretchr/testify/require" +) + +type sourceWatcherRegistration struct { + spend chan *chainsource.SpendDetail + done chan struct{} + once sync.Once + cancel bool +} + +type sourceWatcherBackend struct { + chainsource.ChainBackend + + mu sync.Mutex + registrations map[wire.OutPoint]*sourceWatcherRegistration +} + +type sourceWatcherSink struct { + mu sync.Mutex + failures int + calls int + channelID arkchannel.ID + event *arkchannel.SourceSpent +} + +// RegisterSpend records one passive spend registration. +func (b *sourceWatcherBackend) RegisterSpend(_ context.Context, + outpoint *wire.OutPoint, _ []byte, _ uint32) ( + *chainsource.SpendRegistration, error) { + + b.mu.Lock() + defer b.mu.Unlock() + registration := &sourceWatcherRegistration{ + spend: make(chan *chainsource.SpendDetail, 1), + done: make(chan struct{}), + } + b.registrations[*outpoint] = registration + + return &chainsource.SpendRegistration{ + Spend: registration.spend, + Reorged: make(chan uint64), + Done: registration.done, + Cancel: func() { + registration.once.Do(func() { + b.mu.Lock() + registration.cancel = true + b.mu.Unlock() + close(registration.done) + }) + }, + }, nil +} + +// ApplyLocalEvent records one watcher event and injects transient failures +// when asked. +func (s *sourceWatcherSink) ApplyLocalEvent(_ context.Context, id arkchannel.ID, + event arkchannel.Event) (arkchannel.Record, error) { + + s.mu.Lock() + defer s.mu.Unlock() + s.calls++ + s.channelID = id + sourceSpent, ok := event.(*arkchannel.SourceSpent) + if !ok { + return arkchannel.Record{}, fmt.Errorf("unexpected source "+ + "watcher event %T", event) + } + s.event = sourceSpent + if s.failures > 0 { + s.failures-- + + return arkchannel.Record{}, context.DeadlineExceeded + } + + return arkchannel.Record{}, nil +} + +// TestArkChannelSourceWatcherCoversAllAncestry verifies every path in a +// multi-input OOR proof is armed and the first spend is retried durably. +func TestArkChannelSourceWatcherCoversAllAncestry(t *testing.T) { + t.Parallel() + + treeOne, sourceOne := sourceWatcherTree(t, 10) + treeTwo, sourceTwo := sourceWatcherTree(t, 20) + desc := &vtxo.Descriptor{ + Outpoint: sourceWatcherOutpoint(30), + Ancestry: []vtxo.Ancestry{ + { + TreePath: treeOne, + CommitmentTxID: treeOne.Root.Input.Hash, + InputIndices: []uint32{ + 0, + }, + TreeDepth: 1, + }, + { + TreePath: treeTwo, + CommitmentTxID: treeTwo.Root.Input.Hash, + InputIndices: []uint32{ + 1, + }, + TreeDepth: 1, + }, + }, + CreatedHeight: 7, + } + plan, err := fraud.BuildWatchPlan(desc) + require.NoError(t, err) + + backend := &sourceWatcherBackend{ + registrations: make( + map[wire.OutPoint]*sourceWatcherRegistration, + ), + } + sink := &sourceWatcherSink{failures: 1} + watcher := newArkChannelSourceWatcher(backend, btclog.Disabled) + watcher.retryDelay = 5 * time.Millisecond + require.NoError(t, watcher.BindChannelEventSink(sink)) + t.Cleanup(watcher.Stop) + + id := arkchannel.ID{1, 2, 3} + require.NoError(t, watcher.Track(t.Context(), id, desc)) + backend.mu.Lock() + require.Len(t, backend.registrations, len(plan.Watches)) + require.Contains(t, backend.registrations, treeOne.Root.Input) + require.Contains(t, backend.registrations, sourceOne) + require.Contains(t, backend.registrations, treeTwo.Root.Input) + require.Contains(t, backend.registrations, sourceTwo) + registration := backend.registrations[treeTwo.Root.Input] + backend.mu.Unlock() + + spendingTx := wire.NewMsgTx(2) + spendingTx.AddTxIn(wire.NewTxIn( + &treeTwo.Root.Input, nil, nil, + )) + spendingTx.AddTxOut(&wire.TxOut{Value: 1, PkScript: []byte{0x51}}) + spendingTxID := spendingTx.TxHash() + registration.spend <- &chainsource.SpendDetail{ + SpentOutPoint: &treeTwo.Root.Input, + SpenderTxHash: &spendingTxID, + SpendingTx: spendingTx, + SpenderInputIndex: 0, + SpendingHeight: 8, + } + + require.Eventually(t, func() bool { + sink.mu.Lock() + defer sink.mu.Unlock() + + return sink.calls == 2 + }, time.Second, time.Millisecond) + sink.mu.Lock() + require.Equal(t, id, sink.channelID) + require.Equal(t, treeTwo.Root.Input, sink.event.OutPoint) + require.Equal(t, spendingTxID, sink.event.SpendingTxID) + sink.mu.Unlock() + + require.Eventually(t, func() bool { + backend.mu.Lock() + defer backend.mu.Unlock() + for _, item := range backend.registrations { + if !item.cancel { + return false + } + } + + return true + }, time.Second, time.Millisecond) +} + +// sourceWatcherTree creates a one-node ancestry tree and its VTXO leaf. +func sourceWatcherTree(t *testing.T, seed byte) (*tree.Tree, wire.OutPoint) { + t.Helper() + root := &tree.Node{ + Input: sourceWatcherOutpoint(seed), + Outputs: []*wire.TxOut{ + { + Value: 1_000, + PkScript: []byte{ + 0x51, + seed, + }, + }, + }, + Children: make(map[uint32]*tree.Node), + } + source, err := root.GetNonAnchorOutpoint() + require.NoError(t, err) + + return &tree.Tree{ + Root: root, + BatchOutput: &wire.TxOut{ + Value: 1_000, + PkScript: []byte{ + 0x51, + seed, + 0, + }, + }, + }, *source +} + +// sourceWatcherOutpoint returns one deterministic test outpoint. +func sourceWatcherOutpoint(seed byte) wire.OutPoint { + var hash chainhash.Hash + hash[0] = seed + + return wire.OutPoint{Hash: hash} +} diff --git a/waved/config.go b/waved/config.go index 22bd69fc4..00a96a2ea 100644 --- a/waved/config.go +++ b/waved/config.go @@ -774,6 +774,14 @@ type SwapConfig struct { // DefaultMaxActiveReceiveSwaps. MaxActiveReceiveSwaps int `mapstructure:"maxactivereceiveswaps"` + // ArkChannelsEnabled admits explicit open, pay and receive requests. + // It neither starts the peer nor redirects ordinary swaps. + ArkChannelsEnabled bool `mapstructure:"arkchannelsenabled"` + + // SuppressArkChannelRuntime disables the recovery runtime. Startup + // rejects this override while the database contains recoverable state. + SuppressArkChannelRuntime bool `mapstructure:"disablearkchannelruntime"` + // VHTLCRecovery controls when the daemon-owned swap runtime escalates // an already-armed vHTLC recovery row from cooperative retry into // on-chain unroll. @@ -825,6 +833,11 @@ type SwapConfig struct { // pending credit-backed send is about to spend. Nil in builds without // the credit subsystem; set programmatically, never from config files. CreditEarmarkSetter func(credit.EarmarkFunc) `mapstructure:"-"` + + // ArkChannelMailbox is the authenticated swapdk-server mailbox edge + // published by swapclientserver for the channel control runtime. It is + // process wiring, never user configuration. + ArkChannelMailbox mailboxpb.MailboxServiceClient `mapstructure:"-"` } // CreditConfig configures the daemon-owned credit subsystem. diff --git a/waved/logging.go b/waved/logging.go index 368c5b653..8d93a16e3 100644 --- a/waved/logging.go +++ b/waved/logging.go @@ -17,11 +17,50 @@ import ( "github.com/lightninglabs/wavelength/vtxo" "github.com/lightninglabs/wavelength/wallet" lndbuild "github.com/lightningnetwork/lnd/build" + "github.com/lightningnetwork/lnd/chainio" + "github.com/lightningnetwork/lnd/channeldb" + "github.com/lightningnetwork/lnd/contractcourt" + "github.com/lightningnetwork/lnd/funding" + "github.com/lightningnetwork/lnd/htlcswitch" + "github.com/lightningnetwork/lnd/invoices" + "github.com/lightningnetwork/lnd/lnwallet" + "github.com/lightningnetwork/lnd/lnwallet/chanfunding" + "github.com/lightningnetwork/lnd/routing" + "github.com/lightningnetwork/lnd/sweep" ) // SubLoggers maps subsystem tags to their registered btclog instances. type SubLoggers map[string]btclog.Logger +// lndLoggers holds the stable loggers installed before any runtime starts. +// Only their delegates change when another daemon configures logging. +var lndLoggers = make(map[string]*redirectLogger) + +// init binds LND's unsynchronized package globals once, before goroutines can +// read them. Runtime setup must redirect delegates instead of calling +// UseLogger. +func init() { + bindings := map[string]func(btclog.Logger){ + funding.Subsystem: funding.UseLogger, + "CHFD": chanfunding.UseLogger, + "LNWL": lnwallet.UseLogger, + "HSWC": htlcswitch.UseLogger, + "INVC": invoices.UseLogger, + routing.Subsystem: routing.UseLogger, + "CNCT": contractcourt.UseLogger, + "BRAR": contractcourt.UseBreachLogger, + "UTXN": contractcourt.UseNurseryLogger, + "SWPR": sweep.UseLogger, + "CHDB": channeldb.UseLogger, + chainio.Subsystem: chainio.UseLogger, + } + for tag, use := range bindings { + logger := &redirectLogger{} + use(logger) + lndLoggers[tag] = logger + } +} + // allSubsystems is the authoritative list of subsystem tags registered with // the daemon's root SubLoggerManager. var allSubsystems = []string{ @@ -48,6 +87,18 @@ var allSubsystems = []string{ "TXCF", "UNRL", VHTLCRecoverySubsystem, + funding.Subsystem, + "CHFD", + "LNWL", + "HSWC", + "INVC", + routing.Subsystem, + "CNCT", + "BRAR", + "UTXN", + "SWPR", + "CHDB", + chainio.Subsystem, } const ( @@ -89,6 +140,8 @@ func SetupLoggersWithShutdownFn(root *lndbuild.SubLoggerManager, }) } +// setupLoggers registers instance loggers and redirects LND's package loggers +// to the latest configuration without replacing their process-wide interfaces. func setupLoggers(root *lndbuild.SubLoggerManager, genLogger func(string) btclog.Logger) SubLoggers { @@ -98,6 +151,9 @@ func setupLoggers(root *lndbuild.SubLoggerManager, logger := lndbuild.NewSubLogger(sub, genLogger) root.RegisterSubLogger(sub, logger) loggers[sub] = logger + if lndLogger, ok := lndLoggers[sub]; ok { + lndLogger.setLogger(logger) + } } return loggers diff --git a/waved/logging_redirect.go b/waved/logging_redirect.go new file mode 100644 index 000000000..5dbaa9d9e --- /dev/null +++ b/waved/logging_redirect.go @@ -0,0 +1,148 @@ +package waved + +import ( + "context" + "sync/atomic" + + btclogv1 "github.com/btcsuite/btclog" + "github.com/btcsuite/btclog/v2" +) + +// redirectLogger keeps LND's package-global logger interfaces immutable while +// forwarding calls to the latest daemon's output, levels and shutdown callback. +// Derived loggers are snapshots, just as before a subsequent UseLogger call. +type redirectLogger struct { + delegate atomic.Pointer[btclog.Logger] +} + +var _ btclog.Logger = (*redirectLogger)(nil) + +// setLogger publishes an immutable interface value for concurrent readers. +func (l *redirectLogger) setLogger(logger btclog.Logger) { + l.delegate.Store(&logger) +} + +// logger returns the current delegate, or disables logging before daemon setup. +func (l *redirectLogger) logger() btclog.Logger { + if logger := l.delegate.Load(); logger != nil { + return *logger + } + + return btclog.Disabled +} + +// Tracef forwards a formatted trace message. +func (l *redirectLogger) Tracef(format string, params ...any) { + l.logger().Tracef(format, params...) +} + +// Debugf forwards a formatted debug message. +func (l *redirectLogger) Debugf(format string, params ...any) { + l.logger().Debugf(format, params...) +} + +// Infof forwards a formatted info message. +func (l *redirectLogger) Infof(format string, params ...any) { + l.logger().Infof(format, params...) +} + +// Warnf forwards a formatted warning message. +func (l *redirectLogger) Warnf(format string, params ...any) { + l.logger().Warnf(format, params...) +} + +// Errorf forwards a formatted error message. +func (l *redirectLogger) Errorf(format string, params ...any) { + l.logger().Errorf(format, params...) +} + +// Criticalf forwards a formatted critical message and its shutdown callback. +func (l *redirectLogger) Criticalf(format string, params ...any) { + l.logger().Criticalf(format, params...) +} + +// Trace forwards a trace message. +func (l *redirectLogger) Trace(args ...any) { + l.logger().Trace(args...) +} + +// Debug forwards a debug message. +func (l *redirectLogger) Debug(args ...any) { + l.logger().Debug(args...) +} + +// Info forwards an info message. +func (l *redirectLogger) Info(args ...any) { + l.logger().Info(args...) +} + +// Warn forwards a warning message. +func (l *redirectLogger) Warn(args ...any) { + l.logger().Warn(args...) +} + +// Error forwards an error message. +func (l *redirectLogger) Error(args ...any) { + l.logger().Error(args...) +} + +// Critical forwards a critical message and its shutdown callback. +func (l *redirectLogger) Critical(args ...any) { + l.logger().Critical(args...) +} + +// TraceS forwards a structured trace message. +func (l *redirectLogger) TraceS(ctx context.Context, msg string, attrs ...any) { + l.logger().TraceS(ctx, msg, attrs...) +} + +// DebugS forwards a structured debug message. +func (l *redirectLogger) DebugS(ctx context.Context, msg string, attrs ...any) { + l.logger().DebugS(ctx, msg, attrs...) +} + +// InfoS forwards a structured info message. +func (l *redirectLogger) InfoS(ctx context.Context, msg string, attrs ...any) { + l.logger().InfoS(ctx, msg, attrs...) +} + +// WarnS forwards a structured warning message. +func (l *redirectLogger) WarnS(ctx context.Context, msg string, err error, + attrs ...any) { + + l.logger().WarnS(ctx, msg, err, attrs...) +} + +// ErrorS forwards a structured error message. +func (l *redirectLogger) ErrorS(ctx context.Context, msg string, err error, + attrs ...any) { + + l.logger().ErrorS(ctx, msg, err, attrs...) +} + +// CriticalS forwards a structured critical message and its shutdown callback. +func (l *redirectLogger) CriticalS(ctx context.Context, msg string, err error, + attrs ...any) { + + l.logger().CriticalS(ctx, msg, err, attrs...) +} + +// Level returns the current delegate's level. +func (l *redirectLogger) Level() btclogv1.Level { + return l.logger().Level() +} + +// SetLevel updates the current delegate's level. +func (l *redirectLogger) SetLevel(level btclogv1.Level) { + l.logger().SetLevel(level) +} + +// SubSystem snapshots the current delegate with an independent subsystem level. +func (l *redirectLogger) SubSystem(tag string) btclog.Logger { + return l.logger().SubSystem(tag) +} + +// WithPrefix snapshots the current delegate, retaining its level inheritance. +func (l *redirectLogger) WithPrefix(prefix string) btclog.Logger { + return l.logger().WithPrefix(prefix) +} diff --git a/waved/logging_test.go b/waved/logging_test.go new file mode 100644 index 000000000..4f677e544 --- /dev/null +++ b/waved/logging_test.go @@ -0,0 +1,177 @@ +package waved + +import ( + "bytes" + "context" + "io" + "os" + "sync" + "sync/atomic" + "testing" + + "github.com/btcsuite/btclog/v2" + lndbuild "github.com/lightningnetwork/lnd/build" + "github.com/lightningnetwork/lnd/chainio" + "github.com/lightningnetwork/lnd/chainntnfs" + "github.com/lightningnetwork/lnd/lnwallet/chanfunding" + "github.com/stretchr/testify/require" +) + +// TestLNDLoggerReconfiguration checks output, level and shutdown ownership +// after another daemon replaces the delegate, without redirecting per-channel +// copies. +func TestLNDLoggerReconfiguration(t *testing.T) { + var logger redirectLogger + require.Same(t, btclog.Disabled, logger.logger()) + logger.Info("not configured") + + var firstOutput, secondOutput bytes.Buffer + firstRoot := lndbuild.NewSubLoggerManager( + btclog.NewDefaultHandler(&firstOutput), + ) + secondRoot := lndbuild.NewSubLoggerManager( + btclog.NewDefaultHandler(&secondOutput), + ) + var firstShutdown, secondShutdown atomic.Int32 + first := firstRoot.GenSubLogger("TEST", func() { + firstShutdown.Add(1) + }) + second := secondRoot.GenSubLogger("TEST", func() { + secondShutdown.Add(1) + }) + firstRoot.SetLogLevels("info") + secondRoot.SetLogLevels("info") + logger.setLogger(first) + prefixed := logger.WithPrefix("channel") + child := logger.SubSystem("CHILD") + + firstRoot.SetLogLevel("TEST", "debug") + require.Equal(t, btclog.LevelDebug, logger.Level()) + prefixed.Debug("inherited debug") + child.Debug("filtered child") + logger.Debugf("first %d", 1) + + logger.setLogger(second) + logger.Debug("filtered") + logger.InfoS(context.Background(), "second", "key", "value") + logger.Critical("current shutdown") + logger.Criticalf("current shutdown %d", 2) + logger.CriticalS(context.Background(), "current shutdown", nil) + require.Zero(t, firstShutdown.Load()) + require.EqualValues(t, 3, secondShutdown.Load()) + require.Equal(t, btclog.LevelInfo, logger.Level()) + + // Existing channel prefixes retain the old output and share its level; + // they must not silently become loggers for a different daemon. + firstRoot.SetLogLevel("TEST", "trace") + require.Equal(t, btclog.LevelInfo, logger.Level()) + prefixed.Trace("channel snapshot") + child.Info("subsystem snapshot") + logger.SetLevel(btclog.LevelWarn) + require.Equal(t, btclog.LevelWarn, second.Level()) + secondRoot.SetLogLevel("TEST", "debug") + require.Equal(t, btclog.LevelDebug, logger.Level()) + logger.Debug("latest level") + + require.Contains(t, firstOutput.String(), "first 1") + require.Contains(t, firstOutput.String(), "inherited debug") + require.Contains(t, firstOutput.String(), "channel snapshot") + require.Contains(t, firstOutput.String(), "CHILD") + require.NotContains(t, firstOutput.String(), "second") + require.NotContains(t, firstOutput.String(), "filtered child") + require.Contains(t, secondOutput.String(), "second key=value") + require.Contains(t, secondOutput.String(), "current shutdown 2") + require.Contains(t, secondOutput.String(), "latest level") + require.NotContains(t, secondOutput.String(), "filtered") + require.NotContains(t, secondOutput.String(), "snapshot") +} + +// TestSetupLoggersConcurrentReconfiguration exercises LND package-global reads +// while multiple daemon instances register their outputs and change log levels. +func TestSetupLoggersConcurrentReconfiguration(t *testing.T) { + const workers = 4 + const iterations = 100 + var wg sync.WaitGroup + start := make(chan struct{}) + for range workers { + wg.Go(func() { + root := lndbuild.NewSubLoggerManager( + btclog.NewDefaultHandler(io.Discard), + ) + <-start + for range iterations { + SetupLoggersWithShutdownFn(root, func() {}) + root.SetLogLevels("trace") + root.SetLogLevel("CHFD", "debug") + } + }) + wg.Go(func() { + <-start + for range iterations { + // Both operations read real LND logger globals. + // The intent logs directly; a beat derives its + // own prefix. + intent := &chanfunding.PsbtIntent{ + PsbtReady: make(chan error, 1), + } + intent.Cancel() + chainio.NewBeat(chainntnfs.BlockEpoch{}) + for _, logger := range lndLoggers { + logger.Infof("reconfiguration %d", 1) + logger.DebugS( + context.Background(), + "concurrent", + ) + logger.WithPrefix( + "channel").Info("snapshot") + } + } + }) + } + close(start) + wg.Wait() +} + +// TestSetupLoggersUsesLatestDelegate checks that setup changes every installed +// LND delegate while instance-local loggers remain attached to their own root. +func TestSetupLoggersUsesLatestDelegate(t *testing.T) { + firstOutput, err := os.CreateTemp(t.TempDir(), "first.log") + require.NoError(t, err) + var secondOutput bytes.Buffer + firstRoot := lndbuild.NewSubLoggerManager( + btclog.NewDefaultHandler(firstOutput), + ) + secondRoot := lndbuild.NewSubLoggerManager( + btclog.NewDefaultHandler(&secondOutput), + ) + first := SetupLoggersWithShutdownFn(firstRoot, func() {}) + second := SetupLoggersWithShutdownFn(secondRoot, func() {}) + for tag, logger := range lndLoggers { + require.Same(t, second[tag], logger.logger(), tag) + } + require.NoError(t, firstOutput.Close()) + + // Development nolog/stdlog builds deliberately bypass daemon outputs. + // The forwarding logger must preserve that choice as well. + if lndbuild.Deployment == lndbuild.Development && + lndbuild.LoggingType != lndbuild.LogTypeDefault { + return + } + for tag, logger := range lndLoggers { + require.NotSame(t, first[tag], logger.logger(), tag) + } + firstRoot.SetLogLevels("error") + first["CHFD"].Info("filtered first instance") + secondRoot.SetLogLevel("CHFD", "debug") + intent := &chanfunding.PsbtIntent{ + PsbtReady: make(chan error, 1), + } + intent.Cancel() + firstLogs, err := os.ReadFile(firstOutput.Name()) + require.NoError(t, err) + require.Empty(t, firstLogs) + require.Contains( + t, secondOutput.String(), + "PSBT funding intent canceled", + ) +} diff --git a/waved/native_ark_channel_controller.go b/waved/native_ark_channel_controller.go new file mode 100644 index 000000000..0bb1c204a --- /dev/null +++ b/waved/native_ark_channel_controller.go @@ -0,0 +1,2233 @@ +package waved + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "sync" + "time" + + "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/btcsuite/btclog/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/db" + "github.com/lightninglabs/wavelength/lib/arkscript" + "github.com/lightninglabs/wavelength/lib/types" + "github.com/lightninglabs/wavelength/lnruntime" + "github.com/lightninglabs/wavelength/rpc/arkchannelrpc" + "github.com/lightningnetwork/lnd/chanstate" + "github.com/lightningnetwork/lnd/contractcourt" + "github.com/lightningnetwork/lnd/htlcswitch" + "github.com/lightningnetwork/lnd/keychain" + "github.com/lightningnetwork/lnd/lntypes" + "github.com/lightningnetwork/lnd/lnwire" +) + +var ( + // ErrInsufficientArkChannelLiquidity means no active private channel + // has enough balance on the requested sending side. + ErrInsufficientArkChannelLiquidity = fmt.Errorf("insufficient active " + + "Ark channel liquidity") +) + +const ( + arkChannelArkKeyFamily keychain.KeyFamily = 220 + arkChannelBackingKeyFamily keychain.KeyFamily = 221 + arkChannelFunderKeyFamily keychain.KeyFamily = 223 + arkChannelPaymentCleanupTimeout = 30 * time.Second + maxArkChannelIdempotencyKeyLength = 128 +) + +// HubArkChannelControllerConfig contains the hub-only signer, publisher, and +// authenticated client transport needed to compose one native endpoint. +type HubArkChannelControllerConfig struct { + Process ArkChannelControllerConfig + + RemoteNode [33]byte + PeerSender lnruntime.PeerEventSender + Info lnruntime.FundingPeerInfo + CloseObserver lnruntime.CooperativeCloseObserver + CloseDefender lnruntime.CooperativeCloseDefender + PaymentBridge lnruntime.PaymentBridgeCoordinator + + // NodeFactory attaches this peer to a process-owned native engine. + // Nil retains a dedicated client-style engine and database. + NodeFactory lnruntime.NativeNodeFactory + + // RecoveryDeltaFloor covers the longest persisted obligation across + // every peer sharing the engine, including peers not yet attached. + RecoveryDeltaFloor uint32 + + // DeferStart lets the process prepare every durable peer and backing + // before any shared lnd funding or on-chain restoration starts. + DeferStart bool +} + +// NativeArkChannelController owns one Ark FSM and one modular lnd endpoint. +type NativeArkChannelController struct { + party arkchannel.Party + cfg ArkChannelControllerConfig + + prePONROOR prePONRResultController + coordinator *arkchannel.Coordinator + remote lnruntime.ProcessFundingPeer + fundingPeer lnruntime.RecoveryCounterparty + paymentPeer lnruntime.ProcessPaymentPeer + peerInfo lnruntime.FundingPeerInfo + clientPeer clientArkChannelPeer + keys nativeArkChannelKeys + + mu sync.RWMutex + node *lnruntime.NativeNode + service *arkchannel.Service + clientClose *lnruntime.ClientCooperativeCloseProcess + hubClose *lnruntime.HubCooperativeCloseProcess + paymentBridge lnruntime.PaymentBridgeCoordinator + startAttempt *arkChannelStartAttempt + stopped bool + + lifecycleCtx context.Context //nolint:containedctx // owned + lifecycleCancel context.CancelFunc + lifecycleWG sync.WaitGroup + workersOnce sync.Once + expiryPayoutWatches sync.Map + stopOnce sync.Once + stopErr error + + clientStarter func(context.Context) error + nodeFactory lnruntime.NativeNodeFactory + deferHubStart bool + hubStartMu sync.Mutex + hubStarted bool +} + +// arkChannelStartAttempt is one shared client endpoint startup result. +type arkChannelStartAttempt struct { + done chan struct{} + err error +} + +var _ contractcourt.AuxChannelLifecycle = (*NativeArkChannelController)(nil) + +// nativeArkChannelKeys are fixed wallet roles restored by locator on restart. +type nativeArkChannelKeys struct { + ark keychain.KeyDescriptor + backing keychain.KeyDescriptor + funder keychain.KeyDescriptor +} + +// loggedArkChannelForceCloser makes the irreversible lnd handoff observable +// while preserving lnd's idempotent close API as the implementation boundary. +type loggedArkChannelForceCloser struct { + node *lnruntime.NativeNode + log btclog.Logger +} + +// EnsureForceCloseChannel resumes an interrupted close or starts the peer's +// close after source-spend recovery materializes the channel. +func (c *loggedArkChannelForceCloser) EnsureForceCloseChannel( + channelPoint wire.OutPoint) error { + + ctx := context.Background() + c.log.InfoS(ctx, "Ensuring Ark channel force close", + btclog.Fmt("channel_point", "%v", channelPoint), + ) + err := c.node.EnsureForceCloseChannel(channelPoint) + if err != nil { + c.log.WarnS(ctx, "Ark channel force close failed", + err, + btclog.Fmt("channel_point", "%v", channelPoint), + ) + + return err + } + c.log.InfoS(ctx, "Ark channel force close ensured", + btclog.Fmt("channel_point", "%v", channelPoint), + ) + + return nil +} + +// LightningPaymentResult is the atomic public-payment result returned after +// the private source settled with the same preimage. +type LightningPaymentResult struct { + PaymentHash lntypes.Hash + Preimage lntypes.Preimage + PrivateAmount btcutil.Amount + Fee btcutil.Amount + ChannelID arkchannel.ID +} + +// ArkChannelMaterializationDelta sizes one native arbitrator for both current +// admissions and every persisted channel it must protect. A shared engine's +// caller must include every peer, not just the first endpoint to start. +func ArkChannelMaterializationDelta(records []arkchannel.Record, + floor uint32) uint32 { + + for _, record := range records { + floor = max(floor, record.Snapshot.Terms.VTXO.FunderDelay) + } + + return floor +} + +// NewHubFundingPeerInfo derives the immutable channel policy advertised by a +// real operator Wavelength process. The key roles share the same deterministic +// locators used when the hub endpoint is restored after restart. +func NewHubFundingPeerInfo(ctx context.Context, + cfg ArkChannelControllerConfig) (lnruntime.FundingPeerInfo, error) { + + if err := validateArkChannelProcessConfig(cfg); err != nil { + return lnruntime.FundingPeerInfo{}, err + } + if cfg.OperatorTerms == nil || cfg.OperatorTerms.PubKey == nil { + return lnruntime.FundingPeerInfo{}, fmt.Errorf("Ark operator " + + "terms are required") + } + keys, err := deriveNativeArkChannelKeys(ctx, cfg, arkchannel.PartyHub) + if err != nil { + return lnruntime.FundingPeerInfo{}, err + } + channelDelay := cfg.OperatorTerms.VTXOExitDelay + if channelDelay > ^uint32(0)-arkscript.DefaultChannelReactionWindow { + return lnruntime.FundingPeerInfo{}, fmt.Errorf("Ark channel " + + "delay exceeds sequence range") + } + info := lnruntime.FundingPeerInfo{ + ChannelDelay: channelDelay, + FunderDelay: channelDelay + + arkscript.DefaultChannelReactionWindow, + MinimumExitDelay: channelDelay, + } + copy(info.HubNodeKey[:], cfg.IdentityKey.PubKey.SerializeCompressed()) + copy(info.HubArkKey[:], keys.ark.PubKey.SerializeCompressed()) + copy(info.HubChannelKey[:], keys.backing.PubKey.SerializeCompressed()) + copy( + info.ArkOperatorKey[:], + cfg.OperatorTerms.PubKey.SerializeCompressed(), + ) + + return info, info.Validate() +} + +// NewClientArkChannelController constructs a lazy client endpoint. Startup +// restores existing channels locally. First use authenticates hub +// policy over the mailbox before starting native lnd components. +func NewClientArkChannelController(ctx context.Context, + cfg ArkChannelControllerConfig) (*NativeArkChannelController, error) { + + cfg = withArkChannelControllerDefaults(cfg) + + if err := validateClientArkChannelProcessConfig(cfg); err != nil { + return nil, err + } + var observers []arkchannel.RecordObserver + if cfg.RecordObserver != nil { + observers = append(observers, cfg.RecordObserver) + } + coordinator, err := arkchannel.NewCoordinator(cfg.Store, observers...) + if err != nil { + return nil, err + } + remote, err := lnruntime.NewMailboxFundingPeer(cfg.PeerRPC) + if err != nil { + return nil, err + } + keys, err := deriveNativeArkChannelKeys( + ctx, cfg, arkchannel.PartyClient, + ) + if err != nil { + return nil, err + } + + controller := &NativeArkChannelController{ + party: arkchannel.PartyClient, cfg: cfg, prePONROOR: cfg.OOR, + coordinator: coordinator, remote: remote, + fundingPeer: remote, paymentPeer: remote, keys: keys, + } + controller.initLifecycle(ctx) + + return controller, nil +} + +// NewHubArkChannelController eagerly composes one authenticated client +// endpoint for swapserver's channel directory. +func NewHubArkChannelController(ctx context.Context, + cfg HubArkChannelControllerConfig) (*NativeArkChannelController, + error) { + + cfg.Process = withArkChannelControllerDefaults(cfg.Process) + + if err := validateArkChannelProcessConfig(cfg.Process); err != nil { + return nil, err + } + if _, err := btcec.ParsePubKey(cfg.RemoteNode[:]); err != nil { + return nil, fmt.Errorf("parse client channel node: %w", err) + } + if cfg.PeerSender == nil || cfg.CloseObserver == nil || + cfg.CloseDefender == nil { + return nil, fmt.Errorf("complete hub channel process is " + + "required") + } + if err := cfg.Info.Validate(); err != nil { + return nil, err + } + var observers []arkchannel.RecordObserver + if cfg.Process.RecordObserver != nil { + observers = append(observers, cfg.Process.RecordObserver) + } + coordinator, err := arkchannel.NewCoordinator( + cfg.Process.Store, observers..., + ) + if err != nil { + return nil, err + } + keys, err := deriveNativeArkChannelKeys( + ctx, cfg.Process, arkchannel.PartyHub, + ) + if err != nil { + return nil, err + } + controller := &NativeArkChannelController{ + party: arkchannel.PartyHub, cfg: cfg.Process, + coordinator: coordinator, peerInfo: cfg.Info, keys: keys, + paymentBridge: cfg.PaymentBridge, + nodeFactory: cfg.NodeFactory, deferHubStart: cfg.DeferStart, + } + controller.initLifecycle(ctx) + if err := controller.startHub( + ctx, cfg.RemoteNode, cfg.PeerSender, cfg.CloseObserver, + cfg.CloseDefender, cfg.RecoveryDeltaFloor, + ); err != nil { + + controller.lifecycleCancel() + + return nil, err + } + + return controller, nil +} + +// initLifecycle creates the process-owned cancellation root used by startup, +// recovery, and maintenance workers. +func (c *NativeArkChannelController) initLifecycle(parent context.Context) { + c.lifecycleCtx, c.lifecycleCancel = context.WithCancel( + context.WithoutCancel(parent), + ) +} + +// validateArkChannelProcessConfig rejects incomplete process composition. +func validateArkChannelProcessConfig(cfg ArkChannelControllerConfig) error { + switch { + case cfg.Store == nil: + return fmt.Errorf("Ark channel store is required") + + case cfg.Wallet == nil: + return fmt.Errorf("Ark channel wallet is required") + + case cfg.ChainBackend == nil || cfg.ChainNotifier == nil: + return fmt.Errorf("Ark channel chain backend is required") + + case cfg.FeeEstimator == nil: + return fmt.Errorf("Ark channel fee estimator is required") + + case cfg.Materializer == nil || cfg.Recovery == nil: + return fmt.Errorf("Ark channel recovery runtime is required") + + case cfg.IdentityKey.PubKey == nil: + return fmt.Errorf("Ark channel identity key is required") + + case cfg.OORDestination == nil: + return fmt.Errorf("Ark channel OOR destination key is required") + + case cfg.NetParams == nil: + return fmt.Errorf("Ark channel network is required") + + case cfg.ChannelDataDir == "": + return fmt.Errorf("Ark channel data directory is required") + + default: + return nil + } +} + +// validateClientArkChannelProcessConfig checks the funding and publication +// dependencies that only the client-owned promotion process may execute. +func validateClientArkChannelProcessConfig( + cfg ArkChannelControllerConfig) error { + + if err := validateArkChannelProcessConfig(cfg); err != nil { + return err + } + switch { + case cfg.Peer == nil || cfg.PeerRPC == nil || cfg.PeerSender == nil: + return fmt.Errorf("Ark channel peer transport is required") + + case cfg.OOR == nil || cfg.Materializer == nil: + return fmt.Errorf("Ark channel OOR and unroller are required") + + case cfg.PrepareOOR == nil: + return fmt.Errorf("Ark channel OOR preparer is required") + + case cfg.LookupOOR == nil: + return fmt.Errorf("Ark channel OOR lookup is required") + + default: + return nil + } +} + +// deriveNativeArkChannelKeys restores stable process-owned policy roles. +func deriveNativeArkChannelKeys(ctx context.Context, + cfg ArkChannelControllerConfig, + party arkchannel.Party) (nativeArkChannelKeys, error) { + + derive := func(family keychain.KeyFamily) (keychain.KeyDescriptor, + error) { + + desc, err := cfg.Wallet.DeriveKey( + ctx, + keychain.KeyLocator{ + Family: family, Index: cfg.KeyIndex, + }, + ) + if err != nil { + return keychain.KeyDescriptor{}, err + } + + return *desc, nil + } + arkKey, err := derive(arkChannelArkKeyFamily) + if err != nil { + return nativeArkChannelKeys{}, err + } + backingKey, err := derive(arkChannelBackingKeyFamily) + if err != nil { + return nativeArkChannelKeys{}, err + } + keys := nativeArkChannelKeys{ark: arkKey, backing: backingKey} + if party == arkchannel.PartyClient { + keys.funder, err = derive(arkChannelFunderKeyFamily) + if err != nil { + return nativeArkChannelKeys{}, err + } + } + + return keys, nil +} + +// ensureClientStarted loads hub policy and starts the local native endpoint. +func (c *NativeArkChannelController) ensureClientStarted( + ctx context.Context) error { + + c.mu.Lock() + if c.node != nil { + c.mu.Unlock() + + return nil + } + if c.stopped { + c.mu.Unlock() + + return fmt.Errorf("Ark channel controller is stopped") + } + if c.lifecycleCtx == nil { + c.mu.Unlock() + + return fmt.Errorf("Ark channel controller is not started") + } + attempt := c.startAttempt + if attempt == nil { + attempt = &arkChannelStartAttempt{done: make(chan struct{})} + c.startAttempt = attempt + c.lifecycleWG.Add(1) + //nolint:contextcheck // startup uses the controller lifecycle + go c.runClientStart(attempt) + } + c.mu.Unlock() + + select { + case <-attempt.done: + return attempt.err + + case <-ctx.Done(): + return ctx.Err() + } +} + +// runClientStart executes one bounded process-owned startup attempt. +func (c *NativeArkChannelController) runClientStart( + attempt *arkChannelStartAttempt) { + + defer c.lifecycleWG.Done() + startCtx, cancel := context.WithTimeout( + c.lifecycleCtx, defaultArkChannelClientStartTimeout, + ) + defer cancel() + + starter := c.startClient + if c.clientStarter != nil { + starter = c.clientStarter + } + err := starter(startCtx) + + c.mu.Lock() + attempt.err = err + if c.startAttempt == attempt { + c.startAttempt = nil + } + close(attempt.done) + c.mu.Unlock() +} + +// startClient loads hub policy and composes the local native endpoint. +func (c *NativeArkChannelController) startClient(ctx context.Context) error { + delivery, err := c.refreshDelivery() + if err != nil { + return err + } + peer, err := c.clientStartupPeer(ctx) + if err != nil { + return err + } + remoteKey, err := btcec.ParsePubKey(peer.nodeKey[:]) + if err != nil { + return err + } + node, err := c.newNode( + ctx, arkchannel.PartyClient, remoteKey, c.cfg.PeerSender, + peer.materializationDelta, + ) + if err != nil { + return err + } + negotiator, err := node.NewNegotiator(c.fundingPeer, c.cfg.Recovery) + if err != nil { + _ = node.Stop() + + return err + } + closeEndpoint, err := lnruntime.NewNativeCooperativeCloseEndpoint( + arkchannel.PartyClient, node.Runtime(), nil, + keychain.KeyDescriptor{}, delivery, + ) + if err != nil { + _ = node.Stop() + + return err + } + publisher := lnruntime.CooperativeClosePublisherFunc(func( + ctx context.Context, id arkchannel.ID, terms arkchannel.Terms, + source arkchannel.VTXOBinding, + request arkchannel.CooperativeCloseRequest, + settlement arkchannel.CooperativeClose) error { + + return c.cfg.OOR.SettleCooperativeClose( + ctx, id, terms, source, request, settlement, c.keys.ark, + delivery.CooperativeCloseDelivery, + ) + }) + clientClose, err := lnruntime.NewClientCooperativeCloseProcess( + closeEndpoint, c.cfg.Peer, publisher, delivery, + ) + if err != nil { + _ = node.Stop() + + return err + } + service, err := c.newService(node, negotiator, clientClose) + if err != nil { + _ = node.Stop() + + return err + } + c.mu.Lock() + if c.stopped { + c.mu.Unlock() + _ = node.Stop() + + return fmt.Errorf("Ark channel controller is stopped") + } + c.service = service + c.mu.Unlock() + cleanup := func() { + _ = node.Stop() + + c.mu.Lock() + if c.service == service { + c.service = nil + } + c.mu.Unlock() + } + if err := tolerateNativeArkChannelFailures( + ctx, restoreNativeArkChannelBackings(ctx, node, service), + c.cfg.Log, "Ark channel backing restore failed", + ); err != nil { + + cleanup() + + return err + } + if err := node.Start(); err != nil { + cleanup() + + return err + } + if err := tolerateNativeArkChannelFailures( + ctx, c.restoreRecoveryWatches(ctx, service), c.cfg.Log, + "Ark channel recovery watch restore failed", + ); err != nil { + + cleanup() + + return err + } + resumeIDs, err := nativeArkChannelResumeIDs(ctx, service) + if err != nil { + cleanup() + + return err + } + c.mu.Lock() + if c.stopped { + c.mu.Unlock() + cleanup() + + return fmt.Errorf("Ark channel controller is stopped") + } + c.clientPeer = peer + c.node = node + c.clientClose = clientClose + c.mu.Unlock() + //nolint:contextcheck // recovery uses the controller lifecycle + c.startNativeArkChannelResume(service, node, resumeIDs) + //nolint:contextcheck // expiry protection owns the controller lifecycle + c.startLifecycleWorker(func(ctx context.Context) { + c.runSourceExpiryGuard(ctx, service, node) + }) + + return nil +} + +// startHub starts one operator endpoint for an authenticated client. +func (c *NativeArkChannelController) startHub(ctx context.Context, + remoteNode [33]byte, sender lnruntime.PeerEventSender, + closeObserver lnruntime.CooperativeCloseObserver, + closeDefender lnruntime.CooperativeCloseDefender, + sharedFloor uint32) error { + + remoteKey, err := btcec.ParsePubKey(remoteNode[:]) + if err != nil { + return err + } + records, err := c.coordinator.ListNonTerminal(ctx) + if err != nil { + return err + } + delta := ArkChannelMaterializationDelta( + records, max(c.peerInfo.FunderDelay, sharedFloor), + ) + node, err := c.newNode( + ctx, arkchannel.PartyHub, remoteKey, sender, delta, + ) + if err != nil { + return err + } + delivery, err := c.refreshDelivery() + if err != nil { + _ = node.Stop() + + return err + } + closeEndpoint, err := lnruntime.NewNativeCooperativeCloseEndpoint( + arkchannel.PartyHub, node.Runtime(), c.cfg.Wallet.BtcWallet, + c.keys.ark, delivery, + ) + if err != nil { + _ = node.Stop() + + return err + } + hubClose, err := lnruntime.NewHubCooperativeCloseProcess( + closeEndpoint, delivery, closeObserver, closeDefender, + ) + if err != nil { + _ = node.Stop() + + return err + } + service, err := c.newService( + node, node.FundingEndpoint(), + &lnruntime.HubCooperativeCloseExecutor{ + HubCooperativeCloseProcess: hubClose, + }, + ) + if err != nil { + _ = node.Stop() + + return err + } + c.service = service + cleanup := func() { + c.service = nil + _ = node.Stop() + } + if err := tolerateNativeArkChannelFailures( + ctx, restoreNativeArkChannelBackingRecords(node, records), + c.cfg.Log, "Ark channel backing restore failed", + ); err != nil { + + cleanup() + + return err + } + c.mu.Lock() + c.node, c.hubClose = node, hubClose + c.mu.Unlock() + if c.deferHubStart { + return nil + } + if err := c.StartHub(ctx); err != nil { + cleanup() + + return err + } + + return nil +} + +// StartHub starts a prepared hub peer after all durable peers are registered. +// A shared engine is started once; links and Ark recovery stay peer-scoped. +func (c *NativeArkChannelController) StartHub(ctx context.Context) error { + c.hubStartMu.Lock() + defer c.hubStartMu.Unlock() + if c.hubStarted { + return nil + } + c.mu.RLock() + node, service := c.node, c.service + stopped := c.stopped + c.mu.RUnlock() + if c.party != arkchannel.PartyHub || stopped || node == nil { + return fmt.Errorf("prepared native hub endpoint is required") + } + if err := node.Start(); err != nil { + return err + } + if err := tolerateNativeArkChannelFailures( + ctx, c.restoreRecoveryWatches(ctx, service), c.cfg.Log, + "Ark channel recovery watch restore failed", + ); err != nil { + return err + } + resumeIDs, err := nativeArkChannelResumeIDs(ctx, service) + if err != nil { + return err + } + //nolint:contextcheck // recovery uses the controller lifecycle + c.startNativeArkChannelResume(service, node, resumeIDs) + //nolint:contextcheck // expiry protection owns the controller lifecycle + c.startLifecycleWorker(func(ctx context.Context) { + c.runSourceExpiryGuard(ctx, service, node) + }) + c.hubStarted = true + + return nil +} + +// arkChannelBackingRestorer registers virtual funding before lnd restores its +// pending funding manager state. +type arkChannelBackingRestorer interface { + RestoreBacking(arkchannel.Terms, arkchannel.Backing) error +} + +// restoreNativeArkChannelBackings reconstructs the notifier's in-memory map +// from durable FSM records before any lnd subsystem starts. +func restoreNativeArkChannelBackings(ctx context.Context, + restorer arkChannelBackingRestorer, service *arkchannel.Service) error { + + records, err := service.ListChannels(ctx) + if err != nil { + return err + } + + return restoreNativeArkChannelBackingRecords(restorer, records) +} + +// restoreNativeArkChannelBackingRecords registers every signed backing in one +// pre-start snapshot of the durable channel store. +func restoreNativeArkChannelBackingRecords(restorer arkChannelBackingRestorer, + records []arkchannel.Record) error { + + failures := make([]arkchannel.ResumeFailure, 0) + for _, record := range records { + backing := record.Snapshot.Backing + if backing == nil || + record.Snapshot.Phase == arkchannel.PhaseClosed { + + continue + } + if err := restorer.RestoreBacking( + record.Snapshot.Terms, *backing, + ); err != nil { + + failures = append(failures, arkchannel.ResumeFailure{ + ChannelID: record.Snapshot.Terms.ID, + Err: fmt.Errorf( + "restore backing: %w", err, + ), + }) + } + } + if len(failures) > 0 { + return &arkchannel.ResumeFailures{Failures: failures} + } + + return nil +} + +// tolerateNativeArkChannelFailures reports durable per-channel failures without +// tearing down independent links that recovered successfully. +func tolerateNativeArkChannelFailures(ctx context.Context, err error, + log btclog.Logger, message string) error { + + if err == nil { + return nil + } + var failures *arkchannel.ResumeFailures + if !errors.As(err, &failures) { + return err + } + if log == nil { + log = btclog.Disabled + } + for _, failure := range failures.Failures { + log.WarnS( + ctx, message, failure.Err, btclog.Fmt( + "channel_id", "%x", failure.ChannelID[:], + ), + ) + } + + return nil +} + +// arkChannelForceCloseResumer reconciles one materialized channel with lnd's +// durable commitment-broadcast state. +type arkChannelForceCloseResumer interface { + ResumeForceCloseChannel(wire.OutPoint) error +} + +// resumeOnchainArkChannelRecords attempts every materialized channel and +// returns only isolated failures after the complete recovery pass. +func resumeOnchainArkChannelRecords(node arkChannelForceCloseResumer, + records []arkchannel.Record) error { + + failures := make([]arkchannel.ResumeFailure, 0) + for _, record := range records { + if !shouldResumeOnchainArkChannel(record.Snapshot) { + continue + } + if record.Snapshot.Backing == nil { + failures = append(failures, arkchannel.ResumeFailure{ + ChannelID: record.Snapshot.Terms.ID, + Err: fmt.Errorf( + "materialized channel has no " + + "backing", + ), + }) + + continue + } + if err := node.ResumeForceCloseChannel( + record.Snapshot.Backing.ChannelPoint, + ); err != nil { + + failures = append(failures, arkchannel.ResumeFailure{ + ChannelID: record.Snapshot.Terms.ID, + Err: fmt.Errorf("resume materialized channel: "+ + "%w", + err), + }) + } + } + if len(failures) > 0 { + return &arkchannel.ResumeFailures{Failures: failures} + } + + return nil +} + +// shouldResumeOnchainArkChannel reports whether backing publication crossed +// the durable handoff but lnd may still need its commitment broadcast marker. +func shouldResumeOnchainArkChannel(snapshot arkchannel.Snapshot) bool { + return snapshot.Phase == arkchannel.PhaseOnChain +} + +// restoreRecoveryWatches arms persisted ancestry before replaying any channel +// action that could activate or publish native lnd state. +func (c *NativeArkChannelController) restoreRecoveryWatches(ctx context.Context, + service *arkchannel.Service) error { + + records, err := service.ListChannels(ctx) + if err != nil { + return err + } + + return c.cfg.Recovery.RestoreWatches(ctx, records) +} + +// newNode composes native lnd state over one authenticated peer sender. +func (c *NativeArkChannelController) newNode(ctx context.Context, + party arkchannel.Party, remoteKey *btcec.PublicKey, + sender lnruntime.PeerEventSender, materializationDelta uint32) ( + *lnruntime.NativeNode, error) { + + transport, err := lnruntime.NewDurablePeerTransport( + lnruntime.DurablePeerTransportConfig{ + Sender: sender, + CorrelationKey: hex.EncodeToString( + c.cfg.IdentityKey.PubKey.SerializeCompressed(), + ), + }, + ) + if err != nil { + return nil, err + } + log := c.cfg.Log + if log == nil { + log = btclog.Disabled + } + logCtx := context.WithoutCancel(ctx) + onChannelFailure := func(channelID lnwire.ChannelID, + scid lnwire.ShortChannelID, + failure htlcswitch.LinkFailureError) { + + log.WarnS(logCtx, "Native Ark channel link failed", + failure, + btclog.Fmt("channel_id", "%x", channelID[:]), + btclog.Fmt("scid", "%v", scid), + ) + } + //nolint:contextcheck // link callbacks use the controller lifecycle + shouldDisableChannelAdds := func(channelPoint wire.OutPoint) (bool, + error) { + + checkCtx, cancel := context.WithTimeout( + c.lifecycleCtx, 5*time.Second, + ) + defer cancel() + record, err := c.coordinator.FindByChannelPoint( + checkCtx, channelPoint, + ) + if err != nil { + return false, fmt.Errorf("load Ark channel refresh "+ + "lifecycle: %w", err) + } + + if record.Snapshot.Phase == arkchannel.PhaseMaterializing { + return true, nil + } + // The external hold has its own release barrier; don't also + // acquire an ordinary flush that an unsigned abort can't undo. + if shouldHoldArkChannelClose(record.Snapshot) { + return false, nil + } + if record.Snapshot.Source == nil { + return false, fmt.Errorf("channel source is missing") + } + height, _, err := c.cfg.ChainBackend.BestBlock(checkCtx) + if err != nil { + return false, err + } + + return c.cfg.Recovery.SourceExpiring( + checkCtx, record.Snapshot.Terms, + *record.Snapshot.Source, height, + ) + } + + //nolint:contextcheck // link callbacks use the controller lifecycle + shouldHoldExternalClose := func(point wire.OutPoint) (bool, error) { + checkCtx, cancel := context.WithTimeout( + c.lifecycleCtx, 5*time.Second, + ) + defer cancel() + + record, err := c.coordinator.FindByChannelPoint(checkCtx, point) + if err != nil { + return false, err + } + + return shouldHoldArkChannelClose(record.Snapshot), nil + } + + opener := c.cfg.OpenChannelDB + if opener == nil { + opener = db.OpenChannelDB + } + nodeCfg := lnruntime.NativeNodeConfig{ + Party: party, + Chain: c.cfg.Wallet.BtcWallet, Notifier: c.cfg.ChainNotifier, + WalletController: c.cfg.Wallet.BtcWallet, + KeyRing: c.cfg.Wallet.KeyRing(), Signer: c. + cfg. + Wallet. + BtcWallet, + FeeEstimator: c.cfg.FeeEstimator, NetParams: c.cfg.NetParams, + IdentityKey: c.cfg.IdentityKey, BackingKey: c.keys.backing, + RemoteNodeKey: remoteKey, Transport: transport, + Intents: c.coordinator, OnChannelFailure: onChannelFailure, + MaterializationDelta: materializationDelta, + ChannelLifecycle: c, + ShouldDisableChannelAdds: shouldDisableChannelAdds, + ShouldHoldExternalClose: shouldHoldExternalClose, + } + if c.nodeFactory != nil { + return c.nodeFactory(nodeCfg) + } + channelDB, err := opener(c.cfg.ChannelDataDir) + if err != nil { + return nil, err + } + nodeCfg.DB, nodeCfg.OwnsDB = channelDB, true + + return lnruntime.NewNativeNode(nodeCfg) +} + +// ChainWatchOwner reports whether lnd or the Ark lifecycle currently owns +// chain observation for a channel. +func (c *NativeArkChannelController) ChainWatchOwner(ctx context.Context, + channel *chanstate.OpenChannel) (contractcourt.ChainWatchOwner, error) { + + record, err := c.coordinator.FindByChannelPoint( + ctx, channel.FundingOutpoint, + ) + if err != nil { + return 0, fmt.Errorf("load Ark channel lifecycle: %w", err) + } + + if shouldWatchArkChannel(record.Snapshot.Phase) { + return contractcourt.ChainWatchOwnerLnd, nil + } + + return contractcourt.ChainWatchOwnerAux, nil +} + +// PrepareCommitmentPublish materializes the Ark backing before lnd publishes +// a commitment transaction. +func (c *NativeArkChannelController) PrepareCommitmentPublish( + ctx context.Context, channelPoint wire.OutPoint) error { + + return c.materializeBeforeCommitment(ctx, channelPoint) +} + +const arkChannelFinalizationRetry = time.Second + +// WaitForChannelFinalization durably records lnd's terminal channel state. +// The Ark owner retains retry policy so lnd only provides the cancellation and +// ordering boundary. +func (c *NativeArkChannelController) WaitForChannelFinalization( + ctx context.Context, channelPoint wire.OutPoint) error { + + for { + err := c.recordFullyResolvedChannel(ctx, channelPoint) + if err == nil { + return nil + } + + if c.cfg.Log != nil { + c.cfg.Log.WarnS(ctx, "Unable to finalize Ark channel", + err, + btclog.Fmt("channel_point", "%v", channelPoint), + ) + } + + timer := time.NewTimer(arkChannelFinalizationRetry) + select { + case <-timer.C: + continue + + case <-ctx.Done(): + timer.Stop() + + return ctx.Err() + } + } +} + +// materializeBeforeCommitment blocks lnd's local commitment publication until +// either recovery-ready endpoint has durably published the exact backing. +func (c *NativeArkChannelController) materializeBeforeCommitment( + ctx context.Context, channelPoint wire.OutPoint) error { + + record, err := c.coordinator.FindByChannelPoint(ctx, channelPoint) + if err != nil { + return fmt.Errorf("load channel publication lifecycle: %w", err) + } + if record.Snapshot.Phase == arkchannel.PhaseOnChain { + return nil + } + if c.service == nil { + return fmt.Errorf("Ark channel service is not ready") + } + record, err = c.service.Materialize( + ctx, record.Snapshot.Terms.ID, + ) + if err != nil { + return fmt.Errorf("materialize channel backing: %w", err) + } + if record.Snapshot.Phase != arkchannel.PhaseOnChain { + return fmt.Errorf("channel backing stopped in phase %s", + record.Snapshot.Phase) + } + + return nil +} + +// shouldWatchArkChannel reports whether lnd must own the channel's chain and +// contract lifecycle. An unpublished outpoint remains dormant, while an +// observed publication can be handled without first contacting the peer. +func shouldWatchArkChannel(phase arkchannel.Phase) bool { + switch phase { + case arkchannel.PhaseActivating, arkchannel.PhaseActive, + arkchannel.PhaseMaterializing, arkchannel.PhaseOnChain, + arkchannel.PhaseCoopClosing, + arkchannel.PhaseCoopCloseSigned, + arkchannel.PhaseCoopClosePublished: + return true + + default: + return false + } +} + +// shouldHoldArkChannelClose preserves a released payout even when expiry +// has handed the competing backing to lnd. PhaseOnChain alone is not a hold. +func shouldHoldArkChannelClose(s arkchannel.Snapshot) bool { + if s.CooperativeClose != nil { + return true + } + switch s.Phase { + case arkchannel.PhaseCoopClosing, + arkchannel.PhaseCoopCloseSigned, + arkchannel.PhaseCoopClosePublished: + return true + + default: + return false + } +} + +// recordFullyResolvedChannel advances the Ark FSM only after lnd has resolved +// and swept every output. Chain evidence can recover a peer that never +// received the initiating endpoint's materialization transition. +func (c *NativeArkChannelController) recordFullyResolvedChannel( + ctx context.Context, channelPoint wire.OutPoint) error { + + record, err := c.coordinator.FindByChannelPoint(ctx, channelPoint) + if err != nil { + return err + } + switch record.Snapshot.Phase { + case arkchannel.PhaseActivating, arkchannel.PhaseActive, + arkchannel.PhaseMaterializing, + arkchannel.PhaseCoopClosing, + arkchannel.PhaseCoopCloseSigned: + + record, _, err = c.coordinator.Apply( + ctx, record.Snapshot.Terms.ID, + &arkchannel.BackingObserved{ + TxID: channelPoint.Hash, + }, + ) + if err != nil { + return err + } + + case arkchannel.PhaseOnChain: + case arkchannel.PhaseClosed: + return nil + + default: + return fmt.Errorf("cannot resolve on-chain channel from %s", + record.Snapshot.Phase) + } + + _, _, err = c.coordinator.Apply( + ctx, record.Snapshot.Terms.ID, &arkchannel.ChannelClosed{}, + ) + + return err +} + +// newService binds the endpoint's native lnd and Ark side effects to one FSM. +func (c *NativeArkChannelController) newService(node *lnruntime.NativeNode, + funding arkchannel.FundingCanceler, + closer arkchannel.ChannelCooperativeCloser) (*arkchannel.Service, + error) { + + var oor arkchannel.OORTransferController + if c.cfg.OOR != nil { + oor = c.cfg.OOR + } + var materializer arkchannel.ChannelMaterializer + if c.cfg.Materializer != nil { + materializer = c.cfg.Materializer + } + log := c.cfg.Log + if log == nil { + log = btclog.Disabled + } + forceCloser := &loggedArkChannelForceCloser{ + node: node, log: log, + } + executor, err := arkchannel.NewNativeExecutor( + c.party, node.FundingActivator(), funding, oor, materializer, + node, forceCloser, closer, + ) + if err != nil { + return nil, err + } + + service, err := arkchannel.NewService(c.party, c.coordinator, executor) + if err != nil { + return nil, err + } + if err := c.cfg.Recovery.BindChannelEventSink(service); err != nil { + return nil, err + } + + return service, nil +} + +// PromoteVTXO prepares and activates one client-funded OOR channel. +func (c *NativeArkChannelController) PromoteVTXO(ctx context.Context, + amount btcutil.Amount, idempotencyKey string) (arkchannel.Record, + error) { + + if c.party != arkchannel.PartyClient { + return arkchannel.Record{}, fmt.Errorf("only a client can " + + "promote VTXO liquidity") + } + if amount <= 0 { + return arkchannel.Record{}, fmt.Errorf("channel amount must " + + "be positive") + } + if idempotencyKey == "" { + return arkchannel.Record{}, fmt.Errorf("idempotency key is " + + "required") + } + if len(idempotencyKey) > maxArkChannelIdempotencyKeyLength { + return arkchannel.Record{}, fmt.Errorf("idempotency key "+ + "exceeds %d bytes", maxArkChannelIdempotencyKeyLength) + } + if err := c.ensureClientStarted(ctx); err != nil { + return arkchannel.Record{}, err + } + terms, existing, err := c.newPromotionTerms( + ctx, amount, idempotencyKey, + ) + if err != nil { + return arkchannel.Record{}, err + } + if existing != nil && existing.Snapshot.Source != nil { + if _, err := c.resumeBoundPromotion( + ctx, *existing, + ); err != nil { + return arkchannel.Record{}, err + } + + return c.waitPromotionCompletion(ctx, terms.ID) + } + if _, err := c.remote.RegisterPromotion(ctx, terms); err != nil { + return arkchannel.Record{}, err + } + if _, err := c.service.RegisterPromotion(ctx, terms); err != nil { + return arkchannel.Record{}, err + } + if _, err := c.service.StartOORPreparation(ctx, terms.ID); err != nil { + return arkchannel.Record{}, err + } + binding, err := c.cfg.PrepareOOR( + ctx, terms, arkchannel.DefaultBackingFee, + ) + if err != nil { + return arkchannel.Record{}, err + } + if _, err := c.remote.BindPreparedOOR( + ctx, terms.ID, binding, + ); err != nil { + return arkchannel.Record{}, err + } + if _, err := c.service.BindPreparedOOR( + ctx, terms.ID, binding, + ); err != nil { + return arkchannel.Record{}, err + } + + return c.waitPromotionCompletion(ctx, terms.ID) +} + +// waitPromotionCompletion preserves the blocking promotion contract across +// idempotent retries while the durable channel FSM finishes asynchronously. +func (c *NativeArkChannelController) waitPromotionCompletion( + ctx context.Context, id arkchannel.ID) (arkchannel.Record, error) { + + ticker := time.NewTicker(arkChannelControllerPollInterval) + defer ticker.Stop() + + for { + record, err := c.service.GetChannel(ctx, id) + if err != nil { + return arkchannel.Record{}, err + } + switch record.Snapshot.Phase { + case arkchannel.PhaseActive: + ready, err := c.hubPromotionReady(ctx, record.Snapshot) + if err != nil { + return arkchannel.Record{}, err + } + if ready { + + // The local channel may have started closing + // while the peer read was in flight. + return c.service.GetChannel(ctx, id) + } + + case arkchannel.PhaseFailed: + return arkchannel.Record{}, fmt.Errorf("channel "+ + "promotion failed: %s", record.Snapshot.Failure) + + case arkchannel.PhaseRequested, + arkchannel.PhaseNegotiating, + arkchannel.PhaseBackingReady, + arkchannel.PhaseActivating, + arkchannel.PhaseCancelling: + + // A peer callback or replayable channel action still + // owns the next durable transition. + + default: + // Preserve idempotent lookup after the channel has + // moved beyond its active creation lifecycle. + return record, nil + } + + select { + case <-ctx.Done(): + return arkchannel.Record{}, ctx.Err() + + case <-ticker.C: + } + } +} + +// resumeBoundPromotion resumes only channel-creation work. A later channel +// phase must be reported as-is instead of revalidating the finalized OOR. +func (c *NativeArkChannelController) resumeBoundPromotion(ctx context.Context, + record arkchannel.Record) (arkchannel.Record, error) { + + switch record.Snapshot.Phase { + case arkchannel.PhaseNegotiating, arkchannel.PhaseBackingReady, + arkchannel.PhaseActivating, arkchannel.PhaseCancelling: + return c.service.ResumeChannelAction( + ctx, record.Snapshot.Terms.ID, + ) + + default: + return record, nil + } +} + +// newPromotionTerms creates stable protocol identifiers and binds every key +// role to the two endpoint wallets. +func (c *NativeArkChannelController) newPromotionTerms(ctx context.Context, + amount btcutil.Amount, idempotencyKey string) (arkchannel.Terms, + *arkchannel.Record, error) { + + if idempotencyKey == "" { + return arkchannel.Terms{}, nil, fmt.Errorf("idempotency key " + + "is required") + } + id, pending, scid := c.promotionIdentifiers(idempotencyKey) + + record, err := c.coordinator.Get(ctx, id) + if err == nil { + terms := record.Snapshot.Terms + info := fundingPeerFromTerms(terms) + expected, err := c.newClientFundedTerms( + id, pending, scid, amount, info, + ) + if err != nil { + return arkchannel.Terms{}, nil, err + } + if terms != expected || + terms.HubNodeKey != c.clientPeer.nodeKey { + return arkchannel.Terms{}, nil, fmt.Errorf( + "idempotency key is already bound to " + + "different channel terms") + } + + return terms, &record, nil + } + if !errors.Is(err, arkchannel.ErrNotFound) { + return arkchannel.Terms{}, nil, err + } + info, err := c.clientPeer.promotionPolicy(ctx, c.remote) + if err != nil { + return arkchannel.Terms{}, nil, err + } + terms, err := c.newClientFundedTerms(id, pending, scid, amount, info) + + return terms, nil, err +} + +// promotionIdentifiers derives every retry-sensitive protocol identifier from +// the daemon identity and caller-provided idempotency key. +func (c *NativeArkChannelController) promotionIdentifiers( + idempotencyKey string) (arkchannel.ID, [32]byte, uint64) { + + derive := func(label string) [32]byte { + hash := sha256.New() + _, _ = hash.Write( + []byte("wavelength/ark-channel/promotion/v1/"), + ) + _, _ = hash.Write([]byte(label)) + _, _ = hash.Write([]byte{0}) + _, _ = hash.Write( + c.cfg.IdentityKey.PubKey.SerializeCompressed(), + ) + _, _ = hash.Write([]byte{0}) + _, _ = hash.Write([]byte(idempotencyKey)) + var result [32]byte + copy(result[:], hash.Sum(nil)) + + return result + } + id := arkchannel.ID(derive("channel-id")) + pending := derive("pending-channel-id") + scidSeed := derive("reserved-scid") + blockHeight := uint32(scidSeed[0])<<16 | + uint32(scidSeed[1])<<8 | uint32(scidSeed[2]) + txIndex := uint32(scidSeed[3])<<16 | + uint32(scidSeed[4])<<8 | uint32(scidSeed[5]) + if blockHeight == 0 { + blockHeight = 1 + } + if txIndex == 0 { + txIndex = 1 + } + scid := lnwire.ShortChannelID{ + BlockHeight: blockHeight, TxIndex: txIndex, + TxPosition: 0, + }.ToUint64() + + return id, pending, scid +} + +// newClientFundedTerms binds deterministic or random protocol identifiers to +// this endpoint's fixed channel and Ark keys. +func (c *NativeArkChannelController) newClientFundedTerms(id arkchannel.ID, + pending [32]byte, scid uint64, amount btcutil.Amount, + info lnruntime.FundingPeerInfo) (arkchannel.Terms, error) { + + terms := arkchannel.Terms{ + ID: id, + Kind: arkchannel.KindPromotion, + Funder: arkchannel.PartyClient, + PendingChannelID: pending, ReservedSCID: scid, + Capacity: amount, + VTXO: arkchannel.VTXOTerms{ + ChannelDelay: info.ChannelDelay, + FunderDelay: info.FunderDelay, + MinExitDelay: info.MinimumExitDelay, + }, + } + copy( + terms.ClientNodeKey[:], + c.cfg.IdentityKey.PubKey.SerializeCompressed(), + ) + terms.HubNodeKey = info.HubNodeKey + copy( + terms.VTXO.ClientArkKey[:], + c.keys.ark.PubKey.SerializeCompressed(), + ) + terms.VTXO.HubArkKey = info.HubArkKey + terms.VTXO.ArkOperatorKey = info.ArkOperatorKey + copy( + terms.VTXO.ClientChannelKey[:], + c.keys.backing.PubKey.SerializeCompressed(), + ) + terms.VTXO.HubChannelKey = info.HubChannelKey + copy( + terms.VTXO.FunderKey[:], + c.keys.funder.PubKey.SerializeCompressed(), + ) + + return terms, terms.Validate() +} + +// PayLightningInvoice asks the hub to dispatch one public invoice only after +// this endpoint's private same-hash HTLC is held. +func (c *NativeArkChannelController) PayLightningInvoice(ctx context.Context, + paymentRequest string, maxFee btcutil.Amount) (LightningPaymentResult, + error) { + + if c.party != arkchannel.PartyClient { + return LightningPaymentResult{}, fmt.Errorf("public payment " + + "is available only on the client endpoint") + } + if paymentRequest == "" || maxFee < 0 { + return LightningPaymentResult{}, fmt.Errorf("valid payment " + + "request and maximum fee are required") + } + if err := c.ensureClientStarted(ctx); err != nil { + return LightningPaymentResult{}, err + } + preparation, err := c.paymentPeer.PrepareOutgoingPayment( + ctx, paymentRequest, maxFee, + ) + if err != nil { + return LightningPaymentResult{}, err + } + record, err := c.service.GetChannel(ctx, preparation.ChannelID) + if err != nil { + return LightningPaymentResult{}, c.cancelOutgoingPayment( + ctx, preparation.PaymentHash, err, + ) + } + if record.Snapshot.Terms.ReservedSCID != preparation.ReservedSCID { + err := fmt.Errorf("payment preparation changed channel SCID") + + return LightningPaymentResult{}, c.cancelOutgoingPayment( + ctx, preparation.PaymentHash, err, + ) + } + preimage, err := c.node.PayInvoiceResult( + ctx, record, preparation.PaymentHash, preparation.PrivateAmount, + ) + if err != nil { + return LightningPaymentResult{}, c.cancelOutgoingPayment( + ctx, preparation.PaymentHash, err, + ) + } + if preimage.Hash() != preparation.PaymentHash { + err := fmt.Errorf("payment preimage does not match preparation") + + return LightningPaymentResult{}, c.cancelOutgoingPayment( + ctx, preparation.PaymentHash, err, + ) + } + + return LightningPaymentResult{ + PaymentHash: preparation.PaymentHash, Preimage: preimage, + PrivateAmount: preparation.PrivateAmount, Fee: preparation.Fee, + ChannelID: preparation.ChannelID, + }, nil +} + +// cancelOutgoingPayment releases a prepared public-payment reservation even +// when the request that detected the failure has already been canceled. +func (c *NativeArkChannelController) cancelOutgoingPayment(ctx context.Context, + hash lntypes.Hash, cause error) error { + + cleanupCtx, cancel := context.WithTimeout( + context.WithoutCancel(ctx), arkChannelPaymentCleanupTimeout, + ) + defer cancel() + + err := c.paymentPeer.CancelOutgoingPayment( + cleanupCtx, hash, cause.Error(), + ) + if err != nil { + return errors.Join( + cause, fmt.Errorf("cancel outgoing payment: %w", err), + ) + } + + return cause +} + +// PrepareIncomingPayment installs the known-preimage native invoice before a +// route hint can be exposed to an external payer. +func (c *NativeArkChannelController) PrepareIncomingPayment(ctx context.Context, + preimage lntypes.Preimage, amount btcutil.Amount) error { + + if c.party != arkchannel.PartyClient { + return fmt.Errorf("incoming payment preparation is client only") + } + if err := c.ensureClientStarted(ctx); err != nil { + return err + } + + return c.AddInvoiceWithPreimage(ctx, preimage, amount) +} + +// RegisterIncomingPayment binds the advertised future SCID to this +// authenticated endpoint after the private invoice is durable. It returns the +// public CLTV delta needed to safely nest the private channel payment. +func (c *NativeArkChannelController) RegisterIncomingPayment( + ctx context.Context, hash lntypes.Hash, amount btcutil.Amount, + reservedSCID uint64) (arkchannel.ID, uint32, error) { + + if c.party != arkchannel.PartyClient { + return arkchannel.ID{}, 0, fmt.Errorf("incoming payment " + + "registration is client only") + } + if err := c.ensureClientStarted(ctx); err != nil { + return arkchannel.ID{}, 0, err + } + id, err := c.paymentPeer.RegisterIncomingPayment( + ctx, hash, amount, reservedSCID, + ) + if err != nil { + return arkchannel.ID{}, 0, err + } + record, err := c.service.GetChannel(ctx, id) + if err != nil { + return arkchannel.ID{}, 0, err + } + if record.Snapshot.Phase != arkchannel.PhaseActive { + return arkchannel.ID{}, 0, fmt.Errorf("registered channel is " + + "not active") + } + delta, err := lnruntime.ArkChannelReceiveCLTVDelta( + record.Snapshot.Terms.VTXO, + ) + + return id, delta, err +} + +// WaitIncomingPayment waits for the private hold invoice and returns the active +// channel that delivered it without releasing the shared preimage. +func (c *NativeArkChannelController) WaitIncomingPayment(ctx context.Context, + hash lntypes.Hash) (arkchannel.ID, error) { + + if c.party != arkchannel.PartyClient { + return arkchannel.ID{}, fmt.Errorf("incoming payment wait is " + + "client only") + } + if err := c.ensureClientStarted(ctx); err != nil { + return arkchannel.ID{}, err + } + + incomingSCID, err := c.node.WaitInvoiceAcceptedChannel(ctx, hash) + if err != nil { + return arkchannel.ID{}, err + } + + record, err := c.activeChannelBySCID(ctx, incomingSCID) + if err != nil { + return arkchannel.ID{}, err + } + + return record.Snapshot.Terms.ID, nil +} + +// activeChannelBySCID binds an accepted native invoice HTLC to one durable +// active channel instead of trusting the public route reservation. +func (c *NativeArkChannelController) activeChannelBySCID(ctx context.Context, + scid lnwire.ShortChannelID) (arkchannel.Record, error) { + + if scid == (lnwire.ShortChannelID{}) { + return arkchannel.Record{}, fmt.Errorf("incoming payment " + + "channel SCID is empty") + } + record, err := c.cfg.Store.GetBySCID(ctx, scid.ToUint64()) + if err != nil { + return arkchannel.Record{}, err + } + if record.Snapshot.Phase != arkchannel.PhaseActive { + return arkchannel.Record{}, fmt.Errorf("incoming channel is " + + "not active") + } + + return record, nil +} + +// SettleIncomingPayment releases the private hold invoice after the SDK +// durably records acceptance on the registered channel. +func (c *NativeArkChannelController) SettleIncomingPayment(ctx context.Context, + preimage lntypes.Preimage) error { + + if c.party != arkchannel.PartyClient { + return fmt.Errorf("incoming payment settlement is client only") + } + if err := c.ensureClientStarted(ctx); err != nil { + return err + } + + return c.SettleHoldInvoice(ctx, preimage) +} + +// CancelIncomingPayment cancels the registration and its private hold invoice. +func (c *NativeArkChannelController) CancelIncomingPayment(ctx context.Context, + hash lntypes.Hash, reason string) error { + + if c.party != arkchannel.PartyClient { + return fmt.Errorf("incoming payment cancellation is client " + + "only") + } + if reason == "" { + return fmt.Errorf("incoming payment cancellation reason is " + + "required") + } + if err := c.ensureClientStarted(ctx); err != nil { + return err + } + if err := c.paymentPeer.CancelIncomingPayment( + ctx, hash, reason, + ); err != nil { + return fmt.Errorf("cancel hub incoming payment: %w", err) + } + if err := c.CancelInvoice(ctx, hash); err != nil { + return fmt.Errorf("cancel incoming hold invoice: %w", err) + } + + return nil +} + +// MaterializeAndForceClose asks lnd to force close. Its blocking publication +// barrier materializes the client-funded backing first, while the peer learns +// the lifecycle only from its already armed chain watcher. +func (c *NativeArkChannelController) MaterializeAndForceClose( + ctx context.Context, id arkchannel.ID) (arkchannel.Record, + chainhash.Hash, chainhash.Hash, error) { + + if c.party != arkchannel.PartyClient { + return arkchannel.Record{}, chainhash.Hash{}, chainhash.Hash{}, + fmt.Errorf("only a client can request force close") + } + if err := c.ensureClientStarted(ctx); err != nil { + return arkchannel.Record{}, chainhash.Hash{}, + chainhash.Hash{}, err + } + record, err := c.service.GetChannel(ctx, id) + if err != nil { + return arkchannel.Record{}, chainhash.Hash{}, + chainhash.Hash{}, err + } + if record.Snapshot.Backing == nil { + return arkchannel.Record{}, chainhash.Hash{}, chainhash.Hash{}, + fmt.Errorf("materialized channel backing is missing") + } + backing := record.Snapshot.Backing.Clone() + closeTx, forceErr := c.node.ForceCloseChannel(backing.ChannelPoint) + if forceErr == nil { + if closeTx == nil { + return arkchannel.Record{}, chainhash.Hash{}, + chainhash.Hash{}, fmt.Errorf("lnd returned " + + "no force-close transaction") + } + } + + // Both endpoints watch the unpublished channel point before Ark + // materializes it. Either commitment may therefore win publication, + // even when the local ForceCloseChannel call itself succeeds. Return + // only the transaction lnd durably classified as the channel close. + closeTxID, waitErr := c.node.WaitForceCloseResult( + ctx, backing.ChannelPoint, + ) + if waitErr != nil { + if forceErr != nil { + return arkchannel.Record{}, chainhash.Hash{}, + chainhash.Hash{}, fmt.Errorf("force close "+ + "channel: %w; reconcile peer close: %v", + forceErr, waitErr) + } + + return arkchannel.Record{}, chainhash.Hash{}, chainhash.Hash{}, + fmt.Errorf("reconcile force close: %w", waitErr) + } + record, err = c.service.GetChannel(ctx, id) + if err != nil { + return arkchannel.Record{}, chainhash.Hash{}, + chainhash.Hash{}, err + } + + return record, backing.ChannelPoint.Hash, closeTxID, nil +} + +// RefreshChannel starts the client-owned 3-of-3 in-Ark refresh process. +func (c *NativeArkChannelController) RefreshChannel(ctx context.Context, + id arkchannel.ID) (arkchannel.Record, error) { + + if c.party != arkchannel.PartyClient { + return arkchannel.Record{}, fmt.Errorf("only a client can " + + "refresh a channel in Ark") + } + if err := c.ensureClientStarted(ctx); err != nil { + return arkchannel.Record{}, err + } + + return c.clientClose.RequestCooperativeClose(ctx, id) +} + +// GetChannel returns the endpoint's durable Ark channel record. +func (c *NativeArkChannelController) GetChannel(ctx context.Context, + id arkchannel.ID) (arkchannel.Record, error) { + + return c.coordinator.Get(ctx, id) +} + +// ListChannels returns every channel that still needs recovery, observation, +// or operator action without requiring the native endpoint to be online. +func (c *NativeArkChannelController) ListChannels(ctx context.Context) ( + []arkchannel.Record, error) { + + return c.coordinator.ListNonTerminal(ctx) +} + +// ChannelBalance returns lnd's authoritative active-channel balances. +func (c *NativeArkChannelController) ChannelBalance(ctx context.Context, + id arkchannel.ID) (btcutil.Amount, btcutil.Amount, error) { + + if c.party == arkchannel.PartyClient { + if err := c.ensureClientStarted(ctx); err != nil { + return 0, 0, err + } + } + c.mu.RLock() + node := c.node + c.mu.RUnlock() + if node == nil { + return 0, 0, fmt.Errorf("native Ark channel endpoint is not " + + "ready") + } + record, err := c.coordinator.Get(ctx, id) + if err != nil { + return 0, 0, err + } + + return node.ChannelBalance(record) +} + +// SelectActiveChannel finds an ordinary native channel with enough balance on +// the requested local or remote side. lnd remains authoritative and may still +// reject a racing payment that consumes the same balance. +func (c *NativeArkChannelController) SelectActiveChannel(ctx context.Context, + amount btcutil.Amount, localSends bool) (arkchannel.Record, error) { + + if amount <= 0 { + return arkchannel.Record{}, fmt.Errorf("payment amount must " + + "be positive") + } + if c.party == arkchannel.PartyClient { + if err := c.ensureClientStarted(ctx); err != nil { + return arkchannel.Record{}, err + } + } + c.mu.RLock() + service := c.service + node := c.node + c.mu.RUnlock() + if service == nil || node == nil { + return arkchannel.Record{}, fmt.Errorf("native Ark channel " + + "endpoint is not ready") + } + records, err := service.ListChannels(ctx) + if err != nil { + return arkchannel.Record{}, err + } + for _, record := range records { + if record.Snapshot.Phase != arkchannel.PhaseActive { + continue + } + local, remote, err := node.ChannelBalance(record) + if err != nil { + continue + } + available := remote + if localSends { + available = local + } + if available >= amount { + return record, nil + } + } + + return arkchannel.Record{}, fmt.Errorf("%w for %d sat", + ErrInsufficientArkChannelLiquidity, amount) +} + +// AddHoldInvoice registers the private source for an outgoing bridge. +func (c *NativeArkChannelController) AddHoldInvoice(ctx context.Context, + hash lntypes.Hash, amount btcutil.Amount) error { + + if c.party == arkchannel.PartyClient { + if err := c.ensureClientStarted(ctx); err != nil { + return err + } + } + + return c.node.AddHoldInvoice(ctx, hash, amount) +} + +// AddInvoiceWithPreimage registers the private hold destination for an incoming +// bridge before its BOLT 11 invoice is exposed to a payer. +func (c *NativeArkChannelController) AddInvoiceWithPreimage(ctx context.Context, + preimage lntypes.Preimage, amount btcutil.Amount) error { + + if c.party == arkchannel.PartyClient { + if err := c.ensureClientStarted(ctx); err != nil { + return err + } + } + _, err := c.node.AddInvoiceWithPreimage( + ctx, amount, preimage, true, + ) + + return err +} + +// WaitInvoiceAccepted waits for a private hold invoice HTLC. +func (c *NativeArkChannelController) WaitInvoiceAccepted(ctx context.Context, + hash lntypes.Hash) error { + + return c.node.WaitInvoiceAccepted(ctx, hash) +} + +// AcceptedInvoiceDeadline derives the public dispatch ceiling from the +// accepted native HTLC, not an invoice preference or a bridge replay row. +func (c *NativeArkChannelController) AcceptedInvoiceDeadline( + ctx context.Context, id arkchannel.ID, hash lntypes.Hash, + amount btcutil.Amount) (uint32, error) { + + c.mu.RLock() + service, node := c.service, c.node + c.mu.RUnlock() + if service == nil || node == nil { + return 0, fmt.Errorf("native channel endpoint is not ready") + } + record, err := service.GetChannel(ctx, id) + if err != nil { + return 0, err + } + + return node.AcceptedInvoiceDeadline(ctx, record, hash, amount) +} + +// WaitInvoiceSettled waits for an incoming private destination to settle. +func (c *NativeArkChannelController) WaitInvoiceSettled(ctx context.Context, + hash lntypes.Hash) error { + + return c.node.WaitInvoiceSettled(ctx, hash) +} + +// SettleHoldInvoice releases a private hold invoice with its shared preimage. +func (c *NativeArkChannelController) SettleHoldInvoice(ctx context.Context, + preimage lntypes.Preimage) error { + + return c.node.SettleHoldInvoice(ctx, preimage) +} + +// CancelInvoice fails a private hold invoice before its preimage is released. +func (c *NativeArkChannelController) CancelInvoice(ctx context.Context, + hash lntypes.Hash) error { + + return c.node.CancelInvoice(ctx, hash) +} + +// LookupChannelPayment reads the durable result without starting the endpoint +// or requiring the original channel to still have an active link. +func (c *NativeArkChannelController) LookupChannelPayment(ctx context.Context, + id arkchannel.ID, hash lntypes.Hash, amount btcutil.Amount) ( + lntypes.Preimage, bool, error) { + + c.mu.RLock() + service, node := c.service, c.node + c.mu.RUnlock() + if service == nil || node == nil { + return lntypes.Preimage{}, false, fmt.Errorf("native channel " + + "endpoint is not ready") + } + record, err := service.GetChannel(ctx, id) + if err != nil { + return lntypes.Preimage{}, false, err + } + + return node.LookupChannelPayment(ctx, record, hash, amount) +} + +// PayHash sends or resumes one same-hash payment over a selected private +// channel and returns the destination preimage. A new attempt must expire no +// later than maxExpiryHeight. +func (c *NativeArkChannelController) PayHash(ctx context.Context, + id arkchannel.ID, hash lntypes.Hash, amount btcutil.Amount, + maxExpiryHeight uint32) (lntypes.Preimage, error) { + + if c.party == arkchannel.PartyClient { + if err := c.ensureClientStarted(ctx); err != nil { + return lntypes.Preimage{}, err + } + } + record, err := c.service.GetChannel(ctx, id) + if err != nil { + return lntypes.Preimage{}, err + } + + return c.node.PayInvoiceResultBefore( + ctx, record, hash, amount, maxExpiryHeight, + ) +} + +// PeerMessageHandler dispatches authenticated BOLT messages into native lnd. +// +//nolint:ll // The concrete method name and interface type are both significant. +func (c *NativeArkChannelController) PeerMessageHandler() lnruntime.PeerEventHandler { + return func(ctx context.Context, message lnwire.Message) error { + if c.party == arkchannel.PartyClient { + if err := c.ensureClientStarted(ctx); err != nil { + return fmt.Errorf("start native Ark channel "+ + "endpoint: %w", err) + } + } + log := c.cfg.Log + if log == nil { + log = btclog.Disabled + } + log.DebugS(ctx, "Dispatching native Ark channel peer message", + btclog.Fmt("party", "%s", c.party), + btclog.Fmt("message_type", "%s", message.MsgType()), + ) + c.mu.RLock() + node := c.node + c.mu.RUnlock() + if node == nil { + return fmt.Errorf("native Ark channel endpoint is " + + "not ready") + } + + return node.PeerMessageHandler()(ctx, message) + } +} + +// FundingPeerService returns the generated funding protocol for a hub +// controller bound to its authenticated client. +func (c *NativeArkChannelController) FundingPeerService(remoteNode [33]byte) ( + arkchannelrpc.ArkChannelFundingPeerServiceMailboxServer, error) { + + c.mu.RLock() + defer c.mu.RUnlock() + if c.party != arkchannel.PartyHub || c.node == nil || c.service == nil { + return nil, fmt.Errorf("hub Ark channel endpoint is not ready") + } + + return lnruntime.NewFundingPeerRPCServer( + lnruntime.FundingPeerRPCServerConfig{ + RemoteNode: remoteNode, Info: c.peerInfo, + Service: c.service, Funding: c.node.FundingEndpoint(), + Node: c.node, Recovery: c.cfg.Recovery, + Bridge: c.paymentBridge, + }, + ) +} + +// CooperativeClosePeerService returns the generated close protocol for a hub +// controller bound to its authenticated client. +func (c *NativeArkChannelController) CooperativeClosePeerService( + remoteNode [33]byte) (arkchannelrpc.ArkChannelPeerServiceMailboxServer, + error) { + + c.mu.RLock() + defer c.mu.RUnlock() + if c.party != arkchannel.PartyHub || c.hubClose == nil { + return nil, fmt.Errorf("hub cooperative close endpoint is " + + "not ready") + } + + return lnruntime.NewCooperativeClosePeerRPCServer( + remoteNode, c.hubClose, + ) +} + +// Quiesce cancels and joins controller workers without releasing the native +// node, Ark service, recovery controller, or stores. Shared-engine shutdown +// must retain these objects until lnd has finished its lifecycle callbacks. +func (c *NativeArkChannelController) Quiesce() { + c.mu.Lock() + c.stopped = true + cancel := c.lifecycleCancel + c.mu.Unlock() + if cancel != nil { + cancel() + } + c.lifecycleWG.Wait() +} + +// Retire joins all native callbacks before releasing a terminal hub session. +// Do not retire on transport loss: a disconnected peer can still own funds. +func (c *NativeArkChannelController) Retire() error { + c.Quiesce() + c.mu.RLock() + node := c.node + c.mu.RUnlock() + var err error + if node != nil { + err = node.Retire() + } + + return errors.Join(err, c.Stop()) +} + +// Stop releases native lnd state before the owning wallet and database stop. +func (c *NativeArkChannelController) Stop() error { + c.stopOnce.Do(func() { + c.Quiesce() + + c.mu.Lock() + node := c.node + c.mu.Unlock() + + if node != nil { + c.stopErr = node.Stop() + } + // Standalone clients also invoke auxiliary callbacks while + // stopping their native engine. Release its references only + // after that engine has joined. + c.mu.Lock() + c.node = nil + c.service = nil + c.clientClose = nil + c.hubClose = nil + c.mu.Unlock() + if c.cfg.Recovery != nil { + c.cfg.Recovery.Stop() + } + }) + + return c.stopErr +} + +// arkChannelRefreshDelivery returns the ordinary Ark account key that owns +// this endpoint's replacement VTXO after an in-Ark refresh. +type arkChannelRefreshDelivery struct { + owner *btcec.PublicKey + minimum btcutil.Amount + maximum btcutil.Amount + policySource func() *types.OperatorTerms + coordinator *arkchannel.Coordinator + registerPolicy func(context.Context) (*types.OperatorTerms, error) +} + +// refreshDelivery binds payout limits without making current client policy a +// prerequisite for restoring unilateral recovery. +func (c *NativeArkChannelController) refreshDelivery() ( + *arkChannelRefreshDelivery, error) { + + terms := c.cfg.OperatorTerms + d := &arkChannelRefreshDelivery{ + owner: c.cfg.OORDestination, + policySource: c.cfg.OperatorTermsSource, + coordinator: c.coordinator, + registerPolicy: c.cfg.RegisterRefreshPolicy, + } + if terms == nil && d.policySource == nil { + return nil, fmt.Errorf("refresh operator policy is unavailable") + } + if terms != nil { + d.minimum = terms.MinVTXOAmountFloor() + d.maximum = terms.MaxVTXOAmount + } + + return d, nil +} + +// ValidateCooperativeCloseOutputs rejects known operator-policy failures before +// either endpoint releases an irreversible authorization. +func (d *arkChannelRefreshDelivery) ValidateCooperativeCloseOutputs( + proposal arkchannel.CooperativeCloseProposal) error { + + minimum, maximum := d.minimum, d.maximum + if d.policySource != nil { + terms := d.policySource() + if terms == nil { + return fmt.Errorf("refresh operator policy is " + + "unavailable") + } + minimum = terms.MinVTXOAmountFloor() + maximum = terms.MaxVTXOAmount + } + for _, amount := range []btcutil.Amount{ + proposal.ClientOutput, proposal.HubOutput, + } { + if amount == 0 { + continue + } + if amount < minimum || (maximum > 0 && amount > maximum) { + return fmt.Errorf("refresh payout %d outside limits", + amount) + } + } + + return nil +} + +// CooperativeCloseDelivery fixes the policy that the local wallet actually +// registered. Keep the original owner-only encoding while policies match. +func (d *arkChannelRefreshDelivery) CooperativeCloseDelivery( + ctx context.Context, id arkchannel.ID) ([]byte, error) { + + if d == nil || d.owner == nil { + return nil, fmt.Errorf("channel refresh OOR owner is required") + } + + if d.registerPolicy == nil || d.coordinator == nil { + return nil, fmt.Errorf("refresh registration is unavailable") + } + record, err := d.coordinator.Get(ctx, id) + if err != nil { + return nil, err + } + current, err := d.registerPolicy(ctx) + if err != nil { + return nil, err + } + if current == nil || current.PubKey == nil || + current.VTXOExitDelay == 0 { + return nil, fmt.Errorf("registered refresh policy is " + + "incomplete") + } + source := record.Snapshot.Terms.VTXO + if bytes.Equal( + source.ArkOperatorKey[:], current.PubKey.SerializeCompressed(), + ) && + source.MinExitDelay == current.VTXOExitDelay { + return d.owner.SerializeCompressed(), nil + } + + return arkscript.EncodeStandardVTXOTemplate( + d.owner, current.PubKey, current.VTXOExitDelay, + ) +} + +// ValidateCooperativeCloseDelivery proves the replacement VTXO is assigned to +// this endpoint's ordinary Ark account. +func (d *arkChannelRefreshDelivery) ValidateCooperativeCloseDelivery( + _ context.Context, _ arkchannel.ID, delivery []byte) error { + + owner, err := arkchannel.CooperativeCloseDeliveryOwner(delivery) + if err != nil { + return err + } + if d == nil || d.owner == nil || !sameXOnlyPubKey(d.owner, owner) { + return fmt.Errorf("channel refresh owner is not the " + + "configured Ark account") + } + + return nil +} + +//nolint:ll // Keep the complete delivery contract explicit for API audits. +var ( + _ ArkChannelController = (*NativeArkChannelController)(nil) + _ lnruntime.CooperativeCloseDeliverySource = (*arkChannelRefreshDelivery)(nil) + _ lnruntime.CooperativeCloseDeliveryValidator = (*arkChannelRefreshDelivery)(nil) +) diff --git a/waved/native_ark_channel_controller_test.go b/waved/native_ark_channel_controller_test.go new file mode 100644 index 000000000..7daebfba2 --- /dev/null +++ b/waved/native_ark_channel_controller_test.go @@ -0,0 +1,611 @@ +package waved + +import ( + "context" + "errors" + "fmt" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/arkchannel/oorbridge" + "github.com/lightninglabs/wavelength/lnruntime" + "github.com/lightningnetwork/lnd/lntypes" + "github.com/lightningnetwork/lnd/lnwire" + "github.com/stretchr/testify/require" +) + +type recordingArkChannelBackingRestorer struct { + restored []arkchannel.ID + failID arkchannel.ID +} + +type recordingArkChannelForceCloseResumer struct { + failPoint wire.OutPoint + resumed []wire.OutPoint +} + +type recordingProcessPaymentPeer struct { + lnruntime.ProcessPaymentPeer + + cancelContextErr error + cancelHash lntypes.Hash + cancelReason string + cancelErr error +} + +type noOpPromotionActionExecutor struct{} + +// Execute accepts action-free requested-state replay in this test. +func (noOpPromotionActionExecutor) Execute(context.Context, arkchannel.ID, + arkchannel.Action) error { + + return nil +} + +// CancelOutgoingPayment records the cleanup context and requested failure. +func (p *recordingProcessPaymentPeer) CancelOutgoingPayment(ctx context.Context, + hash lntypes.Hash, reason string) error { + + p.cancelContextErr = ctx.Err() + p.cancelHash = hash + p.cancelReason = reason + + return p.cancelErr +} + +// ResumeForceCloseChannel records each independent on-chain reconciliation. +func (r *recordingArkChannelForceCloseResumer) ResumeForceCloseChannel( + channelPoint wire.OutPoint) error { + + r.resumed = append(r.resumed, channelPoint) + if channelPoint == r.failPoint { + return fmt.Errorf("injected force-close resume failure") + } + + return nil +} + +// RestoreBacking records each durable backing passed to native lnd startup. +func (r *recordingArkChannelBackingRestorer) RestoreBacking( + terms arkchannel.Terms, _ arkchannel.Backing) error { + + r.restored = append(r.restored, terms.ID) + if terms.ID == r.failID { + return fmt.Errorf("injected backing restore failure") + } + + return nil +} + +// TestShouldWatchArkChannel verifies restart admission follows durable channel +// ownership instead of admitting every channel in lnd's database. +func TestShouldWatchArkChannel(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + phase arkchannel.Phase + watch bool + }{ + { + name: "requested", + phase: arkchannel.PhaseRequested, + }, + { + name: "negotiating", + phase: arkchannel.PhaseNegotiating, + }, + { + name: "backing ready", + phase: arkchannel.PhaseBackingReady, + }, + { + name: "activating", + phase: arkchannel.PhaseActivating, + watch: true, + }, + { + name: "active", + phase: arkchannel.PhaseActive, + watch: true, + }, + { + name: "materializing", + phase: arkchannel.PhaseMaterializing, + watch: true, + }, + { + name: "on chain", + phase: arkchannel.PhaseOnChain, + watch: true, + }, + { + name: "closed", + phase: arkchannel.PhaseClosed, + }, + { + name: "cancelling", + phase: arkchannel.PhaseCancelling, + }, + { + name: "failed", + phase: arkchannel.PhaseFailed, + }, + { + name: "coop closing", + phase: arkchannel.PhaseCoopClosing, + watch: true, + }, + { + name: "coop close signed", + phase: arkchannel.PhaseCoopCloseSigned, + watch: true, + }, + { + name: "coop close published", + phase: arkchannel.PhaseCoopClosePublished, + watch: true, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + actual := shouldWatchArkChannel(test.phase) + require.Equal(t, test.watch, actual) + }) + } +} + +// TestRestoreArkChannelCloseHold separates ordinary on-chain links from a +// backing that still competes with an outstanding payout authorization. +func TestRestoreArkChannelCloseHold(t *testing.T) { + t.Parallel() + + quiesced := []arkchannel.Phase{ + arkchannel.PhaseCoopClosing, + arkchannel.PhaseCoopCloseSigned, + arkchannel.PhaseCoopClosePublished, + } + for phase := arkchannel.PhaseRequested; phase <= + arkchannel.PhaseCoopClosePublished; phase++ { + + expected := false + for _, closePhase := range quiesced { + if phase == closePhase { + expected = true + break + } + } + s := arkchannel.Snapshot{Phase: phase} + require.Equal(t, expected, shouldHoldArkChannelClose(s), phase) + s.CooperativeClose = &arkchannel.CooperativeClose{} + require.True(t, shouldHoldArkChannelClose(s), phase) + } +} + +// TestRestoreNativeArkChannelBackingRecords verifies every live signed backing +// is registered before lnd startup while unsigned and archived channels are +// skipped. +func TestRestoreNativeArkChannelBackingRecords(t *testing.T) { + t.Parallel() + + firstID := arkchannel.ID{1} + secondID := arkchannel.ID{2} + thirdID := arkchannel.ID{3} + closedID := arkchannel.ID{4} + restorer := &recordingArkChannelBackingRestorer{} + records := []arkchannel.Record{ + { + Snapshot: arkchannel.Snapshot{ + Terms: arkchannel.Terms{ + ID: firstID, + }, + Backing: &arkchannel.Backing{ + Transaction: []byte{ + 1, + }, + }, + }, + }, + { + Snapshot: arkchannel.Snapshot{ + Terms: arkchannel.Terms{ + ID: arkchannel.ID{ + 9, + }, + }, + }, + }, + { + Snapshot: arkchannel.Snapshot{ + Terms: arkchannel.Terms{ + ID: secondID, + }, + Backing: &arkchannel.Backing{ + Transaction: []byte{ + 2, + }, + }, + }, + }, + { + Snapshot: arkchannel.Snapshot{ + Terms: arkchannel.Terms{ + ID: thirdID, + }, + Backing: &arkchannel.Backing{ + Transaction: []byte{ + 3, + }, + }, + }, + }, + { + Snapshot: arkchannel.Snapshot{ + Terms: arkchannel.Terms{ + ID: closedID, + }, + Phase: arkchannel.PhaseClosed, + Backing: &arkchannel.Backing{ + Transaction: []byte{ + 4, + }, + }, + }, + }, + } + require.NoError( + t, restoreNativeArkChannelBackingRecords( + restorer, records, + ), + ) + require.Equal( + t, []arkchannel.ID{firstID, secondID, thirdID}, + restorer.restored, + ) + + restorer = &recordingArkChannelBackingRestorer{failID: secondID} + err := restoreNativeArkChannelBackingRecords(restorer, records) + var failures *arkchannel.ResumeFailures + require.ErrorAs(t, err, &failures) + require.Len(t, failures.Failures, 1) + require.Equal(t, secondID, failures.Failures[0].ChannelID) + require.ErrorContains( + t, failures.Failures[0].Err, "injected backing restore failure", + ) + require.Equal( + t, []arkchannel.ID{firstID, secondID, thirdID}, + restorer.restored, + ) +} + +// TestResumeOnchainArkChannelRecordsIsolatesFailures verifies one broken lnd +// close record does not suppress reconciliation for another channel. +func TestResumeOnchainArkChannelRecordsIsolatesFailures(t *testing.T) { + t.Parallel() + + firstPoint := wire.OutPoint{Index: 1} + secondPoint := wire.OutPoint{Index: 2} + resumer := &recordingArkChannelForceCloseResumer{ + failPoint: firstPoint, + } + records := []arkchannel.Record{ + { + Snapshot: arkchannel.Snapshot{ + Terms: arkchannel.Terms{ + ID: arkchannel.ID{ + 1, + }, + }, + Phase: arkchannel.PhaseOnChain, + Backing: &arkchannel.Backing{ + ChannelPoint: firstPoint, + }, + }, + }, + { + Snapshot: arkchannel.Snapshot{ + Terms: arkchannel.Terms{ + ID: arkchannel.ID{ + 9, + }, + }, + Phase: arkchannel.PhaseActive, + }, + }, + { + Snapshot: arkchannel.Snapshot{ + Terms: arkchannel.Terms{ + ID: arkchannel.ID{ + 2, + }, + }, + Phase: arkchannel.PhaseOnChain, + Backing: &arkchannel.Backing{ + ChannelPoint: secondPoint, + }, + }, + }, + } + err := resumeOnchainArkChannelRecords(resumer, records) + var failures *arkchannel.ResumeFailures + require.ErrorAs(t, err, &failures) + require.Len(t, failures.Failures, 1) + require.Equal(t, arkchannel.ID{1}, failures.Failures[0].ChannelID) + require.Equal( + t, []wire.OutPoint{firstPoint, secondPoint}, resumer.resumed, + ) +} + +// TestShouldResumeOnchainArkChannel verifies either recovery-ready endpoint +// re-drives lnd commitment publication after backing materialization. +func TestShouldResumeOnchainArkChannel(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + phase arkchannel.Phase + expected bool + }{ + { + name: "on-chain channel resumes commitment", + phase: arkchannel.PhaseOnChain, expected: true, + }, + { + name: "active source has nothing to resume", + phase: arkchannel.PhaseActive, + }, + { + name: "closed source has nothing to resume", + phase: arkchannel.PhaseClosed, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + snapshot := arkchannel.Snapshot{Phase: test.phase} + require.Equal( + t, test.expected, + shouldResumeOnchainArkChannel(snapshot), + ) + }) + } +} + +// TestCancelOutgoingPaymentDetachesFromRequest proves every successful +// preparation gets a cleanup attempt even after its request is canceled. +func TestCancelOutgoingPaymentDetachesFromRequest(t *testing.T) { + t.Parallel() + + requestCtx, cancel := context.WithCancel(t.Context()) + cancel() + cause := errors.New("private payment failed") + hash := lntypes.Hash{1, 2, 3} + peer := &recordingProcessPaymentPeer{} + controller := &NativeArkChannelController{paymentPeer: peer} + + err := controller.cancelOutgoingPayment(requestCtx, hash, cause) + require.ErrorIs(t, err, cause) + require.NoError(t, peer.cancelContextErr) + require.Equal(t, hash, peer.cancelHash) + require.Equal(t, cause.Error(), peer.cancelReason) + + peer.cancelErr = errors.New("cleanup failed") + err = controller.cancelOutgoingPayment(requestCtx, hash, cause) + require.ErrorIs(t, err, cause) + require.ErrorIs(t, err, peer.cancelErr) +} + +// TestEnsureClientStartedSharesProcessAttempt proves one canceled request does +// not cancel startup that another caller is waiting on. +func TestEnsureClientStartedSharesProcessAttempt(t *testing.T) { + t.Parallel() + + startupErr := errors.New("startup failed") + started := make(chan struct{}) + release := make(chan struct{}) + var starts atomic.Int32 + controller := &NativeArkChannelController{ + clientStarter: func(ctx context.Context) error { + if starts.Add(1) == 1 { + close(started) + } + + select { + case <-release: + return startupErr + + case <-ctx.Done(): + return ctx.Err() + } + }, + } + controller.initLifecycle(t.Context()) + t.Cleanup(func() { + require.NoError(t, controller.Stop()) + }) + + requestCtx, cancel := context.WithCancel(t.Context()) + firstResult := make(chan error, 1) + go func() { + firstResult <- controller.ensureClientStarted(requestCtx) + }() + <-started + cancel() + require.ErrorIs(t, <-firstResult, context.Canceled) + + secondResult := make(chan error, 1) + go func() { + secondResult <- controller.ensureClientStarted(t.Context()) + }() + require.Never(t, func() bool { + return starts.Load() != 1 + }, 25*time.Millisecond, time.Millisecond) + close(release) + require.ErrorIs(t, <-secondResult, startupErr) + require.Equal(t, int32(1), starts.Load()) +} + +// TestArkChannelControllerStopCancelsStartup verifies concurrent shutdown is +// idempotent and waits for a process-owned startup attempt to exit. +func TestArkChannelControllerStopCancelsStartup(t *testing.T) { + t.Parallel() + + started := make(chan struct{}) + controller := &NativeArkChannelController{ + clientStarter: func(ctx context.Context) error { + close(started) + <-ctx.Done() + + return ctx.Err() + }, + } + controller.initLifecycle(t.Context()) + startResult := make(chan error, 1) + go func() { + startResult <- controller.ensureClientStarted(t.Context()) + }() + <-started + + var shutdown sync.WaitGroup + shutdown.Add(2) + errs := make(chan error, 2) + for range 2 { + go func() { + defer shutdown.Done() + + errs <- controller.Stop() + }() + } + shutdown.Wait() + close(errs) + for err := range errs { + require.NoError(t, err) + } + require.ErrorIs(t, <-startResult, context.Canceled) +} + +// TestArkChannelControllerStartsForExistingState proves startup recovery does +// not wait for a new RPC when the durable store already owns a channel. +func TestArkChannelControllerStartsForExistingState(t *testing.T) { + t.Parallel() + + now := time.Unix(30_000, 0).UTC() + controller, coordinator, terms, closeStore := testPrePONRController( + t, now, oorbridge.PreparationLookup{ + Status: oorbridge.PreparationAbsent, + }, + ) + t.Cleanup(closeStore) + _, err := coordinator.Request(t.Context(), terms) + require.NoError(t, err) + controller.party = arkchannel.PartyClient + controller.initLifecycle(t.Context()) + started := make(chan struct{}) + controller.clientStarter = func(ctx context.Context) error { + close(started) + <-ctx.Done() + + return ctx.Err() + } + controller.Start() + + select { + case <-started: + case <-time.After(time.Second): + t.Fatal("existing Ark channel did not trigger client startup") + } + require.NoError(t, controller.Stop()) +} + +// TestPromotionIdentifiersAreStableAndScoped verifies a retried creation gets +// the same protocol identity without colliding across daemon identities. +func TestPromotionIdentifiersAreStableAndScoped(t *testing.T) { + t.Parallel() + + first := &NativeArkChannelController{cfg: ArkChannelControllerConfig{ + IdentityKey: testKeyDescriptor(t, 70), + }} + second := &NativeArkChannelController{cfg: ArkChannelControllerConfig{ + IdentityKey: testKeyDescriptor(t, 71), + }} + + firstID, firstPending, firstSCID := + first.promotionIdentifiers("invoice-42") + retryID, retryPending, retrySCID := + first.promotionIdentifiers("invoice-42") + require.Equal(t, firstID, retryID) + require.Equal(t, firstPending, retryPending) + require.Equal(t, firstSCID, retrySCID) + reservedSCID := lnwire.NewShortChanIDFromInt(firstSCID) + require.NotZero(t, reservedSCID.BlockHeight) + require.Zero(t, reservedSCID.TxPosition) + + otherKeyID, _, _ := first.promotionIdentifiers("invoice-43") + otherIdentityID, _, _ := second.promotionIdentifiers("invoice-42") + require.NotEqual(t, firstID, otherKeyID) + require.NotEqual(t, firstID, otherIdentityID) +} + +// TestNewPromotionTermsRequiresIdempotencyKey verifies the controller cannot +// reintroduce an unrecoverable random channel identity below the RPC layer. +func TestNewPromotionTermsRequiresIdempotencyKey(t *testing.T) { + t.Parallel() + + controller := &NativeArkChannelController{} + _, _, err := controller.newPromotionTerms(t.Context(), 100_000, "") + require.ErrorContains(t, err, "idempotency key is required") +} + +// TestResumeBoundPromotionReturnsActiveRecord verifies an RPC replay does not +// re-enter the prepared-OOR admission path after channel activation. +func TestResumeBoundPromotionReturnsActiveRecord(t *testing.T) { + t.Parallel() + + record := arkchannel.Record{Snapshot: arkchannel.Snapshot{ + Terms: arkchannel.Terms{ + ID: arkchannel.ID{ + 1, + }, + }, + Phase: arkchannel.PhaseActive, + }} + controller := &NativeArkChannelController{} + + actual, err := controller.resumeBoundPromotion(t.Context(), record) + require.NoError(t, err) + require.Equal(t, record, actual) +} + +// TestWaitPromotionCompletionBlocksTransitionalRecord verifies idempotent RPC +// replay cannot report successful creation while the durable FSM is pending. +func TestWaitPromotionCompletionBlocksTransitionalRecord(t *testing.T) { + t.Parallel() + + now := time.Unix(41_000, 0).UTC() + controller, coordinator, terms, closeStore := testPrePONRController( + t, now, oorbridge.PreparationLookup{}, + ) + t.Cleanup(closeStore) + _, err := coordinator.Request(t.Context(), terms) + require.NoError(t, err) + + service, err := arkchannel.NewService( + controller.party, coordinator, noOpPromotionActionExecutor{}, + ) + require.NoError(t, err) + controller.service = service + + ctx, cancel := context.WithCancel(t.Context()) + cancel() + _, err = controller.waitPromotionCompletion(ctx, terms.ID) + require.ErrorIs(t, err, context.Canceled) +} diff --git a/waved/native_ark_channel_refresh_policy_test.go b/waved/native_ark_channel_refresh_policy_test.go new file mode 100644 index 000000000..6b6a6c86e --- /dev/null +++ b/waved/native_ark_channel_refresh_policy_test.go @@ -0,0 +1,158 @@ +package waved + +import ( + "context" + "errors" + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/lib/arkscript" + "github.com/lightninglabs/wavelength/lib/types" + "github.com/stretchr/testify/require" +) + +// TestRefreshPayoutPolicy checks operator limits before either endpoint's +// authorization can make an otherwise unspendable payout irreversible. +func TestRefreshPayoutPolicy(t *testing.T) { + t.Parallel() + delivery := &arkChannelRefreshDelivery{minimum: 330, maximum: 100_000} + for _, test := range []struct { + name string + client, hub btcutil.Amount + valid bool + }{ + { + name: "both", + client: 330, + hub: 100_000, + valid: true, + }, + { + name: "one output", + client: 100_000, + valid: true, + }, + { + name: "client dust", + client: 329, + hub: 1_000, + }, + { + name: "hub dust", + client: 1_000, + hub: 1, + }, + { + name: "over cap", + client: 100_001, + }, + } { + t.Run(test.name, func(t *testing.T) { + err := delivery.ValidateCooperativeCloseOutputs( + arkchannel.CooperativeCloseProposal{ + ClientOutput: test.client, + HubOutput: test.hub, + }, + ) + if test.valid { + require.NoError(t, err) + + return + } + require.ErrorContains(t, err, "outside limits") + }) + } +} + +// TestRefreshDeliveryRegistersRotatedPolicy checks new quotes against the +// registered policy and signed replay against the immutable owner alone. +func TestRefreshDeliveryRegistersRotatedPolicy(t *testing.T) { + t.Parallel() + raw, coordinator := testArkChannelResumeStore(t, t.TempDir()) + t.Cleanup(func() { require.NoError(t, raw.Close()) }) + terms := testPrePONRTerms(t) + _, err := coordinator.Request(t.Context(), terms) + require.NoError(t, err) + source, err := btcec.ParsePubKey(terms.VTXO.ArkOperatorKey[:]) + require.NoError(t, err) + current := &types.OperatorTerms{ + PubKey: source, VTXOExitDelay: terms.VTXO.MinExitDelay, + } + owner := testKeyDescriptor(t, 7).PubKey + var registrationErr error + // Use the same static opening terms and live registration hook that + // SwapDK supplies to each native hub endpoint. + controller := &NativeArkChannelController{ + coordinator: coordinator, + cfg: ArkChannelControllerConfig{ + OORDestination: owner, + OperatorTerms: &types.OperatorTerms{ + PubKey: source, + VTXOExitDelay: current.VTXOExitDelay, + }, + RegisterRefreshPolicy: func(context.Context) ( + *types.OperatorTerms, error) { + + return current, registrationErr + }, + }, + } + d, err := controller.refreshDelivery() + require.NoError(t, err) + original, err := d.CooperativeCloseDelivery(t.Context(), terms.ID) + require.NoError(t, err) + require.Equal(t, owner.SerializeCompressed(), original) + current.PubKey = testKeyDescriptor(t, 8).PubKey + quoted, err := d.CooperativeCloseDelivery(t.Context(), terms.ID) + require.NoError(t, err) + want, err := arkscript.EncodeStandardVTXOTemplate( + owner, current.PubKey, current.VTXOExitDelay, + ) + require.NoError(t, err) + require.Equal(t, want, quoted) + registrationErr = errors.New("registration unavailable") + _, err = d.CooperativeCloseDelivery(t.Context(), terms.ID) + require.ErrorIs(t, err, registrationErr) + for _, encoded := range [][]byte{original, quoted} { + require.NoError( + t, + d.ValidateCooperativeCloseDelivery( + t.Context(), terms.ID, encoded, + ), + ) + } +} + +// TestRefreshDeliveryUsesClientPolicySource covers clients without the static +// hub-only snapshot, including startup before operator negotiation completes. +func TestRefreshDeliveryUsesClientPolicySource(t *testing.T) { + t.Parallel() + var policy *types.OperatorTerms + controller := &NativeArkChannelController{ + cfg: ArkChannelControllerConfig{ + OperatorTermsSource: func() *types.OperatorTerms { + return policy + }, + }, + } + delivery, err := controller.refreshDelivery() + require.NoError(t, err) + proposal := arkchannel.CooperativeCloseProposal{ClientOutput: 100_000} + require.ErrorContains( + t, delivery.ValidateCooperativeCloseOutputs( + proposal, + ), + "policy is unavailable", + ) + policy = &types.OperatorTerms{MaxVTXOAmount: 100_000} + require.NoError(t, delivery.ValidateCooperativeCloseOutputs(proposal)) + policy = &types.OperatorTerms{MaxVTXOAmount: 99_999} + require.ErrorContains( + t, delivery.ValidateCooperativeCloseOutputs( + proposal, + ), + "outside limits", + ) +} diff --git a/waved/native_ark_channel_resume.go b/waved/native_ark_channel_resume.go new file mode 100644 index 000000000..01b871663 --- /dev/null +++ b/waved/native_ark_channel_resume.go @@ -0,0 +1,107 @@ +package waved + +import ( + "context" + "fmt" + + "github.com/btcsuite/btclog/v2" + "github.com/lightninglabs/wavelength/arkchannel" +) + +// nativeArkChannelResumeIDs validates the complete inventory synchronously. +// Replay must reload records in owned workers because a recovery watch can +// make even an initially active channel require future-block materialization. +func nativeArkChannelResumeIDs(ctx context.Context, + service *arkchannel.Service) ([]arkchannel.ID, error) { + + records, err := service.ListChannels(ctx) + if err != nil { + return nil, err + } + ids := make([]arkchannel.ID, 0, len(records)) + for _, record := range records { + _, err := arkchannel.PendingAction(record.Snapshot) + if err != nil { + return nil, fmt.Errorf("validate channel recovery "+ + "%x: %w", record.Snapshot.Terms.ID[:4], err) + } + ids = append(ids, record.Snapshot.Terms.ID) + } + + return ids, nil +} + +// startNativeArkChannelResume isolates durable replay in the existing +// controller lifecycle. One channel waiting for blocks cannot hold up startup +// or another channel; Stop cancels and joins these workers before lnd closes. +func (c *NativeArkChannelController) startNativeArkChannelResume( + service *arkchannel.Service, node arkChannelForceCloseResumer, + ids []arkchannel.ID) { + + for _, id := range ids { + c.startLifecycleWorker(func(ctx context.Context) { + c.resumeNativeArkChannel(ctx, service, node, id) + }) + } +} + +// resumeNativeArkChannel retries the action from fresh durable state instead +// of retaining a stale action or treating an operational failure as terminal. +func (c *NativeArkChannelController) resumeNativeArkChannel(ctx context.Context, + service *arkchannel.Service, node arkChannelForceCloseResumer, + id arkchannel.ID) { + + for ctx.Err() == nil { + record, err := c.resumeChannelAction(ctx, service, id) + if err == nil && + shouldResumeOnchainArkChannel(record.Snapshot) { + + err = resumeOnchainArkChannelRecords( + node, []arkchannel.Record{record}, + ) + } + if err == nil || ctx.Err() != nil { + return + } + if c.cfg.Log != nil { + c.cfg.Log.DebugS( + ctx, + "Ark channel recovery deferred; retrying", + btclog.Hex("channel_id", id[:]), + btclog.Fmt("error", "%v", err), + ) + } + + select { + case <-ctx.Done(): + return + + case <-c.cfg.Clock.TickAfter( + defaultArkChannelClientRetryInterval, + ): + } + } +} + +// resumeChannelAction reconciles a client's preparation before replay. A peer +// RPC here may wait, so this belongs to the individual channel worker, not +// the startup path that arms every channel's expiry guard. +func (c *NativeArkChannelController) resumeChannelAction(ctx context.Context, + service *arkchannel.Service, id arkchannel.ID) (arkchannel.Record, + error) { + + if c.party == arkchannel.PartyClient { + record, err := service.GetChannel(ctx, id) + if err != nil { + return arkchannel.Record{}, err + } + err = c.maintainPrePONRChannel( + ctx, service, record, c.cfg.Clock.Now(), + ) + if err != nil { + return arkchannel.Record{}, err + } + } + + return service.ResumeChannelAction(ctx, id) +} diff --git a/waved/native_ark_channel_resume_test.go b/waved/native_ark_channel_resume_test.go new file mode 100644 index 000000000..8c5978587 --- /dev/null +++ b/waved/native_ark_channel_resume_test.go @@ -0,0 +1,517 @@ +package waved + +import ( + "context" + "errors" + "fmt" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/btcsuite/btcd/btcec/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/db" + "github.com/lightningnetwork/lnd/clock" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/keychain" + "github.com/stretchr/testify/require" +) + +type arkChannelResumeExecutor func(context.Context, arkchannel.ID, + arkchannel.Action) error + +// Execute routes durable actions into a controlled materializer. +func (e arkChannelResumeExecutor) Execute(ctx context.Context, id arkchannel.ID, + action arkchannel.Action) error { + + return e(ctx, id, action) +} + +type arkChannelResumeForceCloser chan wire.OutPoint + +// ResumeForceCloseChannel records the post-materialization native handoff. +func (c arkChannelResumeForceCloser) ResumeForceCloseChannel( + point wire.OutPoint) error { + + c <- point + + return nil +} + +type arkChannelResumeInventory struct { + arkchannel.Store + records []arkchannel.Record + err error +} + +// ListNonTerminal injects enumeration and validation failures at bootstrap. +func (s arkChannelResumeInventory) ListNonTerminal(context.Context) ( + []arkchannel.Record, error) { + + return s.records, s.err +} + +// TestNativeArkChannelResumeLeavesMaterializationPending forces the durable +// restart window before any future blocks can complete materialization. +func TestNativeArkChannelResumeLeavesMaterializationPending(t *testing.T) { + t.Parallel() + + raw, coordinator := testArkChannelResumeStore(t, t.TempDir()) + t.Cleanup(func() { require.NoError(t, raw.Close()) }) + initial := testArkChannelResumeRecord(t, coordinator, true) + id := initial.Snapshot.Terms.ID + started := make(chan struct{}) + release := make(chan struct{}) + forced := make(chan struct{}, 1) + var service *arkchannel.Service + executor := arkChannelResumeExecutor(func(ctx context.Context, + _ arkchannel.ID, action arkchannel.Action) error { + + switch action.(type) { + case *arkchannel.PublishChannel: + close(started) + select { + case <-release: + case <-ctx.Done(): + return ctx.Err() + } + _, err := service.ApplyLocalEvent(ctx, id, + &arkchannel.BackingPublished{ + TxID: initial. + Snapshot. + Backing. + ChannelPoint. + Hash, + }, + ) + + return err + + case *arkchannel.ForceCloseChannel: + forced <- struct{}{} + + return nil + + default: + return fmt.Errorf("unexpected recovery action %T", + action) + } + }) + var err error + service, err = arkchannel.NewService( + arkchannel.PartyHub, coordinator, executor, + ) + require.NoError(t, err) + controller := testArkChannelResumeController(t) + resumed := make(arkChannelResumeForceCloser, 1) + controller.clientStarter = func(ctx context.Context) error { + ids, err := nativeArkChannelResumeIDs( + ctx, service, + ) + if err != nil { + return err + } + //nolint:contextcheck // recovery outlives the startup context + controller.startNativeArkChannelResume(service, resumed, ids) + + return nil + } + requestCtx, cancel := context.WithCancel(t.Context()) + defer cancel() + startup := make(chan error, 1) + go func() { + startup <- controller.ensureClientStarted(requestCtx) + }() + select { + case err := <-startup: + require.NoError(t, err) + + case <-time.After(5 * time.Second): + t.Fatal("startup waited for block-dependent materialization") + } + <-started + cancel() + actual, err := coordinator.Get(t.Context(), id) + require.NoError(t, err) + require.Equal(t, initial, actual) + close(release) + select { + case <-forced: + case <-time.After(5 * time.Second): + t.Fatal("materialization did not resume force close") + } + require.Equal(t, initial.Snapshot.Backing.ChannelPoint, <-resumed) + actual, err = coordinator.Get(t.Context(), id) + require.NoError(t, err) + require.Equal(t, arkchannel.PhaseOnChain, actual.Snapshot.Phase) + require.True(t, actual.Snapshot.BackingPublished) +} + +// TestNativeArkChannelResumeStopJoinsAndRestarts proves canceled recovery is +// joined before storage closes and remains replayable from the reopened DB. +func TestNativeArkChannelResumeStopJoinsAndRestarts(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + raw, coordinator := testArkChannelResumeStore(t, dir) + initial := testArkChannelResumeRecord(t, coordinator, true) + started := make(chan struct{}) + canceled := make(chan struct{}) + allowExit := make(chan struct{}) + releaseExit := sync.OnceFunc(func() { close(allowExit) }) + controller := testArkChannelResumeController(t) + t.Cleanup(releaseExit) + service, err := arkchannel.NewService( + arkchannel.PartyHub, coordinator, + arkChannelResumeExecutor(func(ctx context.Context, + _ arkchannel.ID, action arkchannel.Action) error { + + if _, ok := action.(*arkchannel.PublishChannel); !ok { + return fmt.Errorf("unexpected action %T", + action) + } + close(started) + <-ctx.Done() + close(canceled) + <-allowExit + + return ctx.Err() + }), + ) + require.NoError(t, err) + ids, err := nativeArkChannelResumeIDs( + t.Context(), service, + ) + require.NoError(t, err) + controller.startNativeArkChannelResume(service, nil, ids) + <-started + stopped := make(chan error, 1) + go func() { + stopped <- controller.Stop() + }() + <-canceled + select { + case err := <-stopped: + require.NoError(t, err) + t.Fatal("Stop returned before its recovery worker exited") + + default: + } + releaseExit() + require.NoError(t, <-stopped) + actual, err := coordinator.Get(t.Context(), initial.Snapshot.Terms.ID) + require.NoError(t, err) + require.Equal(t, initial, actual) + require.NoError(t, raw.Close()) + + raw, coordinator = testArkChannelResumeStore(t, dir) + t.Cleanup(func() { require.NoError(t, raw.Close()) }) + controller = testArkChannelResumeController(t) + var attempts atomic.Int32 + service, err = arkchannel.NewService( + arkchannel.PartyHub, coordinator, + arkChannelResumeExecutor(func(ctx context.Context, + id arkchannel.ID, action arkchannel.Action) error { + + switch action.(type) { + case *arkchannel.PublishChannel: + if attempts.Add(1) == 1 { + return errors.New("materializer " + + "temporarily unavailable") + } + _, _, err := coordinator.Apply(ctx, id, + &arkchannel.BackingPublished{ + TxID: initial. + Snapshot. + Backing. + ChannelPoint. + Hash, + }, + ) + + return err + + default: + return fmt.Errorf("unexpected action %T", + action) + } + }), + ) + require.NoError(t, err) + ids, err = nativeArkChannelResumeIDs( + t.Context(), service, + ) + require.NoError(t, err) + resumed := make(arkChannelResumeForceCloser, 1) + controller.startNativeArkChannelResume(service, resumed, ids) + select { + case point := <-resumed: + require.Equal(t, initial.Snapshot.Backing.ChannelPoint, point) + + case <-time.After(5 * time.Second): + t.Fatal("durable recovery did not retry after restart") + } + require.Equal(t, int32(2), attempts.Load()) +} + +// TestNativeArkChannelResumeReloadsAfterValidation forces a watch transition +// after validation so a stale active snapshot cannot select synchronous replay. +func TestNativeArkChannelResumeReloadsAfterValidation(t *testing.T) { + t.Parallel() + + raw, coordinator := testArkChannelResumeStore(t, t.TempDir()) + t.Cleanup(func() { require.NoError(t, raw.Close()) }) + initial := testArkChannelResumeRecord(t, coordinator, false) + id := initial.Snapshot.Terms.ID + started := make(chan struct{}) + service, err := arkchannel.NewService( + arkchannel.PartyHub, coordinator, + arkChannelResumeExecutor(func(ctx context.Context, + _ arkchannel.ID, action arkchannel.Action) error { + + if _, ok := action.(*arkchannel.PublishChannel); !ok { + return fmt.Errorf("unexpected action %T", + action) + } + close(started) + <-ctx.Done() + + return ctx.Err() + }), + ) + require.NoError(t, err) + ids, err := nativeArkChannelResumeIDs(t.Context(), service) + require.NoError(t, err) + require.Equal(t, []arkchannel.ID{id}, ids) + // A confirmed recovery watch fires after the active inventory was read. + materializing, _, err := coordinator.Apply(t.Context(), id, + &arkchannel.SourceSpent{ + OutPoint: initial.Snapshot.Source.OutPoint, + SpendingTxID: [32]byte{99}, + }, + ) + require.NoError(t, err) + require.Equal( + t, arkchannel.PhaseMaterializing, materializing.Snapshot.Phase, + ) + controller := testArkChannelResumeController(t) + controller.startNativeArkChannelResume(service, nil, ids) + select { + case <-started: + case <-time.After(5 * time.Second): + t.Fatal( + "recovery did not reload the newly materializing " + + "record", + ) + } + actual, err := coordinator.Get(t.Context(), id) + require.NoError(t, err) + require.Equal(t, materializing, actual) +} + +// TestNativeArkChannelResumeRejectsBootstrapFailures verifies that moving the +// materializer off startup does not defer inventory or record validation. +func TestNativeArkChannelResumeRejectsBootstrapFailures(t *testing.T) { + t.Parallel() + + for _, test := range []struct { + name string + store arkChannelResumeInventory + want string + }{ + { + name: "enumeration", + store: arkChannelResumeInventory{ + err: errors.New("inventory unavailable"), + }, + want: "inventory unavailable", + }, + { + name: "invalid durable record", + store: arkChannelResumeInventory{ + records: []arkchannel.Record{ + {}, + }, + }, + want: "validate channel recovery", + }, + } { + t.Run(test.name, func(t *testing.T) { + coordinator, err := arkchannel.NewCoordinator( + test.store, + ) + require.NoError(t, err) + var executions atomic.Int32 + service, err := arkchannel.NewService( + arkchannel.PartyHub, coordinator, + arkChannelResumeExecutor(func(context.Context, + arkchannel.ID, + arkchannel.Action) error { + + executions.Add(1) + + return nil + }), + ) + require.NoError(t, err) + ids, err := nativeArkChannelResumeIDs( + t.Context(), service, + ) + require.ErrorContains(t, err, test.want) + require.Empty(t, ids) + require.Zero(t, executions.Load()) + }) + } +} + +// testArkChannelResumeController installs the real owned-worker lifecycle. +func testArkChannelResumeController(t *testing.T) *NativeArkChannelController { + t.Helper() + controller := &NativeArkChannelController{ + cfg: withArkChannelControllerDefaults( + ArkChannelControllerConfig{ + Log: btclog.Disabled, + }, + ), + } + controller.initLifecycle(t.Context()) + t.Cleanup(func() { require.NoError(t, controller.Stop()) }) + + return controller +} + +// testArkChannelResumeStore opens the production SQL-backed channel store. +func testArkChannelResumeStore(t *testing.T, + dir string) (*db.Store, *arkchannel.Coordinator) { + + t.Helper() + raw, err := db.NewStoreFromConfig( + db.DefaultConfig(dir), btclog.Disabled, + ) + require.NoError(t, err) + coordinator, err := arkchannel.NewCoordinator( + raw.NewArkChannelStore( + clock.NewDefaultClock(), + ), + ) + require.NoError(t, err) + + return raw, coordinator +} + +// testArkChannelResumeRecord persists a fully signed channel, optionally with +// a confirmed source-conflict trigger, without executing its pending effect. +func testArkChannelResumeRecord(t *testing.T, + coordinator *arkchannel.Coordinator, + materializing bool) arkchannel.Record { + + t.Helper() + terms := testPrePONRTerms(t) + keys := make([]*btcec.PrivateKey, 2) + for i := range keys { + key, err := btcec.NewPrivateKey() + require.NoError(t, err) + keys[i] = key + } + copy( + terms.VTXO.ClientChannelKey[:], + keys[0].PubKey().SerializeCompressed(), + ) + copy( + terms.VTXO.HubChannelKey[:], + keys[1].PubKey().SerializeCompressed(), + ) + + return persistArkChannelResumeRecord( + t, coordinator, terms, keys[0], keys[1], materializing, + ) +} + +// persistArkChannelResumeRecord installs a signed channel for the specified +// wallets so restart tests can use real wallet-derived local keys. +func persistArkChannelResumeRecord(t *testing.T, + coordinator *arkchannel.Coordinator, terms arkchannel.Terms, + clientKey, hubKey *btcec.PrivateKey, + materializing bool) arkchannel.Record { + + t.Helper() + binding := testPrePONRBinding(t, terms) + 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, binding) + require.NoError(t, err) + sign := func(party arkchannel.Party, + key *btcec.PrivateKey) input.Signature { + + 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 + } + backing, err := template.Complete( + terms, binding, sign(arkchannel.PartyClient, clientKey), + sign(arkchannel.PartyHub, hubKey), + ) + require.NoError(t, err) + _, err = coordinator.Request(t.Context(), terms) + require.NoError(t, err) + var record arkchannel.Record + 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, + }, + } { + record, _, err = coordinator.Apply(t.Context(), terms.ID, event) + require.NoError(t, err) + } + require.Equal(t, arkchannel.PhaseActive, record.Snapshot.Phase) + if materializing { + record, _, err = coordinator.Apply( + t.Context(), terms.ID, &arkchannel.SourceSpent{ + OutPoint: binding.OutPoint, + SpendingTxID: [32]byte{99}, + }, + ) + require.NoError(t, err) + require.Equal( + t, arkchannel.PhaseMaterializing, record.Snapshot.Phase, + ) + } + + return record +} diff --git a/waved/native_ark_channel_shutdown_test.go b/waved/native_ark_channel_shutdown_test.go new file mode 100644 index 000000000..6d8978fc6 --- /dev/null +++ b/waved/native_ark_channel_shutdown_test.go @@ -0,0 +1,80 @@ +package waved + +import ( + "context" + "sync/atomic" + "testing" + "time" + + "github.com/lightninglabs/wavelength/arkchannel" + "github.com/lightninglabs/wavelength/lnruntime" + "github.com/stretchr/testify/require" +) + +// quiesceRecovery records an unexpected release of the recovery lifecycle. +type quiesceRecovery struct { + ArkChannelRecoveryController + stopped atomic.Bool +} + +// Stop records terminal teardown, which quiescing must not perform. +func (r *quiesceRecovery) Stop() { + r.stopped.Store(true) +} + +// TestNativeArkChannelQuiesceRetainsLifecycle verifies controller workers are +// joined while every object required by native shutdown remains available. +func TestNativeArkChannelQuiesceRetainsLifecycle(t *testing.T) { + t.Parallel() + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + recovery := &quiesceRecovery{} + node := &lnruntime.NativeNode{} + service := &arkchannel.Service{} + coordinator := &arkchannel.Coordinator{} + controller := &NativeArkChannelController{ + cfg: ArkChannelControllerConfig{ + Recovery: recovery, + }, + node: node, service: service, coordinator: coordinator, + lifecycleCtx: ctx, lifecycleCancel: cancel, + } + canceled := make(chan struct{}) + release := make(chan struct{}) + controller.lifecycleWG.Add(1) + go func() { + defer controller.lifecycleWG.Done() + <-ctx.Done() + close(canceled) + <-release + }() + done := make(chan struct{}) + go func() { + controller.Quiesce() + close(done) + }() + select { + case <-canceled: + case <-time.After(time.Second): + t.Fatal("controller worker was not canceled") + } + select { + case <-done: + t.Fatal("quiesce returned before its worker joined") + + default: + } + close(release) + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("quiesce did not join its worker") + } + require.Same(t, node, controller.node) + require.Same(t, service, controller.service) + require.Same(t, coordinator, controller.coordinator) + require.Same(t, recovery, controller.cfg.Recovery) + require.False(t, recovery.stopped.Load()) + require.True(t, controller.stopped) + controller.Quiesce() +} diff --git a/waved/rpc_ark_channel_recovery.go b/waved/rpc_ark_channel_recovery.go new file mode 100644 index 000000000..11c89ea23 --- /dev/null +++ b/waved/rpc_ark_channel_recovery.go @@ -0,0 +1,60 @@ +package waved + +import ( + "context" + + "github.com/lightninglabs/wavelength/lnruntime" + "github.com/lightninglabs/wavelength/waverpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// ExportOORRecoveryPackage returns the immutable local lineage for one exact +// output created by this daemon. It does not install ownership or watches. +func (r *RPCServer) ExportOORRecoveryPackage(ctx context.Context, + req *waverpc.ExportOORRecoveryPackageRequest) ( + *waverpc.ExportOORRecoveryPackageResponse, error) { + + if r == nil || r.server == nil || r.server.vtxoStore == nil { + return nil, status.Error( + codes.Unavailable, + "OOR recovery exporter is unavailable", + ) + } + source, err := lnruntime.OORRecoverySourceFromRPC( + req.GetSource(), + ) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + packages := r.newLocalOORArtifactStore() + if packages == nil { + return nil, status.Error( + codes.Unavailable, "OOR artifact store is unavailable", + ) + } + terms, err := r.server.fetchOperatorTerms(ctx) + if err != nil { + return nil, status.Errorf(codes.Unavailable, "fetch Ark "+ + "operator terms: %v", err) + } + exporter := &arkChannelRecoveryArchive{ + vtxos: r.server.vtxoStore, packages: packages, + } + recovery, err := exporter.ExportOORRecoveryPackage( + ctx, source, terms.PubKey, + ) + if err != nil { + return nil, status.Errorf(codes.Internal, "export OOR "+ + "recovery package: %v", err) + } + message, err := lnruntime.ChannelRecoveryToRPC(recovery) + if err != nil { + return nil, status.Errorf(codes.Internal, "encode OOR "+ + "recovery package: %v", err) + } + + return &waverpc.ExportOORRecoveryPackageResponse{ + Recovery: message, + }, nil +} diff --git a/waved/rpc_ark_channel_status_test.go b/waved/rpc_ark_channel_status_test.go new file mode 100644 index 000000000..d9062c3c2 --- /dev/null +++ b/waved/rpc_ark_channel_status_test.go @@ -0,0 +1,22 @@ +package waved + +import ( + "testing" + + "github.com/lightninglabs/wavelength/waverpc" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// TestArkChannelMailboxErrorsUseStatusCodes verifies malformed and unavailable +// requests do not collapse to gRPC Unknown. +func TestArkChannelMailboxErrorsUseStatusCodes(t *testing.T) { + t.Parallel() + + rpcServer := &RPCServer{} + _, err := rpcServer.ExportOORRecoveryPackage( + t.Context(), &waverpc.ExportOORRecoveryPackageRequest{}, + ) + require.Equal(t, codes.Unavailable, status.Code(err)) +} diff --git a/waved/rpc_auth.go b/waved/rpc_auth.go index edfb87f72..ddaad4bdf 100644 --- a/waved/rpc_auth.go +++ b/waved/rpc_auth.go @@ -3,6 +3,7 @@ package waved import ( "fmt" + "github.com/lightninglabs/wavelength/rpc/arkchannelrpc" "github.com/lightninglabs/wavelength/rpc/swapclientrpc" "github.com/lightninglabs/wavelength/rpc/wavewalletrpc" "github.com/lightninglabs/wavelength/waverpc" @@ -57,6 +58,9 @@ const ( // entityMacaroon covers privileged daemon credential creation. entityMacaroon = "macaroon" + + // entityChannel covers the lifecycle of Ark-backed Lightning channels. + entityChannel = "channel" ) // wavedEntities is the full set of logical macaroon entities. The read-only @@ -74,6 +78,7 @@ var wavedEntities = []string{ entityFees, entityActivity, entityMacaroon, + entityChannel, } var wavedRPCPermissions = newWavedRPCPermissions() @@ -135,7 +140,7 @@ func newWavedRPCPermissions() map[string][]bakery.Op { ) grant( daemon, entityOOR, "read", "GetIndexedOORSessionByTxid", - "ListOORSessions", "GetOORSession", + "ListOORSessions", "GetOORSession", "ExportOORRecoveryPackage", ) grant( daemon, entityOOR, "write", "SendOOR", "PrepareOOR", @@ -173,6 +178,16 @@ func newWavedRPCPermissions() map[string][]bakery.Op { "EscalateVHTLCRecovery", "CancelVHTLCRecovery", ) + arkChannel := arkchannelrpc.ArkChannelService_ServiceDesc.ServiceName + grant( + arkChannel, entityChannel, "read", "GetChannel", "ListChannels", + ) + grant( + arkChannel, entityChannel, "write", "PromoteVTXO", + "PayLightningInvoice", "MaterializeAndForceClose", + "RefreshChannel", + ) + swap := swapclientrpc.SwapClientService_ServiceDesc.ServiceName grant( swap, entitySwap, "read", "QuotePay", "ListSwaps", "GetSwap", diff --git a/waved/rpc_auth_test.go b/waved/rpc_auth_test.go index 97b1da6ad..6edd3f2cc 100644 --- a/waved/rpc_auth_test.go +++ b/waved/rpc_auth_test.go @@ -5,6 +5,7 @@ import ( btcrpcserver "github.com/btcsuite/btcwallet/rpc/rpcserver" btcwalletrpc "github.com/btcsuite/btcwallet/rpc/walletrpc" + "github.com/lightninglabs/wavelength/rpc/arkchannelrpc" "github.com/lightninglabs/wavelength/rpc/swapclientrpc" "github.com/lightninglabs/wavelength/rpc/wavewalletrpc" "github.com/lightninglabs/wavelength/waverpc" @@ -25,6 +26,8 @@ func TestWavedRPCPermissionsMapsReadMethods(t *testing.T) { waverpc.DaemonService_EstimateFee_FullMethodName, waverpc.DaemonService_GetBalance_FullMethodName, waverpc.MacaroonService_ListPermissions_FullMethodName, + arkchannelrpc.ArkChannelService_GetChannel_FullMethodName, + arkchannelrpc.ArkChannelService_ListChannels_FullMethodName, } { ops, ok := wavedRPCPermissions[fullMethod] require.True(t, ok, fullMethod) @@ -46,6 +49,11 @@ func TestWavedRPCPermissionsMapsMutatingMethods(t *testing.T) { return "/" + waverpc.DaemonService_ServiceDesc.ServiceName + "/" + method } + arkChannelService := + arkchannelrpc.ArkChannelService_ServiceDesc.ServiceName + fullArkChannelMethod := func(method string) string { + return "/" + arkChannelService + "/" + method + } for _, fullMethod := range []string{ waverpc.DaemonService_GenSeed_FullMethodName, @@ -54,6 +62,10 @@ func TestWavedRPCPermissionsMapsMutatingMethods(t *testing.T) { waverpc.DaemonService_RefreshVTXOs_FullMethodName, waverpc.DaemonService_SignReceiveAuthMessage_FullMethodName, waverpc.DaemonService_SignOutSwapHtlcAck_FullMethodName, + fullArkChannelMethod("PromoteVTXO"), + fullArkChannelMethod("PayLightningInvoice"), + fullArkChannelMethod("MaterializeAndForceClose"), + fullArkChannelMethod("RefreshChannel"), fullDaemonMethod("SubmitForfeitParticipantSignatures"), } { ops, ok := wavedRPCPermissions[fullMethod] @@ -67,6 +79,16 @@ func TestWavedRPCPermissionsMapsMutatingMethods(t *testing.T) { } } +// TestRemovedChannelPaymentPermissions denies removed demo payment paths even +// to callers with otherwise valid channel permissions. +func TestRemovedChannelPaymentPermissions(t *testing.T) { + t.Parallel() + for _, method := range []string{"SendPayment", "ReceivePayment"} { + fullMethod := "/arkchannelrpc.ArkChannelService/" + method + require.NotContains(t, wavedRPCPermissions, fullMethod) + } +} + // TestExitExportRequiresWritePermission protects executable signed ancestry // from read-only observers even though export does not mutate wallet state. func TestExitExportRequiresWritePermission(t *testing.T) { @@ -267,9 +289,8 @@ func TestWavedReadOnlyPermissions(t *testing.T) { // TestWavedRPCPermissionsCoverDaemonServices registers every service the // swapruntime/wavewalletrpc daemon serves and asserts the permission map covers // all their methods, via the exact check the startup validator runs. Without -// this, an RPC added without a grant — as happened with the credit RPCs -// (CreateCredit/RedeemCredit/ListCredits) — only fails when the daemon refuses -// to boot, not in CI. +// this, an RPC added without a grant only fails when the daemon refuses to +// boot, not in CI. func TestWavedRPCPermissionsCoverDaemonServices(t *testing.T) { t.Parallel() @@ -282,6 +303,10 @@ func TestWavedRPCPermissionsCoverDaemonServices(t *testing.T) { waverpc.RegisterMacaroonServiceServer( grpcServer, &waverpc.UnimplementedMacaroonServiceServer{}, ) + arkchannelrpc.RegisterArkChannelServiceServer( + grpcServer, + &arkchannelrpc.UnimplementedArkChannelServiceServer{}, + ) swapclientrpc.RegisterSwapClientServiceServer( grpcServer, &swapclientrpc.UnimplementedSwapClientServiceServer{}, diff --git a/waved/rpc_oor_receive.go b/waved/rpc_oor_receive.go index 41675e353..c1db7330c 100644 --- a/waved/rpc_oor_receive.go +++ b/waved/rpc_oor_receive.go @@ -17,6 +17,7 @@ import ( mailboxrpc "github.com/lightninglabs/wavelength/mailbox/rpc" "github.com/lightninglabs/wavelength/waverpc" fn "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/keychain" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) @@ -41,8 +42,9 @@ type receiveScriptRegistrationCompleter interface { registrationRPCKey string) error } -// NewReceiveScript allocates and registers a taproot receive script, or returns -// the exact existing allocation for an idempotent retry. +// NewReceiveScript registers a wallet-owned taproot receive script. Callers can +// request either a retry-safe fresh key or the daemon's durable identity key +// for a protocol destination that must survive independent process restarts. func (r *RPCServer) NewReceiveScript(ctx context.Context, req *waverpc.NewReceiveScriptRequest) ( *waverpc.NewReceiveScriptResponse, error) { @@ -60,6 +62,13 @@ func (r *RPCServer) NewReceiveScript(ctx context.Context, label = defaultOORReceiveScriptLabel } + if req.IdempotencyKey != "" && req.GetIdentityKey() { + return nil, status.Error( + codes.InvalidArgument, + "idempotency_key and identity_key cannot be combined", + ) + } + if req.IdempotencyKey != "" { if len(req.IdempotencyKey) > db.MaxOwnedReceiveScriptIdempotencyKeyBytes { @@ -124,13 +133,29 @@ func (r *RPCServer) NewReceiveScript(ctx context.Context, "initialize OOR receive key ops: %v", err) } - expiresAt := r.server.clk.Now().Add( - defaultOORRegistrationTTL, - ) - keyDesc, pkScript, err := CreateOORReceiveScriptWithExpiry( - ctx, r.server.indexer, store, deriveNextKey, signerFactory, - terms.PubKey, terms.VTXOExitDelay, label, expiresAt, - ) + expiresAt := r.server.clk.Now().Add(defaultOORRegistrationTTL) + var keyDesc *keychain.KeyDescriptor + var pkScript []byte + if req.GetIdentityKey() { + identityKey := r.server.loadClientKeyDesc() + if identityKey.PubKey == nil { + return nil, status.Errorf(codes.Internal, "missing "+ + "daemon identity key") + } + + pkScript, err = RegisterOwnedOORReceiveScriptWithExpiry( + ctx, r.server.indexer, store, identityKey, + signerFactory, terms.PubKey, terms.VTXOExitDelay, label, + expiresAt, + ) + keyDesc = &identityKey + } else { + keyDesc, pkScript, err = CreateOORReceiveScriptWithExpiry( + ctx, r.server.indexer, store, deriveNextKey, + signerFactory, terms.PubKey, terms.VTXOExitDelay, label, + expiresAt, + ) + } if err != nil { return nil, status.Errorf(codes.Internal, "unable to create "+ "OOR receive script: %v", err) diff --git a/waved/server.go b/waved/server.go index 21a786e66..738f3f4a3 100644 --- a/waved/server.go +++ b/waved/server.go @@ -29,6 +29,7 @@ import ( "github.com/lightninglabs/lndclient" tapsdk "github.com/lightninglabs/tap-sdk" "github.com/lightninglabs/tap-sdk/embedded" + "github.com/lightninglabs/wavelength/arkchannel/unrollbridge" "github.com/lightninglabs/wavelength/arkrpc" "github.com/lightninglabs/wavelength/baselib/actor" "github.com/lightninglabs/wavelength/btcwbackend" @@ -47,6 +48,7 @@ import ( "github.com/lightninglabs/wavelength/lib/recovery" "github.com/lightninglabs/wavelength/lib/types" "github.com/lightninglabs/wavelength/lndbackend" + "github.com/lightninglabs/wavelength/lnruntime" "github.com/lightninglabs/wavelength/lwwallet" mailboxpb "github.com/lightninglabs/wavelength/mailbox/pb" mailboxrpc "github.com/lightninglabs/wavelength/mailbox/rpc" @@ -54,6 +56,7 @@ import ( "github.com/lightninglabs/wavelength/oor" "github.com/lightninglabs/wavelength/proofkeys" "github.com/lightninglabs/wavelength/round" + "github.com/lightninglabs/wavelength/rpc/arkchannelrpc" "github.com/lightninglabs/wavelength/rpc/oorpb" "github.com/lightninglabs/wavelength/rpc/roundpb" "github.com/lightninglabs/wavelength/rpcauth" @@ -418,7 +421,6 @@ type Server struct { walletRef fn.Option[actor.ActorRef[ wallet.WalletMsg, wallet.WalletResp, ]] - oorRegistry *oor.OORRegistryActor // durableRoundActor owns the opt-in persistent round consumer // lifecycle. durableRoundActor *round.DurableRoundClientActor @@ -426,10 +428,22 @@ type Server struct { incomingVTXOActor *actor.DurableActor[ *vtxo.IncomingVTXOMsg, vtxo.IncomingVTXOResp, ] - creditRegistry *credit.Registry - vhtlcRecoveryStore *db.VHTLCRecoveryStoreDB - vhtlcRecovery *coordinator.Service - vhtlcPreimages *unrollpolicy.PreimageResolverRegistry + oorRegistry *oor.OORRegistryActor + creditRegistry *credit.Registry + vhtlcRecoveryStore *db.VHTLCRecoveryStoreDB + arkChannelStore *db.ArkChannelStoreDB + arkChannelMu sync.RWMutex + arkChannelController ArkChannelController + arkChannelMailboxRuntime *serverconn.Runtime + arkChannelPeerIngress *lnruntime.PeerMessageIngress + arkChannelStartupWg sync.WaitGroup + arkChannelStart func() + arkChannelReady chan struct{} + arkChannelDone <-chan struct{} + arkChannelRecoveryNeeded bool + vhtlcRecovery *coordinator.Service + vhtlcRecoveryTarget *vhtlcRecoveryTargetMaterializer + vhtlcPreimages *unrollpolicy.PreimageResolverRegistry // ledgerStore exposes the client-side ledger DB adapter for // read-only RPC handlers (GetFeeHistory). Writes go through @@ -460,11 +474,13 @@ type Server struct { // accessors (see GetVTXOLineageTx) can build the same proof DAG // the registry would build, without re-deriving the wiring. The // field is typed as harnessProofAssembler — a narrow interface - // that exposes ONLY the terminal-tolerant entry point — so the - // production EnsureProof path remains reachable solely through - // the unroll registry's own ProofAssembler reference. + // that exposes ONLY the terminal-tolerant entry point. proofAssembler harnessProofAssembler + // channelFundingProofs uses the registry's production capability. + // Unlike the harness accessor, it rejects terminal wallet inputs. + channelFundingProofs unroll.ProofAssembler + // unrollRegistryRef is the actor ref for the unilateral-exit registry. // Set during daemon initialization when the unroll subsystem is wired. unrollRegistryRef fn.Option[actor.ActorRef[ @@ -512,7 +528,8 @@ type Server struct { // lightningReceiptMu owns the optional local wallet-layer adapter. lightningReceiptMu sync.RWMutex lightningReceiptLookup LightningReceiptLookup - lightningReceiptResume func(context.Context, LightningReceiptReference) error + lightningReceiptResume func(context.Context, + LightningReceiptReference) error // hostControllerMu publishes the one ingress mode owner after // bootstrap. @@ -1487,13 +1504,11 @@ func (s *Server) runInner(ctx context.Context, shutdownFn func()) error { if s.outboxPublisher != nil { s.outboxPublisher.Stop() } - if rt := s.loadRuntime(); rt != nil { s.setServerConnected(false) //nolint:contextcheck // owned shutdown _ = rt.StopAndWait(shutdownCtx) } - if s.actorSystem != nil { //nolint:contextcheck // owned shutdown err := s.actorSystem.Shutdown(shutdownCtx) @@ -1596,6 +1611,13 @@ func (s *Server) runInner(ctx context.Context, shutdownFn func()) error { s.subLogger(db.Subsystem), ) s.vtxoStore = dbStore.NewVTXOStore(s.clk) + s.arkChannelStore = dbStore.NewArkChannelStore(s.clk) + s.arkChannelRecoveryNeeded, err = channelRecoveryRequired( + ctx, s.cfg.Swap, s.arkChannelStore.ListNonTerminal, + ) + if err != nil { + return err + } // Build the activity-log store for the wavewalletrpc subserver. s.activityStore = dbStore.NewActivityStore(s.clk) @@ -1674,6 +1696,11 @@ func (s *Server) runInner(ctx context.Context, shutdownFn func()) error { waverpc.RegisterMacaroonServiceServer( s.grpcServer, s.rpcServer, ) + arkchannelrpc.RegisterArkChannelServiceServer( + s.grpcServer, &arkChannelRPCServer{ + server: s, + }, + ) if cleanup := registerBtcwalletRPC(s.grpcServer, s); cleanup != nil { defer cleanup() } @@ -1697,6 +1724,19 @@ func (s *Server) runInner(ctx context.Context, shutdownFn func()) error { defer cleanup() } } + // The Ark channel runtime borrows the swap registrar's mailbox + // transport. Register this defer after registrar cleanup defers so it + // runs first. + defer func() { + s.arkChannelMu.Lock() + s.arkChannelStart = nil + s.arkChannelMu.Unlock() + s.arkChannelStartupWg.Wait() + joinCtx := context.WithoutCancel(ctx) + if err := s.stopArkChannelProcess(joinCtx); err != nil { + s.log.WarnS(joinCtx, "Ark channel shutdown failed", err) + } + }() activePermissions, err := registeredRPCPermissions(s.grpcServer) // Preserve the no-auth development mode's support for custom services // without daemon-defined permissions. When authentication is enabled, @@ -1801,9 +1841,17 @@ func (s *Server) runInner(ctx context.Context, shutdownFn func()) error { ) defer stopHeightRepair() + // A wallet-ready hook can fail after the channel startup supervisor + // begins retrying. Cancel even on that exit before joining either. + walletCtx, stopWallet := context.WithCancel(ctx) + var deferredWg sync.WaitGroup + defer func() { + stopWallet() + deferredWg.Wait() + }() if s.isWalletReady() { err := s.startWalletReadyServices( - ctx, chainSourceRef, timeoutRef, + walletCtx, chainSourceRef, timeoutRef, ) if err != nil { return err @@ -1815,14 +1863,13 @@ func (s *Server) runInner(ctx context.Context, shutdownFn func()) error { // The WaitGroup ensures the goroutine completes (or // is cancelled) before RunWithContext returns and // defers start tearing down resources. - var deferredWg sync.WaitGroup deferredWg.Add(1) go func() { defer deferredWg.Done() select { case <-s.walletReady: - case <-ctx.Done(): + case <-walletCtx.Done(): return } @@ -1837,7 +1884,7 @@ func (s *Server) runInner(ctx context.Context, shutdownFn func()) error { } err := s.startWalletReadyServices( - ctx, chainSourceRef, timeoutRef, + walletCtx, chainSourceRef, timeoutRef, ) if err != nil { if ctx.Err() != nil { @@ -1853,7 +1900,6 @@ func (s *Server) runInner(ctx context.Context, shutdownFn func()) error { return } }() - defer deferredWg.Wait() s.log.InfoS(ctx, "Wallet not ready, waiting for "+ "InitWallet or UnlockWallet RPC", @@ -1900,6 +1946,21 @@ func (s *Server) startWalletReadyServices(ctx context.Context, chainsource.ChainSourceMsg, chainsource.ChainSourceResp, ], timeoutRef actor.TellOnlyRef[timeout.Msg]) error { + if err := s.deriveIdentityKeyEarly(ctx); err != nil { + s.markWalletServicesReady(err) + + return fmt.Errorf("derive identity key: %w", err) + } + if s.arkChannelRecoveryNeeded { + if err := s.startOfflineChannelRecovery( + ctx, chainSourceRef, + ); err != nil { + + s.markWalletServicesReady(err) + + return err + } + } if err := s.connectAndBootstrapMailbox(ctx); err != nil { s.markWalletServicesReady(err) @@ -1928,6 +1989,7 @@ func (s *Server) startWalletReadyServices(ctx context.Context, // finishWalletStartup starts local recovery even when host intake is paused. // Ordinary daemons preserve authenticated policy/replay before subserver hooks. func (s *Server) finishWalletStartup(ctx context.Context) error { + s.armArkChannelStartup(ctx) if !s.cfg.HostDrivenIngress { if err := s.finishWalletOnlineStartup(ctx); err != nil { return err @@ -2856,10 +2918,6 @@ func (s *Server) startWalletDependentActors(ctx context.Context, ], timeoutRef actor.TellOnlyRef[timeout.Msg]) error { - s.expiryAuthenticator = NewBatchExpiryAuthenticator( - chainSourceRef, s.cfg.legacyProofScanFloor(), - ) - // ------------------------------------------------------- // 9. Register the wallet (boarding) actor. // ------------------------------------------------------- @@ -2874,14 +2932,10 @@ func (s *Server) startWalletDependentActors(ctx context.Context, // the manager ref can be passed directly in the round // config, avoiding a post-Start mutation. // ------------------------------------------------------- - s.lazyChainResolver = vtxo.NewLazyChainResolver() - vtxoManagerRef, err := s.initVTXOManager( - ctx, chainSourceRef, s.lazyChainResolver, - ) - if err != nil { + if err := s.ensureLocalVTXOManager(ctx, chainSourceRef); err != nil { return err } - s.vtxoMgrRef = fn.Some(vtxoManagerRef) + vtxoManagerRef := s.vtxoMgrRef.UnsafeFromSome() roundVTXOManager := actor.NewMapInputRef( vtxoManagerRef, mapRoundVTXOManagerMsg, @@ -2908,10 +2962,12 @@ func (s *Server) startWalletDependentActors(ctx context.Context, // ------------------------------------------------------- // 12. Register the unilateral-exit subsystem. // ------------------------------------------------------- - if err := s.initUnrollSubsystem( - ctx, chainSourceRef, - ); err != nil { - return err + if s.unrollRegistry == nil { + if err := s.initUnrollSubsystem( + ctx, chainSourceRef, + ); err != nil { + return err + } } // ------------------------------------------------------- @@ -4352,11 +4408,6 @@ func (s *Server) connectAndNegotiate(ctx context.Context) ( // //nolint:contextcheck // mailbox runtime owns lifecycle after bootstrap func (s *Server) connectAndBootstrapMailbox(ctx context.Context) error { - // Derive the identity key from the now-ready wallet. - if err := s.deriveIdentityKeyEarly(ctx); err != nil { - return fmt.Errorf("derive identity key: %w", err) - } - negotiation, err := s.connectAndNegotiateWithRetry(ctx) if err != nil { return err @@ -4855,6 +4906,50 @@ func (s *Server) dropCustomForfeitSigningContexts(_ context.Context, return nil } +// ensureLocalVTXOManager starts the wallet inventory once, including when +// channel protection needs it before the operator becomes reachable. +func (s *Server) ensureLocalVTXOManager(ctx context.Context, + chainSourceRef actor.ActorRef[ + chainsource.ChainSourceMsg, chainsource.ChainSourceResp, + ]) error { + + if s.vtxoMgrRef.IsSome() { + return nil + } + s.expiryAuthenticator = NewBatchExpiryAuthenticator( + chainSourceRef, s.cfg.legacyProofScanFloor(), + ) + s.lazyChainResolver = vtxo.NewLazyChainResolver() + ref, err := s.initVTXOManager(ctx, chainSourceRef, s.lazyChainResolver) + if err != nil { + return err + } + s.vtxoMgrRef = fn.Some(ref) + + return nil +} + +// startOfflineChannelRecovery restores local signing, chain observation and +// unroll workers before the first network negotiation can block. Recovery +// uses durable channel terms; only online operations require a live peer. +func (s *Server) startOfflineChannelRecovery(ctx context.Context, + chainSourceRef actor.ActorRef[ + chainsource.ChainSourceMsg, chainsource.ChainSourceResp, + ]) error { + + if err := s.ensureLocalVTXOManager(ctx, chainSourceRef); err != nil { + return err + } + if err := s.initUnrollSubsystem(ctx, chainSourceRef); err != nil { + return err + } + if err := s.unrollRegistry.RestoreNonTerminal(ctx); err != nil { + return fmt.Errorf("restore offline unroll jobs: %w", err) + } + + return s.initLocalChannelController(ctx) +} + // initVTXOManager creates, registers, and starts the VTXO manager actor. // The manager recovers persisted VTXOs on startup and spawns one VTXO actor // per live descriptor. @@ -6337,6 +6432,7 @@ func (s *Server) initUnrollSubsystem(ctx context.Context, s.ueStore = ueStore recoveryStore := dbStore.NewVHTLCRecoveryStore(s.clk) s.vhtlcRecoveryStore = recoveryStore + channelStore := s.arkChannelStore preimages := s.vhtlcPreimages vtxoStore := dbStore.NewVTXOStore(s.clk) @@ -6411,6 +6507,7 @@ func (s *Server) initUnrollSubsystem(ctx context.Context, ArtifactStore: oorStore, } s.proofAssembler = proofAssembler + s.channelFundingProofs = proofAssembler legacyProofScanFloor := s.cfg.legacyProofScanFloor() // Adapt the VTXO manager ref into a tell-only exit observer so the @@ -6451,9 +6548,12 @@ func (s *Server) initUnrollSubsystem(ctx context.Context, MaxSweepFeeRateSatPerVByte: s.unrollMaxFeeRate(), SweepFeeRateFallbackSatPerVByte: s. unrollSweepFeeRateFallback(), - ExitSpendPolicyResolver: unrollpolicy.ExitSpendPolicyResolver{ - Jobs: recoveryStore, - Preimage: preimages, + ExitSpendPolicyResolver: unroll.PolicyResolvers{ + unrollpolicy.ExitSpendPolicyResolver{ + Jobs: recoveryStore, + Preimage: preimages, + }, + unrollbridge.Resolver{Channels: channelStore}, }, AssetClaimer: s.unrollAssetClaimer(chainSourceRef), ArmedExitPolicy: func(ctx context.Context, @@ -6494,6 +6594,7 @@ func (s *Server) initUnrollSubsystem(ctx context.Context, return err } s.vhtlcRecovery = recoverySvc + s.vhtlcRecoveryTarget = materializer err = s.initFraudWatcher(ctx, chainSourceRef) if err != nil { diff --git a/waved/vhtlc_recovery_target.go b/waved/vhtlc_recovery_target.go index 3da64cc7f..0aa7036c3 100644 --- a/waved/vhtlc_recovery_target.go +++ b/waved/vhtlc_recovery_target.go @@ -229,18 +229,24 @@ func (m *vhtlcRecoveryTargetMaterializer) buildRecoveryDescriptor( } chainDepth := recoveryChainDepth(roots, 1) + constructionVersion, err := recoveryConstructionVersion(roots) + if err != nil { + return nil, err + } + pkScript := append([]byte(nil), targetOutput.PkScript...) return recoveryDescriptor(job, &vtxo.Descriptor{ - Outpoint: target, - Amount: btcutil.Amount(targetOutput.Value), - PkScript: append([]byte(nil), targetOutput.PkScript...), - OperatorKey: operatorKey, - Ancestry: ancestry, - RoundID: roundID, - CommitmentTxID: commitmentTxID, - BatchExpiry: batchExpiry, - ChainDepth: chainDepth, - CreatedHeight: createdHeight, + Outpoint: target, + Amount: btcutil.Amount(targetOutput.Value), + PkScript: pkScript, + OperatorKey: operatorKey, + Ancestry: ancestry, + RoundID: roundID, + CommitmentTxID: commitmentTxID, + BatchExpiry: batchExpiry, + ChainDepth: chainDepth, + CreatedHeight: createdHeight, + ConstructionVersion: constructionVersion, }) } diff --git a/waverpc/AGENTS.md b/waverpc/AGENTS.md index 239eeb079..7e51db643 100644 --- a/waverpc/AGENTS.md +++ b/waverpc/AGENTS.md @@ -2,9 +2,10 @@ ## Purpose -Daemon gRPC API definitions for wallet, boarding, round, OOR, unroll, and -VHTLC-recovery operations, plus the `Sign*` family through which other -subsystems borrow the daemon identity key (`SignReceiveAuthMessage[Compact]`, +Daemon gRPC API definitions for wallet, boarding, round, OOR, unroll, +VHTLC-recovery, and Ark-channel funding operations, plus the `Sign*` family +through which other subsystems borrow the daemon identity key +(`SignReceiveAuthMessage[Compact]`, `SignOORCustomInput`, `SignVTXOForfeit`, `SignOutSwapHtlcAck`, `SignCreditAccountAuthorization`). Proto source: `waverpc/daemon.proto`. Generated gRPC, REST-gateway, and mailbox-RPC stubs plus one hand-written @@ -33,7 +34,9 @@ the wallet activity projector to correlate the waiting operation. ## Relationships -- **Depends on**: `mailbox/rpc` (mailbox-RPC runtime types used by the +- **Depends on**: `rpc/arkchannelrpc` (`daemon.proto` imports shared channel + terms, VTXO bindings, and recovery messages), `mailbox/rpc` (mailbox-RPC + runtime types used by the generated mailbox stubs), `google.golang.org/genproto/googleapis/rpc/errdetails` and `google.golang.org/grpc` (structured errors in `errors.go`), `grpc-gateway/runtime` (REST gateway in `daemon.pb.gw.go`). @@ -73,3 +76,10 @@ the wallet activity projector to correlate the waiting operation. reports confirmed live holdings by asset; those carriers are excluded from the Bitcoin spendable balance. Listing responses expose the commitment root, but never the sealed transfer package. +- `NewReceiveScriptRequest.identity_key` registers the daemon's durable + identity key for a restart-stable protocol destination, such as an Ark + channel cooperative-close payout. It is mutually exclusive with + `idempotency_key`; combining the two returns `InvalidArgument`. +- `ExportOORRecoveryPackage` separately exports the finalized OOR package + and round ancestry for one exact output. It grants no ownership and starts + no watch by itself. diff --git a/waverpc/CLAUDE.md b/waverpc/CLAUDE.md index 239eeb079..7e51db643 100644 --- a/waverpc/CLAUDE.md +++ b/waverpc/CLAUDE.md @@ -2,9 +2,10 @@ ## Purpose -Daemon gRPC API definitions for wallet, boarding, round, OOR, unroll, and -VHTLC-recovery operations, plus the `Sign*` family through which other -subsystems borrow the daemon identity key (`SignReceiveAuthMessage[Compact]`, +Daemon gRPC API definitions for wallet, boarding, round, OOR, unroll, +VHTLC-recovery, and Ark-channel funding operations, plus the `Sign*` family +through which other subsystems borrow the daemon identity key +(`SignReceiveAuthMessage[Compact]`, `SignOORCustomInput`, `SignVTXOForfeit`, `SignOutSwapHtlcAck`, `SignCreditAccountAuthorization`). Proto source: `waverpc/daemon.proto`. Generated gRPC, REST-gateway, and mailbox-RPC stubs plus one hand-written @@ -33,7 +34,9 @@ the wallet activity projector to correlate the waiting operation. ## Relationships -- **Depends on**: `mailbox/rpc` (mailbox-RPC runtime types used by the +- **Depends on**: `rpc/arkchannelrpc` (`daemon.proto` imports shared channel + terms, VTXO bindings, and recovery messages), `mailbox/rpc` (mailbox-RPC + runtime types used by the generated mailbox stubs), `google.golang.org/genproto/googleapis/rpc/errdetails` and `google.golang.org/grpc` (structured errors in `errors.go`), `grpc-gateway/runtime` (REST gateway in `daemon.pb.gw.go`). @@ -73,3 +76,10 @@ the wallet activity projector to correlate the waiting operation. reports confirmed live holdings by asset; those carriers are excluded from the Bitcoin spendable balance. Listing responses expose the commitment root, but never the sealed transfer package. +- `NewReceiveScriptRequest.identity_key` registers the daemon's durable + identity key for a restart-stable protocol destination, such as an Ark + channel cooperative-close payout. It is mutually exclusive with + `idempotency_key`; combining the two returns `InvalidArgument`. +- `ExportOORRecoveryPackage` separately exports the finalized OOR package + and round ancestry for one exact output. It grants no ownership and starts + no watch by itself. diff --git a/waverpc/daemon.pb.go b/waverpc/daemon.pb.go index 9f1c16ef8..10665d21c 100644 --- a/waverpc/daemon.pb.go +++ b/waverpc/daemon.pb.go @@ -7,6 +7,7 @@ package waverpc import ( + arkchannelrpc "github.com/lightninglabs/wavelength/rpc/arkchannelrpc" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -2574,8 +2575,12 @@ type NewReceiveScriptRequest struct { // prefix keys with an application or tenant identity when they share one // daemon. IdempotencyKey string `protobuf:"bytes,2,opt,name=idempotency_key,json=idempotencyKey,proto3" json:"idempotency_key,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // identity_key registers the daemon's durable identity key instead of + // deriving a fresh receive key. This is reserved for restart-stable + // protocol destinations such as Ark channel refresh payouts. + IdentityKey bool `protobuf:"varint,3,opt,name=identity_key,json=identityKey,proto3" json:"identity_key,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *NewReceiveScriptRequest) Reset() { @@ -2622,6 +2627,13 @@ func (x *NewReceiveScriptRequest) GetIdempotencyKey() string { return "" } +func (x *NewReceiveScriptRequest) GetIdentityKey() bool { + if x != nil { + return x.IdentityKey + } + return false +} + type NewReceiveScriptResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // pk_script_hex is the raw taproot output script encoded as hex. @@ -4531,6 +4543,97 @@ func (x *PrepareOORResponse) GetSessionId() string { return "" } +type ExportOORRecoveryPackageRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // source identifies one exact output in a sender-owned finalized OOR + // package. + Source *arkchannelrpc.OORRecoverySource `protobuf:"bytes,1,opt,name=source,proto3" json:"source,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ExportOORRecoveryPackageRequest) Reset() { + *x = ExportOORRecoveryPackageRequest{} + mi := &file_daemon_proto_msgTypes[47] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ExportOORRecoveryPackageRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExportOORRecoveryPackageRequest) ProtoMessage() {} + +func (x *ExportOORRecoveryPackageRequest) ProtoReflect() protoreflect.Message { + mi := &file_daemon_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 ExportOORRecoveryPackageRequest.ProtoReflect.Descriptor instead. +func (*ExportOORRecoveryPackageRequest) Descriptor() ([]byte, []int) { + return file_daemon_proto_rawDescGZIP(), []int{47} +} + +func (x *ExportOORRecoveryPackageRequest) GetSource() *arkchannelrpc.OORRecoverySource { + if x != nil { + return x.Source + } + return nil +} + +type ExportOORRecoveryPackageResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + // recovery contains the complete endpoint-neutral source lineage. + Recovery *arkchannelrpc.ChannelRecoveryPackage `protobuf:"bytes,1,opt,name=recovery,proto3" json:"recovery,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ExportOORRecoveryPackageResponse) Reset() { + *x = ExportOORRecoveryPackageResponse{} + mi := &file_daemon_proto_msgTypes[48] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ExportOORRecoveryPackageResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExportOORRecoveryPackageResponse) ProtoMessage() {} + +func (x *ExportOORRecoveryPackageResponse) ProtoReflect() protoreflect.Message { + mi := &file_daemon_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 ExportOORRecoveryPackageResponse.ProtoReflect.Descriptor instead. +func (*ExportOORRecoveryPackageResponse) Descriptor() ([]byte, []int) { + return file_daemon_proto_rawDescGZIP(), []int{48} +} + +func (x *ExportOORRecoveryPackageResponse) GetRecovery() *arkchannelrpc.ChannelRecoveryPackage { + if x != nil { + return x.Recovery + } + return nil +} + type SignOORCustomInputRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // custom_input describes the vHTLC/custom VTXO and selected spend path. @@ -4545,7 +4648,7 @@ type SignOORCustomInputRequest struct { func (x *SignOORCustomInputRequest) Reset() { *x = SignOORCustomInputRequest{} - mi := &file_daemon_proto_msgTypes[47] + mi := &file_daemon_proto_msgTypes[49] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4557,7 +4660,7 @@ func (x *SignOORCustomInputRequest) String() string { func (*SignOORCustomInputRequest) ProtoMessage() {} func (x *SignOORCustomInputRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[47] + mi := &file_daemon_proto_msgTypes[49] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4570,7 +4673,7 @@ func (x *SignOORCustomInputRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SignOORCustomInputRequest.ProtoReflect.Descriptor instead. func (*SignOORCustomInputRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{47} + return file_daemon_proto_rawDescGZIP(), []int{49} } func (x *SignOORCustomInputRequest) GetCustomInput() *CustomOORInput { @@ -4606,7 +4709,7 @@ type SignOORCustomInputResponse struct { func (x *SignOORCustomInputResponse) Reset() { *x = SignOORCustomInputResponse{} - mi := &file_daemon_proto_msgTypes[48] + mi := &file_daemon_proto_msgTypes[50] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4618,7 +4721,7 @@ func (x *SignOORCustomInputResponse) String() string { func (*SignOORCustomInputResponse) ProtoMessage() {} func (x *SignOORCustomInputResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[48] + mi := &file_daemon_proto_msgTypes[50] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4631,7 +4734,7 @@ func (x *SignOORCustomInputResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SignOORCustomInputResponse.ProtoReflect.Descriptor instead. func (*SignOORCustomInputResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{48} + return file_daemon_proto_rawDescGZIP(), []int{50} } func (x *SignOORCustomInputResponse) GetSignature() *TaprootScriptSignature { @@ -4679,7 +4782,7 @@ type SignVTXOForfeitRequest struct { func (x *SignVTXOForfeitRequest) Reset() { *x = SignVTXOForfeitRequest{} - mi := &file_daemon_proto_msgTypes[49] + mi := &file_daemon_proto_msgTypes[51] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4691,7 +4794,7 @@ func (x *SignVTXOForfeitRequest) String() string { func (*SignVTXOForfeitRequest) ProtoMessage() {} func (x *SignVTXOForfeitRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[49] + mi := &file_daemon_proto_msgTypes[51] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4704,7 +4807,7 @@ func (x *SignVTXOForfeitRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SignVTXOForfeitRequest.ProtoReflect.Descriptor instead. func (*SignVTXOForfeitRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{49} + return file_daemon_proto_rawDescGZIP(), []int{51} } func (x *SignVTXOForfeitRequest) GetVtxoOutpoint() string { @@ -4789,7 +4892,7 @@ type SignVTXOForfeitResponse struct { func (x *SignVTXOForfeitResponse) Reset() { *x = SignVTXOForfeitResponse{} - mi := &file_daemon_proto_msgTypes[50] + mi := &file_daemon_proto_msgTypes[52] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4801,7 +4904,7 @@ func (x *SignVTXOForfeitResponse) String() string { func (*SignVTXOForfeitResponse) ProtoMessage() {} func (x *SignVTXOForfeitResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[50] + mi := &file_daemon_proto_msgTypes[52] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4814,7 +4917,7 @@ func (x *SignVTXOForfeitResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SignVTXOForfeitResponse.ProtoReflect.Descriptor instead. func (*SignVTXOForfeitResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{50} + return file_daemon_proto_rawDescGZIP(), []int{52} } func (x *SignVTXOForfeitResponse) GetPubkey() []byte { @@ -4852,7 +4955,7 @@ type ForfeitSigningContext struct { func (x *ForfeitSigningContext) Reset() { *x = ForfeitSigningContext{} - mi := &file_daemon_proto_msgTypes[51] + mi := &file_daemon_proto_msgTypes[53] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4864,7 +4967,7 @@ func (x *ForfeitSigningContext) String() string { func (*ForfeitSigningContext) ProtoMessage() {} func (x *ForfeitSigningContext) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[51] + mi := &file_daemon_proto_msgTypes[53] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4877,7 +4980,7 @@ func (x *ForfeitSigningContext) ProtoReflect() protoreflect.Message { // Deprecated: Use ForfeitSigningContext.ProtoReflect.Descriptor instead. func (*ForfeitSigningContext) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{51} + return file_daemon_proto_rawDescGZIP(), []int{53} } func (x *ForfeitSigningContext) GetPaymentHash() []byte { @@ -4907,7 +5010,7 @@ type OutpointSelection struct { func (x *OutpointSelection) Reset() { *x = OutpointSelection{} - mi := &file_daemon_proto_msgTypes[52] + mi := &file_daemon_proto_msgTypes[54] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4919,7 +5022,7 @@ func (x *OutpointSelection) String() string { func (*OutpointSelection) ProtoMessage() {} func (x *OutpointSelection) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[52] + mi := &file_daemon_proto_msgTypes[54] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4932,7 +5035,7 @@ func (x *OutpointSelection) ProtoReflect() protoreflect.Message { // Deprecated: Use OutpointSelection.ProtoReflect.Descriptor instead. func (*OutpointSelection) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{52} + return file_daemon_proto_rawDescGZIP(), []int{54} } func (x *OutpointSelection) GetOutpoints() []string { @@ -4957,7 +5060,7 @@ type RefreshVTXOsRequest struct { func (x *RefreshVTXOsRequest) Reset() { *x = RefreshVTXOsRequest{} - mi := &file_daemon_proto_msgTypes[53] + mi := &file_daemon_proto_msgTypes[55] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4969,7 +5072,7 @@ func (x *RefreshVTXOsRequest) String() string { func (*RefreshVTXOsRequest) ProtoMessage() {} func (x *RefreshVTXOsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[53] + mi := &file_daemon_proto_msgTypes[55] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4982,7 +5085,7 @@ func (x *RefreshVTXOsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RefreshVTXOsRequest.ProtoReflect.Descriptor instead. func (*RefreshVTXOsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{53} + return file_daemon_proto_rawDescGZIP(), []int{55} } func (x *RefreshVTXOsRequest) GetSelection() isRefreshVTXOsRequest_Selection { @@ -5054,7 +5157,7 @@ type RefreshVTXOsResponse struct { func (x *RefreshVTXOsResponse) Reset() { *x = RefreshVTXOsResponse{} - mi := &file_daemon_proto_msgTypes[54] + mi := &file_daemon_proto_msgTypes[56] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5066,7 +5169,7 @@ func (x *RefreshVTXOsResponse) String() string { func (*RefreshVTXOsResponse) ProtoMessage() {} func (x *RefreshVTXOsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[54] + mi := &file_daemon_proto_msgTypes[56] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5079,7 +5182,7 @@ func (x *RefreshVTXOsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RefreshVTXOsResponse.ProtoReflect.Descriptor instead. func (*RefreshVTXOsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{54} + return file_daemon_proto_rawDescGZIP(), []int{56} } func (x *RefreshVTXOsResponse) GetQueuedOutpoints() []string { @@ -5145,7 +5248,7 @@ type RefreshFeeEstimate struct { func (x *RefreshFeeEstimate) Reset() { *x = RefreshFeeEstimate{} - mi := &file_daemon_proto_msgTypes[55] + mi := &file_daemon_proto_msgTypes[57] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5157,7 +5260,7 @@ func (x *RefreshFeeEstimate) String() string { func (*RefreshFeeEstimate) ProtoMessage() {} func (x *RefreshFeeEstimate) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[55] + mi := &file_daemon_proto_msgTypes[57] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5170,7 +5273,7 @@ func (x *RefreshFeeEstimate) ProtoReflect() protoreflect.Message { // Deprecated: Use RefreshFeeEstimate.ProtoReflect.Descriptor instead. func (*RefreshFeeEstimate) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{55} + return file_daemon_proto_rawDescGZIP(), []int{57} } func (x *RefreshFeeEstimate) GetEstimatedTotalFeeSat() int64 { @@ -5238,7 +5341,7 @@ type OutpointFeeEstimate struct { func (x *OutpointFeeEstimate) Reset() { *x = OutpointFeeEstimate{} - mi := &file_daemon_proto_msgTypes[56] + mi := &file_daemon_proto_msgTypes[58] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5250,7 +5353,7 @@ func (x *OutpointFeeEstimate) String() string { func (*OutpointFeeEstimate) ProtoMessage() {} func (x *OutpointFeeEstimate) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[56] + mi := &file_daemon_proto_msgTypes[58] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5263,7 +5366,7 @@ func (x *OutpointFeeEstimate) ProtoReflect() protoreflect.Message { // Deprecated: Use OutpointFeeEstimate.ProtoReflect.Descriptor instead. func (*OutpointFeeEstimate) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{56} + return file_daemon_proto_rawDescGZIP(), []int{58} } func (x *OutpointFeeEstimate) GetOutpoint() string { @@ -5363,7 +5466,7 @@ type CustomRefreshVTXOInput struct { func (x *CustomRefreshVTXOInput) Reset() { *x = CustomRefreshVTXOInput{} - mi := &file_daemon_proto_msgTypes[57] + mi := &file_daemon_proto_msgTypes[59] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5375,7 +5478,7 @@ func (x *CustomRefreshVTXOInput) String() string { func (*CustomRefreshVTXOInput) ProtoMessage() {} func (x *CustomRefreshVTXOInput) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[57] + mi := &file_daemon_proto_msgTypes[59] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5388,7 +5491,7 @@ func (x *CustomRefreshVTXOInput) ProtoReflect() protoreflect.Message { // Deprecated: Use CustomRefreshVTXOInput.ProtoReflect.Descriptor instead. func (*CustomRefreshVTXOInput) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{57} + return file_daemon_proto_rawDescGZIP(), []int{59} } func (x *CustomRefreshVTXOInput) GetOutpoint() string { @@ -5462,7 +5565,7 @@ type CustomRefreshVTXOOutput struct { func (x *CustomRefreshVTXOOutput) Reset() { *x = CustomRefreshVTXOOutput{} - mi := &file_daemon_proto_msgTypes[58] + mi := &file_daemon_proto_msgTypes[60] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5474,7 +5577,7 @@ func (x *CustomRefreshVTXOOutput) String() string { func (*CustomRefreshVTXOOutput) ProtoMessage() {} func (x *CustomRefreshVTXOOutput) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[58] + mi := &file_daemon_proto_msgTypes[60] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5487,7 +5590,7 @@ func (x *CustomRefreshVTXOOutput) ProtoReflect() protoreflect.Message { // Deprecated: Use CustomRefreshVTXOOutput.ProtoReflect.Descriptor instead. func (*CustomRefreshVTXOOutput) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{58} + return file_daemon_proto_rawDescGZIP(), []int{60} } func (x *CustomRefreshVTXOOutput) GetAmountSat() int64 { @@ -5534,7 +5637,7 @@ type RefreshCustomVTXOsRequest struct { func (x *RefreshCustomVTXOsRequest) Reset() { *x = RefreshCustomVTXOsRequest{} - mi := &file_daemon_proto_msgTypes[59] + mi := &file_daemon_proto_msgTypes[61] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5546,7 +5649,7 @@ func (x *RefreshCustomVTXOsRequest) String() string { func (*RefreshCustomVTXOsRequest) ProtoMessage() {} func (x *RefreshCustomVTXOsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[59] + mi := &file_daemon_proto_msgTypes[61] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5559,7 +5662,7 @@ func (x *RefreshCustomVTXOsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RefreshCustomVTXOsRequest.ProtoReflect.Descriptor instead. func (*RefreshCustomVTXOsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{59} + return file_daemon_proto_rawDescGZIP(), []int{61} } func (x *RefreshCustomVTXOsRequest) GetInputs() []*CustomRefreshVTXOInput { @@ -5595,7 +5698,7 @@ type RefreshCustomVTXOsResponse struct { func (x *RefreshCustomVTXOsResponse) Reset() { *x = RefreshCustomVTXOsResponse{} - mi := &file_daemon_proto_msgTypes[60] + mi := &file_daemon_proto_msgTypes[62] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5607,7 +5710,7 @@ func (x *RefreshCustomVTXOsResponse) String() string { func (*RefreshCustomVTXOsResponse) ProtoMessage() {} func (x *RefreshCustomVTXOsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[60] + mi := &file_daemon_proto_msgTypes[62] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5620,7 +5723,7 @@ func (x *RefreshCustomVTXOsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RefreshCustomVTXOsResponse.ProtoReflect.Descriptor instead. func (*RefreshCustomVTXOsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{60} + return file_daemon_proto_rawDescGZIP(), []int{62} } func (x *RefreshCustomVTXOsResponse) GetQueuedOutpoints() []string { @@ -5689,7 +5792,7 @@ type PendingForfeitParticipantSignatureRequest struct { func (x *PendingForfeitParticipantSignatureRequest) Reset() { *x = PendingForfeitParticipantSignatureRequest{} - mi := &file_daemon_proto_msgTypes[61] + mi := &file_daemon_proto_msgTypes[63] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5701,7 +5804,7 @@ func (x *PendingForfeitParticipantSignatureRequest) String() string { func (*PendingForfeitParticipantSignatureRequest) ProtoMessage() {} func (x *PendingForfeitParticipantSignatureRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[61] + mi := &file_daemon_proto_msgTypes[63] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5714,7 +5817,7 @@ func (x *PendingForfeitParticipantSignatureRequest) ProtoReflect() protoreflect. // Deprecated: Use PendingForfeitParticipantSignatureRequest.ProtoReflect.Descriptor instead. func (*PendingForfeitParticipantSignatureRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{61} + return file_daemon_proto_rawDescGZIP(), []int{63} } func (x *PendingForfeitParticipantSignatureRequest) GetRequestId() []byte { @@ -5828,7 +5931,7 @@ type ListPendingForfeitParticipantSignatureRequestsRequest struct { func (x *ListPendingForfeitParticipantSignatureRequestsRequest) Reset() { *x = ListPendingForfeitParticipantSignatureRequestsRequest{} - mi := &file_daemon_proto_msgTypes[62] + mi := &file_daemon_proto_msgTypes[64] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5840,7 +5943,7 @@ func (x *ListPendingForfeitParticipantSignatureRequestsRequest) String() string func (*ListPendingForfeitParticipantSignatureRequestsRequest) ProtoMessage() {} func (x *ListPendingForfeitParticipantSignatureRequestsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[62] + mi := &file_daemon_proto_msgTypes[64] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5853,7 +5956,7 @@ func (x *ListPendingForfeitParticipantSignatureRequestsRequest) ProtoReflect() p // Deprecated: Use ListPendingForfeitParticipantSignatureRequestsRequest.ProtoReflect.Descriptor instead. func (*ListPendingForfeitParticipantSignatureRequestsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{62} + return file_daemon_proto_rawDescGZIP(), []int{64} } func (x *ListPendingForfeitParticipantSignatureRequestsRequest) GetAfterSequence() uint64 { @@ -5880,7 +5983,7 @@ type ListPendingForfeitParticipantSignatureRequestsResponse struct { func (x *ListPendingForfeitParticipantSignatureRequestsResponse) Reset() { *x = ListPendingForfeitParticipantSignatureRequestsResponse{} - mi := &file_daemon_proto_msgTypes[63] + mi := &file_daemon_proto_msgTypes[65] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5892,7 +5995,7 @@ func (x *ListPendingForfeitParticipantSignatureRequestsResponse) String() string func (*ListPendingForfeitParticipantSignatureRequestsResponse) ProtoMessage() {} func (x *ListPendingForfeitParticipantSignatureRequestsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[63] + mi := &file_daemon_proto_msgTypes[65] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5905,7 +6008,7 @@ func (x *ListPendingForfeitParticipantSignatureRequestsResponse) ProtoReflect() // Deprecated: Use ListPendingForfeitParticipantSignatureRequestsResponse.ProtoReflect.Descriptor instead. func (*ListPendingForfeitParticipantSignatureRequestsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{63} + return file_daemon_proto_rawDescGZIP(), []int{65} } func (x *ListPendingForfeitParticipantSignatureRequestsResponse) GetRequests() []*PendingForfeitParticipantSignatureRequest { @@ -5937,7 +6040,7 @@ type ForfeitParticipantSignature struct { func (x *ForfeitParticipantSignature) Reset() { *x = ForfeitParticipantSignature{} - mi := &file_daemon_proto_msgTypes[64] + mi := &file_daemon_proto_msgTypes[66] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5949,7 +6052,7 @@ func (x *ForfeitParticipantSignature) String() string { func (*ForfeitParticipantSignature) ProtoMessage() {} func (x *ForfeitParticipantSignature) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[64] + mi := &file_daemon_proto_msgTypes[66] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5962,7 +6065,7 @@ func (x *ForfeitParticipantSignature) ProtoReflect() protoreflect.Message { // Deprecated: Use ForfeitParticipantSignature.ProtoReflect.Descriptor instead. func (*ForfeitParticipantSignature) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{64} + return file_daemon_proto_rawDescGZIP(), []int{66} } func (x *ForfeitParticipantSignature) GetPubkey() []byte { @@ -5996,7 +6099,7 @@ type SubmitForfeitParticipantSignaturesRequest struct { func (x *SubmitForfeitParticipantSignaturesRequest) Reset() { *x = SubmitForfeitParticipantSignaturesRequest{} - mi := &file_daemon_proto_msgTypes[65] + mi := &file_daemon_proto_msgTypes[67] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6008,7 +6111,7 @@ func (x *SubmitForfeitParticipantSignaturesRequest) String() string { func (*SubmitForfeitParticipantSignaturesRequest) ProtoMessage() {} func (x *SubmitForfeitParticipantSignaturesRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[65] + mi := &file_daemon_proto_msgTypes[67] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6021,7 +6124,7 @@ func (x *SubmitForfeitParticipantSignaturesRequest) ProtoReflect() protoreflect. // Deprecated: Use SubmitForfeitParticipantSignaturesRequest.ProtoReflect.Descriptor instead. func (*SubmitForfeitParticipantSignaturesRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{65} + return file_daemon_proto_rawDescGZIP(), []int{67} } func (x *SubmitForfeitParticipantSignaturesRequest) GetRequestId() []byte { @@ -6046,7 +6149,7 @@ type SubmitForfeitParticipantSignaturesResponse struct { func (x *SubmitForfeitParticipantSignaturesResponse) Reset() { *x = SubmitForfeitParticipantSignaturesResponse{} - mi := &file_daemon_proto_msgTypes[66] + mi := &file_daemon_proto_msgTypes[68] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6058,7 +6161,7 @@ func (x *SubmitForfeitParticipantSignaturesResponse) String() string { func (*SubmitForfeitParticipantSignaturesResponse) ProtoMessage() {} func (x *SubmitForfeitParticipantSignaturesResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[66] + mi := &file_daemon_proto_msgTypes[68] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6071,7 +6174,7 @@ func (x *SubmitForfeitParticipantSignaturesResponse) ProtoReflect() protoreflect // Deprecated: Use SubmitForfeitParticipantSignaturesResponse.ProtoReflect.Descriptor instead. func (*SubmitForfeitParticipantSignaturesResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{66} + return file_daemon_proto_rawDescGZIP(), []int{68} } // LeaveDestination describes where a single leave output should land. @@ -6091,7 +6194,7 @@ type LeaveDestination struct { func (x *LeaveDestination) Reset() { *x = LeaveDestination{} - mi := &file_daemon_proto_msgTypes[67] + mi := &file_daemon_proto_msgTypes[69] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6103,7 +6206,7 @@ func (x *LeaveDestination) String() string { func (*LeaveDestination) ProtoMessage() {} func (x *LeaveDestination) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[67] + mi := &file_daemon_proto_msgTypes[69] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6116,7 +6219,7 @@ func (x *LeaveDestination) ProtoReflect() protoreflect.Message { // Deprecated: Use LeaveDestination.ProtoReflect.Descriptor instead. func (*LeaveDestination) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{67} + return file_daemon_proto_rawDescGZIP(), []int{69} } func (x *LeaveDestination) GetTarget() isLeaveDestination_Target { @@ -6197,7 +6300,7 @@ type LeaveVTXOsRequest struct { func (x *LeaveVTXOsRequest) Reset() { *x = LeaveVTXOsRequest{} - mi := &file_daemon_proto_msgTypes[68] + mi := &file_daemon_proto_msgTypes[70] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6209,7 +6312,7 @@ func (x *LeaveVTXOsRequest) String() string { func (*LeaveVTXOsRequest) ProtoMessage() {} func (x *LeaveVTXOsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[68] + mi := &file_daemon_proto_msgTypes[70] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6222,7 +6325,7 @@ func (x *LeaveVTXOsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use LeaveVTXOsRequest.ProtoReflect.Descriptor instead. func (*LeaveVTXOsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{68} + return file_daemon_proto_rawDescGZIP(), []int{70} } func (x *LeaveVTXOsRequest) GetSelection() isLeaveVTXOsRequest_Selection { @@ -6308,7 +6411,7 @@ type LeaveVTXOsResponse struct { func (x *LeaveVTXOsResponse) Reset() { *x = LeaveVTXOsResponse{} - mi := &file_daemon_proto_msgTypes[69] + mi := &file_daemon_proto_msgTypes[71] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6320,7 +6423,7 @@ func (x *LeaveVTXOsResponse) String() string { func (*LeaveVTXOsResponse) ProtoMessage() {} func (x *LeaveVTXOsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[69] + mi := &file_daemon_proto_msgTypes[71] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6333,7 +6436,7 @@ func (x *LeaveVTXOsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use LeaveVTXOsResponse.ProtoReflect.Descriptor instead. func (*LeaveVTXOsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{69} + return file_daemon_proto_rawDescGZIP(), []int{71} } func (x *LeaveVTXOsResponse) GetQueuedOutpoints() []string { @@ -6378,7 +6481,7 @@ type SendOnChainRequest struct { func (x *SendOnChainRequest) Reset() { *x = SendOnChainRequest{} - mi := &file_daemon_proto_msgTypes[70] + mi := &file_daemon_proto_msgTypes[72] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6390,7 +6493,7 @@ func (x *SendOnChainRequest) String() string { func (*SendOnChainRequest) ProtoMessage() {} func (x *SendOnChainRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[70] + mi := &file_daemon_proto_msgTypes[72] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6403,7 +6506,7 @@ func (x *SendOnChainRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SendOnChainRequest.ProtoReflect.Descriptor instead. func (*SendOnChainRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{70} + return file_daemon_proto_rawDescGZIP(), []int{72} } func (x *SendOnChainRequest) GetDestination() *LeaveDestination { @@ -6511,7 +6614,7 @@ type SendOnChainResponse struct { func (x *SendOnChainResponse) Reset() { *x = SendOnChainResponse{} - mi := &file_daemon_proto_msgTypes[71] + mi := &file_daemon_proto_msgTypes[73] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6523,7 +6626,7 @@ func (x *SendOnChainResponse) String() string { func (*SendOnChainResponse) ProtoMessage() {} func (x *SendOnChainResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[71] + mi := &file_daemon_proto_msgTypes[73] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6536,7 +6639,7 @@ func (x *SendOnChainResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SendOnChainResponse.ProtoReflect.Descriptor instead. func (*SendOnChainResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{71} + return file_daemon_proto_rawDescGZIP(), []int{73} } func (x *SendOnChainResponse) GetActualAmountSat() int64 { @@ -6602,7 +6705,7 @@ type BoardRequest struct { func (x *BoardRequest) Reset() { *x = BoardRequest{} - mi := &file_daemon_proto_msgTypes[72] + mi := &file_daemon_proto_msgTypes[74] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6614,7 +6717,7 @@ func (x *BoardRequest) String() string { func (*BoardRequest) ProtoMessage() {} func (x *BoardRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[72] + mi := &file_daemon_proto_msgTypes[74] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6627,7 +6730,7 @@ func (x *BoardRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use BoardRequest.ProtoReflect.Descriptor instead. func (*BoardRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{72} + return file_daemon_proto_rawDescGZIP(), []int{74} } func (x *BoardRequest) GetTargetVtxoCount() uint32 { @@ -6658,7 +6761,7 @@ type BoardResponse struct { func (x *BoardResponse) Reset() { *x = BoardResponse{} - mi := &file_daemon_proto_msgTypes[73] + mi := &file_daemon_proto_msgTypes[75] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6670,7 +6773,7 @@ func (x *BoardResponse) String() string { func (*BoardResponse) ProtoMessage() {} func (x *BoardResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[73] + mi := &file_daemon_proto_msgTypes[75] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6683,7 +6786,7 @@ func (x *BoardResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use BoardResponse.ProtoReflect.Descriptor instead. func (*BoardResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{73} + return file_daemon_proto_rawDescGZIP(), []int{75} } func (x *BoardResponse) GetStatus() string { @@ -6724,7 +6827,7 @@ type DepositAssetRequest struct { func (x *DepositAssetRequest) Reset() { *x = DepositAssetRequest{} - mi := &file_daemon_proto_msgTypes[74] + mi := &file_daemon_proto_msgTypes[76] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6736,7 +6839,7 @@ func (x *DepositAssetRequest) String() string { func (*DepositAssetRequest) ProtoMessage() {} func (x *DepositAssetRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[74] + mi := &file_daemon_proto_msgTypes[76] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6749,7 +6852,7 @@ func (x *DepositAssetRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DepositAssetRequest.ProtoReflect.Descriptor instead. func (*DepositAssetRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{74} + return file_daemon_proto_rawDescGZIP(), []int{76} } func (x *DepositAssetRequest) GetRequestId() string { @@ -6802,7 +6905,7 @@ type ListAssetDepositsRequest struct { func (x *ListAssetDepositsRequest) Reset() { *x = ListAssetDepositsRequest{} - mi := &file_daemon_proto_msgTypes[75] + mi := &file_daemon_proto_msgTypes[77] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6814,7 +6917,7 @@ func (x *ListAssetDepositsRequest) String() string { func (*ListAssetDepositsRequest) ProtoMessage() {} func (x *ListAssetDepositsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[75] + mi := &file_daemon_proto_msgTypes[77] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6827,7 +6930,7 @@ func (x *ListAssetDepositsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListAssetDepositsRequest.ProtoReflect.Descriptor instead. func (*ListAssetDepositsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{75} + return file_daemon_proto_rawDescGZIP(), []int{77} } type BoardAssetDepositRequest struct { @@ -6840,7 +6943,7 @@ type BoardAssetDepositRequest struct { func (x *BoardAssetDepositRequest) Reset() { *x = BoardAssetDepositRequest{} - mi := &file_daemon_proto_msgTypes[76] + mi := &file_daemon_proto_msgTypes[78] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6852,7 +6955,7 @@ func (x *BoardAssetDepositRequest) String() string { func (*BoardAssetDepositRequest) ProtoMessage() {} func (x *BoardAssetDepositRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[76] + mi := &file_daemon_proto_msgTypes[78] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6865,7 +6968,7 @@ func (x *BoardAssetDepositRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use BoardAssetDepositRequest.ProtoReflect.Descriptor instead. func (*BoardAssetDepositRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{76} + return file_daemon_proto_rawDescGZIP(), []int{78} } func (x *BoardAssetDepositRequest) GetRequestId() string { @@ -6885,7 +6988,7 @@ type ClaimAssetDepositRequest struct { func (x *ClaimAssetDepositRequest) Reset() { *x = ClaimAssetDepositRequest{} - mi := &file_daemon_proto_msgTypes[77] + mi := &file_daemon_proto_msgTypes[79] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6897,7 +7000,7 @@ func (x *ClaimAssetDepositRequest) String() string { func (*ClaimAssetDepositRequest) ProtoMessage() {} func (x *ClaimAssetDepositRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[77] + mi := &file_daemon_proto_msgTypes[79] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6910,7 +7013,7 @@ func (x *ClaimAssetDepositRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ClaimAssetDepositRequest.ProtoReflect.Descriptor instead. func (*ClaimAssetDepositRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{77} + return file_daemon_proto_rawDescGZIP(), []int{79} } func (x *ClaimAssetDepositRequest) GetRequestId() string { @@ -6929,7 +7032,7 @@ type ListAssetDepositsResponse struct { func (x *ListAssetDepositsResponse) Reset() { *x = ListAssetDepositsResponse{} - mi := &file_daemon_proto_msgTypes[78] + mi := &file_daemon_proto_msgTypes[80] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6941,7 +7044,7 @@ func (x *ListAssetDepositsResponse) String() string { func (*ListAssetDepositsResponse) ProtoMessage() {} func (x *ListAssetDepositsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[78] + mi := &file_daemon_proto_msgTypes[80] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6954,7 +7057,7 @@ func (x *ListAssetDepositsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListAssetDepositsResponse.ProtoReflect.Descriptor instead. func (*ListAssetDepositsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{78} + return file_daemon_proto_rawDescGZIP(), []int{80} } func (x *ListAssetDepositsResponse) GetDeposits() []*AssetDeposit { @@ -6998,7 +7101,7 @@ type AssetDeposit struct { func (x *AssetDeposit) Reset() { *x = AssetDeposit{} - mi := &file_daemon_proto_msgTypes[79] + mi := &file_daemon_proto_msgTypes[81] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7010,7 +7113,7 @@ func (x *AssetDeposit) String() string { func (*AssetDeposit) ProtoMessage() {} func (x *AssetDeposit) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[79] + mi := &file_daemon_proto_msgTypes[81] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7023,7 +7126,7 @@ func (x *AssetDeposit) ProtoReflect() protoreflect.Message { // Deprecated: Use AssetDeposit.ProtoReflect.Descriptor instead. func (*AssetDeposit) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{79} + return file_daemon_proto_rawDescGZIP(), []int{81} } func (x *AssetDeposit) GetRequestId() string { @@ -7118,7 +7221,7 @@ type NewAssetReceiveKeysRequest struct { func (x *NewAssetReceiveKeysRequest) Reset() { *x = NewAssetReceiveKeysRequest{} - mi := &file_daemon_proto_msgTypes[80] + mi := &file_daemon_proto_msgTypes[82] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7130,7 +7233,7 @@ func (x *NewAssetReceiveKeysRequest) String() string { func (*NewAssetReceiveKeysRequest) ProtoMessage() {} func (x *NewAssetReceiveKeysRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[80] + mi := &file_daemon_proto_msgTypes[82] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7143,7 +7246,7 @@ func (x *NewAssetReceiveKeysRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use NewAssetReceiveKeysRequest.ProtoReflect.Descriptor instead. func (*NewAssetReceiveKeysRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{80} + return file_daemon_proto_rawDescGZIP(), []int{82} } type AssetReceiveKeys struct { @@ -7163,7 +7266,7 @@ type AssetReceiveKeys struct { func (x *AssetReceiveKeys) Reset() { *x = AssetReceiveKeys{} - mi := &file_daemon_proto_msgTypes[81] + mi := &file_daemon_proto_msgTypes[83] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7175,7 +7278,7 @@ func (x *AssetReceiveKeys) String() string { func (*AssetReceiveKeys) ProtoMessage() {} func (x *AssetReceiveKeys) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[81] + mi := &file_daemon_proto_msgTypes[83] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7188,7 +7291,7 @@ func (x *AssetReceiveKeys) ProtoReflect() protoreflect.Message { // Deprecated: Use AssetReceiveKeys.ProtoReflect.Descriptor instead. func (*AssetReceiveKeys) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{81} + return file_daemon_proto_rawDescGZIP(), []int{83} } func (x *AssetReceiveKeys) GetScriptKey() []byte { @@ -7227,7 +7330,7 @@ type ImportAssetProofRequest struct { func (x *ImportAssetProofRequest) Reset() { *x = ImportAssetProofRequest{} - mi := &file_daemon_proto_msgTypes[82] + mi := &file_daemon_proto_msgTypes[84] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7239,7 +7342,7 @@ func (x *ImportAssetProofRequest) String() string { func (*ImportAssetProofRequest) ProtoMessage() {} func (x *ImportAssetProofRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[82] + mi := &file_daemon_proto_msgTypes[84] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7252,7 +7355,7 @@ func (x *ImportAssetProofRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ImportAssetProofRequest.ProtoReflect.Descriptor instead. func (*ImportAssetProofRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{82} + return file_daemon_proto_rawDescGZIP(), []int{84} } func (x *ImportAssetProofRequest) GetProofFile() []byte { @@ -7277,7 +7380,7 @@ type NewAssetFundingAddressRequest struct { func (x *NewAssetFundingAddressRequest) Reset() { *x = NewAssetFundingAddressRequest{} - mi := &file_daemon_proto_msgTypes[83] + mi := &file_daemon_proto_msgTypes[85] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7289,7 +7392,7 @@ func (x *NewAssetFundingAddressRequest) String() string { func (*NewAssetFundingAddressRequest) ProtoMessage() {} func (x *NewAssetFundingAddressRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[83] + mi := &file_daemon_proto_msgTypes[85] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7302,7 +7405,7 @@ func (x *NewAssetFundingAddressRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use NewAssetFundingAddressRequest.ProtoReflect.Descriptor instead. func (*NewAssetFundingAddressRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{83} + return file_daemon_proto_rawDescGZIP(), []int{85} } type AssetFundingAddress struct { @@ -7315,7 +7418,7 @@ type AssetFundingAddress struct { func (x *AssetFundingAddress) Reset() { *x = AssetFundingAddress{} - mi := &file_daemon_proto_msgTypes[84] + mi := &file_daemon_proto_msgTypes[86] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7327,7 +7430,7 @@ func (x *AssetFundingAddress) String() string { func (*AssetFundingAddress) ProtoMessage() {} func (x *AssetFundingAddress) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[84] + mi := &file_daemon_proto_msgTypes[86] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7340,7 +7443,7 @@ func (x *AssetFundingAddress) ProtoReflect() protoreflect.Message { // Deprecated: Use AssetFundingAddress.ProtoReflect.Descriptor instead. func (*AssetFundingAddress) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{84} + return file_daemon_proto_rawDescGZIP(), []int{86} } func (x *AssetFundingAddress) GetAddress() string { @@ -7358,7 +7461,7 @@ type ListOwnedAssetsRequest struct { func (x *ListOwnedAssetsRequest) Reset() { *x = ListOwnedAssetsRequest{} - mi := &file_daemon_proto_msgTypes[85] + mi := &file_daemon_proto_msgTypes[87] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7370,7 +7473,7 @@ func (x *ListOwnedAssetsRequest) String() string { func (*ListOwnedAssetsRequest) ProtoMessage() {} func (x *ListOwnedAssetsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[85] + mi := &file_daemon_proto_msgTypes[87] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7383,7 +7486,7 @@ func (x *ListOwnedAssetsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListOwnedAssetsRequest.ProtoReflect.Descriptor instead. func (*ListOwnedAssetsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{85} + return file_daemon_proto_rawDescGZIP(), []int{87} } type ListOwnedAssetsResponse struct { @@ -7395,7 +7498,7 @@ type ListOwnedAssetsResponse struct { func (x *ListOwnedAssetsResponse) Reset() { *x = ListOwnedAssetsResponse{} - mi := &file_daemon_proto_msgTypes[86] + mi := &file_daemon_proto_msgTypes[88] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7407,7 +7510,7 @@ func (x *ListOwnedAssetsResponse) String() string { func (*ListOwnedAssetsResponse) ProtoMessage() {} func (x *ListOwnedAssetsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[86] + mi := &file_daemon_proto_msgTypes[88] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7420,7 +7523,7 @@ func (x *ListOwnedAssetsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListOwnedAssetsResponse.ProtoReflect.Descriptor instead. func (*ListOwnedAssetsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{86} + return file_daemon_proto_rawDescGZIP(), []int{88} } func (x *ListOwnedAssetsResponse) GetAssets() []*OwnedAsset { @@ -7451,7 +7554,7 @@ type OwnedAsset struct { func (x *OwnedAsset) Reset() { *x = OwnedAsset{} - mi := &file_daemon_proto_msgTypes[87] + mi := &file_daemon_proto_msgTypes[89] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7463,7 +7566,7 @@ func (x *OwnedAsset) String() string { func (*OwnedAsset) ProtoMessage() {} func (x *OwnedAsset) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[87] + mi := &file_daemon_proto_msgTypes[89] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7476,7 +7579,7 @@ func (x *OwnedAsset) ProtoReflect() protoreflect.Message { // Deprecated: Use OwnedAsset.ProtoReflect.Descriptor instead. func (*OwnedAsset) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{87} + return file_daemon_proto_rawDescGZIP(), []int{89} } func (x *OwnedAsset) GetAssetRef() string { @@ -7529,7 +7632,7 @@ type JoinNextRoundRequest struct { func (x *JoinNextRoundRequest) Reset() { *x = JoinNextRoundRequest{} - mi := &file_daemon_proto_msgTypes[88] + mi := &file_daemon_proto_msgTypes[90] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7541,7 +7644,7 @@ func (x *JoinNextRoundRequest) String() string { func (*JoinNextRoundRequest) ProtoMessage() {} func (x *JoinNextRoundRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[88] + mi := &file_daemon_proto_msgTypes[90] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7554,7 +7657,7 @@ func (x *JoinNextRoundRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use JoinNextRoundRequest.ProtoReflect.Descriptor instead. func (*JoinNextRoundRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{88} + return file_daemon_proto_rawDescGZIP(), []int{90} } type JoinNextRoundResponse struct { @@ -7569,7 +7672,7 @@ type JoinNextRoundResponse struct { func (x *JoinNextRoundResponse) Reset() { *x = JoinNextRoundResponse{} - mi := &file_daemon_proto_msgTypes[89] + mi := &file_daemon_proto_msgTypes[91] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7581,7 +7684,7 @@ func (x *JoinNextRoundResponse) String() string { func (*JoinNextRoundResponse) ProtoMessage() {} func (x *JoinNextRoundResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[89] + mi := &file_daemon_proto_msgTypes[91] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7594,7 +7697,7 @@ func (x *JoinNextRoundResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use JoinNextRoundResponse.ProtoReflect.Descriptor instead. func (*JoinNextRoundResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{89} + return file_daemon_proto_rawDescGZIP(), []int{91} } func (x *JoinNextRoundResponse) GetStatus() string { @@ -7630,7 +7733,7 @@ type SweepBoardingUTXOsRequest struct { func (x *SweepBoardingUTXOsRequest) Reset() { *x = SweepBoardingUTXOsRequest{} - mi := &file_daemon_proto_msgTypes[90] + mi := &file_daemon_proto_msgTypes[92] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7642,7 +7745,7 @@ func (x *SweepBoardingUTXOsRequest) String() string { func (*SweepBoardingUTXOsRequest) ProtoMessage() {} func (x *SweepBoardingUTXOsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[90] + mi := &file_daemon_proto_msgTypes[92] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7655,7 +7758,7 @@ func (x *SweepBoardingUTXOsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SweepBoardingUTXOsRequest.ProtoReflect.Descriptor instead. func (*SweepBoardingUTXOsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{90} + return file_daemon_proto_rawDescGZIP(), []int{92} } func (x *SweepBoardingUTXOsRequest) GetOutpoints() []string { @@ -7708,7 +7811,7 @@ type BoardingSweepOutput struct { func (x *BoardingSweepOutput) Reset() { *x = BoardingSweepOutput{} - mi := &file_daemon_proto_msgTypes[91] + mi := &file_daemon_proto_msgTypes[93] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7720,7 +7823,7 @@ func (x *BoardingSweepOutput) String() string { func (*BoardingSweepOutput) ProtoMessage() {} func (x *BoardingSweepOutput) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[91] + mi := &file_daemon_proto_msgTypes[93] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7733,7 +7836,7 @@ func (x *BoardingSweepOutput) ProtoReflect() protoreflect.Message { // Deprecated: Use BoardingSweepOutput.ProtoReflect.Descriptor instead. func (*BoardingSweepOutput) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{91} + return file_daemon_proto_rawDescGZIP(), []int{93} } func (x *BoardingSweepOutput) GetOutpoint() string { @@ -7805,7 +7908,7 @@ type SweepBoardingUTXOsResponse struct { func (x *SweepBoardingUTXOsResponse) Reset() { *x = SweepBoardingUTXOsResponse{} - mi := &file_daemon_proto_msgTypes[92] + mi := &file_daemon_proto_msgTypes[94] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7817,7 +7920,7 @@ func (x *SweepBoardingUTXOsResponse) String() string { func (*SweepBoardingUTXOsResponse) ProtoMessage() {} func (x *SweepBoardingUTXOsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[92] + mi := &file_daemon_proto_msgTypes[94] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7830,7 +7933,7 @@ func (x *SweepBoardingUTXOsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SweepBoardingUTXOsResponse.ProtoReflect.Descriptor instead. func (*SweepBoardingUTXOsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{92} + return file_daemon_proto_rawDescGZIP(), []int{94} } func (x *SweepBoardingUTXOsResponse) GetStatus() string { @@ -7941,7 +8044,7 @@ type ListBoardingSweepsRequest struct { func (x *ListBoardingSweepsRequest) Reset() { *x = ListBoardingSweepsRequest{} - mi := &file_daemon_proto_msgTypes[93] + mi := &file_daemon_proto_msgTypes[95] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7953,7 +8056,7 @@ func (x *ListBoardingSweepsRequest) String() string { func (*ListBoardingSweepsRequest) ProtoMessage() {} func (x *ListBoardingSweepsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[93] + mi := &file_daemon_proto_msgTypes[95] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7966,7 +8069,7 @@ func (x *ListBoardingSweepsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListBoardingSweepsRequest.ProtoReflect.Descriptor instead. func (*ListBoardingSweepsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{93} + return file_daemon_proto_rawDescGZIP(), []int{95} } func (x *ListBoardingSweepsRequest) GetStatus() string { @@ -8009,7 +8112,7 @@ type BoardingSweepInput struct { func (x *BoardingSweepInput) Reset() { *x = BoardingSweepInput{} - mi := &file_daemon_proto_msgTypes[94] + mi := &file_daemon_proto_msgTypes[96] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8021,7 +8124,7 @@ func (x *BoardingSweepInput) String() string { func (*BoardingSweepInput) ProtoMessage() {} func (x *BoardingSweepInput) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[94] + mi := &file_daemon_proto_msgTypes[96] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8034,7 +8137,7 @@ func (x *BoardingSweepInput) ProtoReflect() protoreflect.Message { // Deprecated: Use BoardingSweepInput.ProtoReflect.Descriptor instead. func (*BoardingSweepInput) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{94} + return file_daemon_proto_rawDescGZIP(), []int{96} } func (x *BoardingSweepInput) GetOutpoint() string { @@ -8104,7 +8207,7 @@ type BoardingSweep struct { func (x *BoardingSweep) Reset() { *x = BoardingSweep{} - mi := &file_daemon_proto_msgTypes[95] + mi := &file_daemon_proto_msgTypes[97] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8116,7 +8219,7 @@ func (x *BoardingSweep) String() string { func (*BoardingSweep) ProtoMessage() {} func (x *BoardingSweep) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[95] + mi := &file_daemon_proto_msgTypes[97] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8129,7 +8232,7 @@ func (x *BoardingSweep) ProtoReflect() protoreflect.Message { // Deprecated: Use BoardingSweep.ProtoReflect.Descriptor instead. func (*BoardingSweep) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{95} + return file_daemon_proto_rawDescGZIP(), []int{97} } func (x *BoardingSweep) GetTxid() string { @@ -8221,7 +8324,7 @@ type ListBoardingSweepsResponse struct { func (x *ListBoardingSweepsResponse) Reset() { *x = ListBoardingSweepsResponse{} - mi := &file_daemon_proto_msgTypes[96] + mi := &file_daemon_proto_msgTypes[98] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8233,7 +8336,7 @@ func (x *ListBoardingSweepsResponse) String() string { func (*ListBoardingSweepsResponse) ProtoMessage() {} func (x *ListBoardingSweepsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[96] + mi := &file_daemon_proto_msgTypes[98] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8246,7 +8349,7 @@ func (x *ListBoardingSweepsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListBoardingSweepsResponse.ProtoReflect.Descriptor instead. func (*ListBoardingSweepsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{96} + return file_daemon_proto_rawDescGZIP(), []int{98} } func (x *ListBoardingSweepsResponse) GetSweeps() []*BoardingSweep { @@ -8279,7 +8382,7 @@ type RoundVTXOInfo struct { func (x *RoundVTXOInfo) Reset() { *x = RoundVTXOInfo{} - mi := &file_daemon_proto_msgTypes[97] + mi := &file_daemon_proto_msgTypes[99] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8291,7 +8394,7 @@ func (x *RoundVTXOInfo) String() string { func (*RoundVTXOInfo) ProtoMessage() {} func (x *RoundVTXOInfo) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[97] + mi := &file_daemon_proto_msgTypes[99] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8304,7 +8407,7 @@ func (x *RoundVTXOInfo) ProtoReflect() protoreflect.Message { // Deprecated: Use RoundVTXOInfo.ProtoReflect.Descriptor instead. func (*RoundVTXOInfo) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{97} + return file_daemon_proto_rawDescGZIP(), []int{99} } func (x *RoundVTXOInfo) GetOutpoint() string { @@ -8352,7 +8455,7 @@ type ScheduledBatchWindow struct { func (x *ScheduledBatchWindow) Reset() { *x = ScheduledBatchWindow{} - mi := &file_daemon_proto_msgTypes[98] + mi := &file_daemon_proto_msgTypes[100] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8364,7 +8467,7 @@ func (x *ScheduledBatchWindow) String() string { func (*ScheduledBatchWindow) ProtoMessage() {} func (x *ScheduledBatchWindow) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[98] + mi := &file_daemon_proto_msgTypes[100] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8377,7 +8480,7 @@ func (x *ScheduledBatchWindow) ProtoReflect() protoreflect.Message { // Deprecated: Use ScheduledBatchWindow.ProtoReflect.Descriptor instead. func (*ScheduledBatchWindow) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{98} + return file_daemon_proto_rawDescGZIP(), []int{100} } func (x *ScheduledBatchWindow) GetRegistrationOpensUnix() int64 { @@ -8462,7 +8565,7 @@ type RoundInfo struct { func (x *RoundInfo) Reset() { *x = RoundInfo{} - mi := &file_daemon_proto_msgTypes[99] + mi := &file_daemon_proto_msgTypes[101] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8474,7 +8577,7 @@ func (x *RoundInfo) String() string { func (*RoundInfo) ProtoMessage() {} func (x *RoundInfo) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[99] + mi := &file_daemon_proto_msgTypes[101] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8487,7 +8590,7 @@ func (x *RoundInfo) ProtoReflect() protoreflect.Message { // Deprecated: Use RoundInfo.ProtoReflect.Descriptor instead. func (*RoundInfo) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{99} + return file_daemon_proto_rawDescGZIP(), []int{101} } func (x *RoundInfo) GetRoundId() string { @@ -8627,7 +8730,7 @@ type ListRoundsRequest struct { func (x *ListRoundsRequest) Reset() { *x = ListRoundsRequest{} - mi := &file_daemon_proto_msgTypes[100] + mi := &file_daemon_proto_msgTypes[102] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8639,7 +8742,7 @@ func (x *ListRoundsRequest) String() string { func (*ListRoundsRequest) ProtoMessage() {} func (x *ListRoundsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[100] + mi := &file_daemon_proto_msgTypes[102] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8652,7 +8755,7 @@ func (x *ListRoundsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListRoundsRequest.ProtoReflect.Descriptor instead. func (*ListRoundsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{100} + return file_daemon_proto_rawDescGZIP(), []int{102} } func (x *ListRoundsRequest) GetPageSize() int32 { @@ -8707,7 +8810,7 @@ type GetRoundRequest struct { func (x *GetRoundRequest) Reset() { *x = GetRoundRequest{} - mi := &file_daemon_proto_msgTypes[101] + mi := &file_daemon_proto_msgTypes[103] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8719,7 +8822,7 @@ func (x *GetRoundRequest) String() string { func (*GetRoundRequest) ProtoMessage() {} func (x *GetRoundRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[101] + mi := &file_daemon_proto_msgTypes[103] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8732,7 +8835,7 @@ func (x *GetRoundRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetRoundRequest.ProtoReflect.Descriptor instead. func (*GetRoundRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{101} + return file_daemon_proto_rawDescGZIP(), []int{103} } func (x *GetRoundRequest) GetRoundId() string { @@ -8752,7 +8855,7 @@ type GetRoundResponse struct { func (x *GetRoundResponse) Reset() { *x = GetRoundResponse{} - mi := &file_daemon_proto_msgTypes[102] + mi := &file_daemon_proto_msgTypes[104] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8764,7 +8867,7 @@ func (x *GetRoundResponse) String() string { func (*GetRoundResponse) ProtoMessage() {} func (x *GetRoundResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[102] + mi := &file_daemon_proto_msgTypes[104] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8777,7 +8880,7 @@ func (x *GetRoundResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetRoundResponse.ProtoReflect.Descriptor instead. func (*GetRoundResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{102} + return file_daemon_proto_rawDescGZIP(), []int{104} } func (x *GetRoundResponse) GetRound() *RoundInfo { @@ -8800,7 +8903,7 @@ type ListRoundsResponse struct { func (x *ListRoundsResponse) Reset() { *x = ListRoundsResponse{} - mi := &file_daemon_proto_msgTypes[103] + mi := &file_daemon_proto_msgTypes[105] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8812,7 +8915,7 @@ func (x *ListRoundsResponse) String() string { func (*ListRoundsResponse) ProtoMessage() {} func (x *ListRoundsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[103] + mi := &file_daemon_proto_msgTypes[105] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8825,7 +8928,7 @@ func (x *ListRoundsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListRoundsResponse.ProtoReflect.Descriptor instead. func (*ListRoundsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{103} + return file_daemon_proto_rawDescGZIP(), []int{105} } func (x *ListRoundsResponse) GetRounds() []*RoundInfo { @@ -8850,7 +8953,7 @@ type WatchRoundsRequest struct { func (x *WatchRoundsRequest) Reset() { *x = WatchRoundsRequest{} - mi := &file_daemon_proto_msgTypes[104] + mi := &file_daemon_proto_msgTypes[106] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8862,7 +8965,7 @@ func (x *WatchRoundsRequest) String() string { func (*WatchRoundsRequest) ProtoMessage() {} func (x *WatchRoundsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[104] + mi := &file_daemon_proto_msgTypes[106] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8875,7 +8978,7 @@ func (x *WatchRoundsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use WatchRoundsRequest.ProtoReflect.Descriptor instead. func (*WatchRoundsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{104} + return file_daemon_proto_rawDescGZIP(), []int{106} } type WatchRoundsResponse struct { @@ -8889,7 +8992,7 @@ type WatchRoundsResponse struct { func (x *WatchRoundsResponse) Reset() { *x = WatchRoundsResponse{} - mi := &file_daemon_proto_msgTypes[105] + mi := &file_daemon_proto_msgTypes[107] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8901,7 +9004,7 @@ func (x *WatchRoundsResponse) String() string { func (*WatchRoundsResponse) ProtoMessage() {} func (x *WatchRoundsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[105] + mi := &file_daemon_proto_msgTypes[107] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8914,7 +9017,7 @@ func (x *WatchRoundsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use WatchRoundsResponse.ProtoReflect.Descriptor instead. func (*WatchRoundsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{105} + return file_daemon_proto_rawDescGZIP(), []int{107} } func (x *WatchRoundsResponse) GetRound() *RoundInfo { @@ -8959,7 +9062,7 @@ type OORSessionInfo struct { func (x *OORSessionInfo) Reset() { *x = OORSessionInfo{} - mi := &file_daemon_proto_msgTypes[106] + mi := &file_daemon_proto_msgTypes[108] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8971,7 +9074,7 @@ func (x *OORSessionInfo) String() string { func (*OORSessionInfo) ProtoMessage() {} func (x *OORSessionInfo) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[106] + mi := &file_daemon_proto_msgTypes[108] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8984,7 +9087,7 @@ func (x *OORSessionInfo) ProtoReflect() protoreflect.Message { // Deprecated: Use OORSessionInfo.ProtoReflect.Descriptor instead. func (*OORSessionInfo) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{106} + return file_daemon_proto_rawDescGZIP(), []int{108} } func (x *OORSessionInfo) GetSessionId() string { @@ -9076,7 +9179,7 @@ type ListOORSessionsRequest struct { func (x *ListOORSessionsRequest) Reset() { *x = ListOORSessionsRequest{} - mi := &file_daemon_proto_msgTypes[107] + mi := &file_daemon_proto_msgTypes[109] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9088,7 +9191,7 @@ func (x *ListOORSessionsRequest) String() string { func (*ListOORSessionsRequest) ProtoMessage() {} func (x *ListOORSessionsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[107] + mi := &file_daemon_proto_msgTypes[109] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9101,7 +9204,7 @@ func (x *ListOORSessionsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListOORSessionsRequest.ProtoReflect.Descriptor instead. func (*ListOORSessionsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{107} + return file_daemon_proto_rawDescGZIP(), []int{109} } func (x *ListOORSessionsRequest) GetPageSize() int32 { @@ -9145,7 +9248,7 @@ type ListOORSessionsResponse struct { func (x *ListOORSessionsResponse) Reset() { *x = ListOORSessionsResponse{} - mi := &file_daemon_proto_msgTypes[108] + mi := &file_daemon_proto_msgTypes[110] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9157,7 +9260,7 @@ func (x *ListOORSessionsResponse) String() string { func (*ListOORSessionsResponse) ProtoMessage() {} func (x *ListOORSessionsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[108] + mi := &file_daemon_proto_msgTypes[110] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9170,7 +9273,7 @@ func (x *ListOORSessionsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListOORSessionsResponse.ProtoReflect.Descriptor instead. func (*ListOORSessionsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{108} + return file_daemon_proto_rawDescGZIP(), []int{110} } func (x *ListOORSessionsResponse) GetSessions() []*OORSessionInfo { @@ -9201,7 +9304,7 @@ type GetOORSessionRequest struct { func (x *GetOORSessionRequest) Reset() { *x = GetOORSessionRequest{} - mi := &file_daemon_proto_msgTypes[109] + mi := &file_daemon_proto_msgTypes[111] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9213,7 +9316,7 @@ func (x *GetOORSessionRequest) String() string { func (*GetOORSessionRequest) ProtoMessage() {} func (x *GetOORSessionRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[109] + mi := &file_daemon_proto_msgTypes[111] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9226,7 +9329,7 @@ func (x *GetOORSessionRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetOORSessionRequest.ProtoReflect.Descriptor instead. func (*GetOORSessionRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{109} + return file_daemon_proto_rawDescGZIP(), []int{111} } func (x *GetOORSessionRequest) GetSessionId() string { @@ -9256,7 +9359,7 @@ type GetOORSessionResponse struct { func (x *GetOORSessionResponse) Reset() { *x = GetOORSessionResponse{} - mi := &file_daemon_proto_msgTypes[110] + mi := &file_daemon_proto_msgTypes[112] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9268,7 +9371,7 @@ func (x *GetOORSessionResponse) String() string { func (*GetOORSessionResponse) ProtoMessage() {} func (x *GetOORSessionResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[110] + mi := &file_daemon_proto_msgTypes[112] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9281,7 +9384,7 @@ func (x *GetOORSessionResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetOORSessionResponse.ProtoReflect.Descriptor instead. func (*GetOORSessionResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{110} + return file_daemon_proto_rawDescGZIP(), []int{112} } func (x *GetOORSessionResponse) GetSession() *OORSessionInfo { @@ -9316,7 +9419,7 @@ type EstimateFeeRequest struct { func (x *EstimateFeeRequest) Reset() { *x = EstimateFeeRequest{} - mi := &file_daemon_proto_msgTypes[111] + mi := &file_daemon_proto_msgTypes[113] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9328,7 +9431,7 @@ func (x *EstimateFeeRequest) String() string { func (*EstimateFeeRequest) ProtoMessage() {} func (x *EstimateFeeRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[111] + mi := &file_daemon_proto_msgTypes[113] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9341,7 +9444,7 @@ func (x *EstimateFeeRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use EstimateFeeRequest.ProtoReflect.Descriptor instead. func (*EstimateFeeRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{111} + return file_daemon_proto_rawDescGZIP(), []int{113} } func (x *EstimateFeeRequest) GetAmountSat() int64 { @@ -9395,7 +9498,7 @@ type EstimateFeeResponse struct { func (x *EstimateFeeResponse) Reset() { *x = EstimateFeeResponse{} - mi := &file_daemon_proto_msgTypes[112] + mi := &file_daemon_proto_msgTypes[114] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9407,7 +9510,7 @@ func (x *EstimateFeeResponse) String() string { func (*EstimateFeeResponse) ProtoMessage() {} func (x *EstimateFeeResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[112] + mi := &file_daemon_proto_msgTypes[114] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9420,7 +9523,7 @@ func (x *EstimateFeeResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use EstimateFeeResponse.ProtoReflect.Descriptor instead. func (*EstimateFeeResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{112} + return file_daemon_proto_rawDescGZIP(), []int{114} } func (x *EstimateFeeResponse) GetLiquidityFeeSat() int64 { @@ -9516,7 +9619,7 @@ type GetFeeHistoryRequest struct { func (x *GetFeeHistoryRequest) Reset() { *x = GetFeeHistoryRequest{} - mi := &file_daemon_proto_msgTypes[113] + mi := &file_daemon_proto_msgTypes[115] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9528,7 +9631,7 @@ func (x *GetFeeHistoryRequest) String() string { func (*GetFeeHistoryRequest) ProtoMessage() {} func (x *GetFeeHistoryRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[113] + mi := &file_daemon_proto_msgTypes[115] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9541,7 +9644,7 @@ func (x *GetFeeHistoryRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetFeeHistoryRequest.ProtoReflect.Descriptor instead. func (*GetFeeHistoryRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{113} + return file_daemon_proto_rawDescGZIP(), []int{115} } func (x *GetFeeHistoryRequest) GetLimit() uint32 { @@ -9649,7 +9752,7 @@ type FeeHistoryEntry struct { func (x *FeeHistoryEntry) Reset() { *x = FeeHistoryEntry{} - mi := &file_daemon_proto_msgTypes[114] + mi := &file_daemon_proto_msgTypes[116] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9661,7 +9764,7 @@ func (x *FeeHistoryEntry) String() string { func (*FeeHistoryEntry) ProtoMessage() {} func (x *FeeHistoryEntry) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[114] + mi := &file_daemon_proto_msgTypes[116] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9674,7 +9777,7 @@ func (x *FeeHistoryEntry) ProtoReflect() protoreflect.Message { // Deprecated: Use FeeHistoryEntry.ProtoReflect.Descriptor instead. func (*FeeHistoryEntry) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{114} + return file_daemon_proto_rawDescGZIP(), []int{116} } func (x *FeeHistoryEntry) GetEntryId() int64 { @@ -9768,7 +9871,7 @@ type GetFeeHistoryResponse struct { func (x *GetFeeHistoryResponse) Reset() { *x = GetFeeHistoryResponse{} - mi := &file_daemon_proto_msgTypes[115] + mi := &file_daemon_proto_msgTypes[117] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9780,7 +9883,7 @@ func (x *GetFeeHistoryResponse) String() string { func (*GetFeeHistoryResponse) ProtoMessage() {} func (x *GetFeeHistoryResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[115] + mi := &file_daemon_proto_msgTypes[117] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9793,7 +9896,7 @@ func (x *GetFeeHistoryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetFeeHistoryResponse.ProtoReflect.Descriptor instead. func (*GetFeeHistoryResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{115} + return file_daemon_proto_rawDescGZIP(), []int{117} } func (x *GetFeeHistoryResponse) GetEntries() []*FeeHistoryEntry { @@ -9834,7 +9937,7 @@ type ListTransactionsRequest struct { func (x *ListTransactionsRequest) Reset() { *x = ListTransactionsRequest{} - mi := &file_daemon_proto_msgTypes[116] + mi := &file_daemon_proto_msgTypes[118] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9846,7 +9949,7 @@ func (x *ListTransactionsRequest) String() string { func (*ListTransactionsRequest) ProtoMessage() {} func (x *ListTransactionsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[116] + mi := &file_daemon_proto_msgTypes[118] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9859,7 +9962,7 @@ func (x *ListTransactionsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListTransactionsRequest.ProtoReflect.Descriptor instead. func (*ListTransactionsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{116} + return file_daemon_proto_rawDescGZIP(), []int{118} } func (x *ListTransactionsRequest) GetFromUnixS() int64 { @@ -9950,7 +10053,7 @@ type TransactionHistoryEntry struct { func (x *TransactionHistoryEntry) Reset() { *x = TransactionHistoryEntry{} - mi := &file_daemon_proto_msgTypes[117] + mi := &file_daemon_proto_msgTypes[119] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9962,7 +10065,7 @@ func (x *TransactionHistoryEntry) String() string { func (*TransactionHistoryEntry) ProtoMessage() {} func (x *TransactionHistoryEntry) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[117] + mi := &file_daemon_proto_msgTypes[119] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9975,7 +10078,7 @@ func (x *TransactionHistoryEntry) ProtoReflect() protoreflect.Message { // Deprecated: Use TransactionHistoryEntry.ProtoReflect.Descriptor instead. func (*TransactionHistoryEntry) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{117} + return file_daemon_proto_rawDescGZIP(), []int{119} } func (x *TransactionHistoryEntry) GetSource() string { @@ -10112,7 +10215,7 @@ type ListTransactionsResponse struct { func (x *ListTransactionsResponse) Reset() { *x = ListTransactionsResponse{} - mi := &file_daemon_proto_msgTypes[118] + mi := &file_daemon_proto_msgTypes[120] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10124,7 +10227,7 @@ func (x *ListTransactionsResponse) String() string { func (*ListTransactionsResponse) ProtoMessage() {} func (x *ListTransactionsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[118] + mi := &file_daemon_proto_msgTypes[120] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10137,7 +10240,7 @@ func (x *ListTransactionsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListTransactionsResponse.ProtoReflect.Descriptor instead. func (*ListTransactionsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{118} + return file_daemon_proto_rawDescGZIP(), []int{120} } func (x *ListTransactionsResponse) GetTransactions() []*TransactionHistoryEntry { @@ -10172,7 +10275,7 @@ type UnrollRequest struct { func (x *UnrollRequest) Reset() { *x = UnrollRequest{} - mi := &file_daemon_proto_msgTypes[119] + mi := &file_daemon_proto_msgTypes[121] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10184,7 +10287,7 @@ func (x *UnrollRequest) String() string { func (*UnrollRequest) ProtoMessage() {} func (x *UnrollRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[119] + mi := &file_daemon_proto_msgTypes[121] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10197,7 +10300,7 @@ func (x *UnrollRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UnrollRequest.ProtoReflect.Descriptor instead. func (*UnrollRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{119} + return file_daemon_proto_rawDescGZIP(), []int{121} } func (x *UnrollRequest) GetOutpoint() string { @@ -10220,7 +10323,7 @@ type UnrollResponse struct { func (x *UnrollResponse) Reset() { *x = UnrollResponse{} - mi := &file_daemon_proto_msgTypes[120] + mi := &file_daemon_proto_msgTypes[122] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10232,7 +10335,7 @@ func (x *UnrollResponse) String() string { func (*UnrollResponse) ProtoMessage() {} func (x *UnrollResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[120] + mi := &file_daemon_proto_msgTypes[122] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10245,7 +10348,7 @@ func (x *UnrollResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use UnrollResponse.ProtoReflect.Descriptor instead. func (*UnrollResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{120} + return file_daemon_proto_rawDescGZIP(), []int{122} } func (x *UnrollResponse) GetCreated() bool { @@ -10277,7 +10380,7 @@ type GetUnrollStatusRequest struct { func (x *GetUnrollStatusRequest) Reset() { *x = GetUnrollStatusRequest{} - mi := &file_daemon_proto_msgTypes[121] + mi := &file_daemon_proto_msgTypes[123] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10289,7 +10392,7 @@ func (x *GetUnrollStatusRequest) String() string { func (*GetUnrollStatusRequest) ProtoMessage() {} func (x *GetUnrollStatusRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[121] + mi := &file_daemon_proto_msgTypes[123] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10302,7 +10405,7 @@ func (x *GetUnrollStatusRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetUnrollStatusRequest.ProtoReflect.Descriptor instead. func (*GetUnrollStatusRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{121} + return file_daemon_proto_rawDescGZIP(), []int{123} } func (x *GetUnrollStatusRequest) GetOutpoint() string { @@ -10354,7 +10457,7 @@ type UnrollProgress struct { func (x *UnrollProgress) Reset() { *x = UnrollProgress{} - mi := &file_daemon_proto_msgTypes[122] + mi := &file_daemon_proto_msgTypes[124] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10366,7 +10469,7 @@ func (x *UnrollProgress) String() string { func (*UnrollProgress) ProtoMessage() {} func (x *UnrollProgress) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[122] + mi := &file_daemon_proto_msgTypes[124] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10379,7 +10482,7 @@ func (x *UnrollProgress) ProtoReflect() protoreflect.Message { // Deprecated: Use UnrollProgress.ProtoReflect.Descriptor instead. func (*UnrollProgress) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{122} + return file_daemon_proto_rawDescGZIP(), []int{124} } func (x *UnrollProgress) GetConfirmedTxs() uint32 { @@ -10464,7 +10567,7 @@ type UnrollCSV struct { func (x *UnrollCSV) Reset() { *x = UnrollCSV{} - mi := &file_daemon_proto_msgTypes[123] + mi := &file_daemon_proto_msgTypes[125] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10476,7 +10579,7 @@ func (x *UnrollCSV) String() string { func (*UnrollCSV) ProtoMessage() {} func (x *UnrollCSV) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[123] + mi := &file_daemon_proto_msgTypes[125] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10489,7 +10592,7 @@ func (x *UnrollCSV) ProtoReflect() protoreflect.Message { // Deprecated: Use UnrollCSV.ProtoReflect.Descriptor instead. func (*UnrollCSV) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{123} + return file_daemon_proto_rawDescGZIP(), []int{125} } func (x *UnrollCSV) GetTargetConfirmHeight() int32 { @@ -10555,7 +10658,7 @@ type UnrollFees struct { func (x *UnrollFees) Reset() { *x = UnrollFees{} - mi := &file_daemon_proto_msgTypes[124] + mi := &file_daemon_proto_msgTypes[126] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10567,7 +10670,7 @@ func (x *UnrollFees) String() string { func (*UnrollFees) ProtoMessage() {} func (x *UnrollFees) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[124] + mi := &file_daemon_proto_msgTypes[126] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10580,7 +10683,7 @@ func (x *UnrollFees) ProtoReflect() protoreflect.Message { // Deprecated: Use UnrollFees.ProtoReflect.Descriptor instead. func (*UnrollFees) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{124} + return file_daemon_proto_rawDescGZIP(), []int{126} } func (x *UnrollFees) GetCpfpFeeSat() int64 { @@ -10682,7 +10785,7 @@ type GetUnrollStatusResponse struct { func (x *GetUnrollStatusResponse) Reset() { *x = GetUnrollStatusResponse{} - mi := &file_daemon_proto_msgTypes[125] + mi := &file_daemon_proto_msgTypes[127] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10694,7 +10797,7 @@ func (x *GetUnrollStatusResponse) String() string { func (*GetUnrollStatusResponse) ProtoMessage() {} func (x *GetUnrollStatusResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[125] + mi := &file_daemon_proto_msgTypes[127] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10707,7 +10810,7 @@ func (x *GetUnrollStatusResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetUnrollStatusResponse.ProtoReflect.Descriptor instead. func (*GetUnrollStatusResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{125} + return file_daemon_proto_rawDescGZIP(), []int{127} } func (x *GetUnrollStatusResponse) GetFound() bool { @@ -10838,7 +10941,7 @@ type ArmVHTLCRecoveryRequest struct { func (x *ArmVHTLCRecoveryRequest) Reset() { *x = ArmVHTLCRecoveryRequest{} - mi := &file_daemon_proto_msgTypes[126] + mi := &file_daemon_proto_msgTypes[128] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10850,7 +10953,7 @@ func (x *ArmVHTLCRecoveryRequest) String() string { func (*ArmVHTLCRecoveryRequest) ProtoMessage() {} func (x *ArmVHTLCRecoveryRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[126] + mi := &file_daemon_proto_msgTypes[128] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10863,7 +10966,7 @@ func (x *ArmVHTLCRecoveryRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ArmVHTLCRecoveryRequest.ProtoReflect.Descriptor instead. func (*ArmVHTLCRecoveryRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{126} + return file_daemon_proto_rawDescGZIP(), []int{128} } func (x *ArmVHTLCRecoveryRequest) GetRequestId() string { @@ -11006,7 +11109,7 @@ type ArmVHTLCRecoveryResponse struct { func (x *ArmVHTLCRecoveryResponse) Reset() { *x = ArmVHTLCRecoveryResponse{} - mi := &file_daemon_proto_msgTypes[127] + mi := &file_daemon_proto_msgTypes[129] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11018,7 +11121,7 @@ func (x *ArmVHTLCRecoveryResponse) String() string { func (*ArmVHTLCRecoveryResponse) ProtoMessage() {} func (x *ArmVHTLCRecoveryResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[127] + mi := &file_daemon_proto_msgTypes[129] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11031,7 +11134,7 @@ func (x *ArmVHTLCRecoveryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ArmVHTLCRecoveryResponse.ProtoReflect.Descriptor instead. func (*ArmVHTLCRecoveryResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{127} + return file_daemon_proto_rawDescGZIP(), []int{129} } func (x *ArmVHTLCRecoveryResponse) GetRecoveryId() string { @@ -11071,7 +11174,7 @@ type EscalateVHTLCRecoveryRequest struct { func (x *EscalateVHTLCRecoveryRequest) Reset() { *x = EscalateVHTLCRecoveryRequest{} - mi := &file_daemon_proto_msgTypes[128] + mi := &file_daemon_proto_msgTypes[130] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11083,7 +11186,7 @@ func (x *EscalateVHTLCRecoveryRequest) String() string { func (*EscalateVHTLCRecoveryRequest) ProtoMessage() {} func (x *EscalateVHTLCRecoveryRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[128] + mi := &file_daemon_proto_msgTypes[130] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11096,7 +11199,7 @@ func (x *EscalateVHTLCRecoveryRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use EscalateVHTLCRecoveryRequest.ProtoReflect.Descriptor instead. func (*EscalateVHTLCRecoveryRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{128} + return file_daemon_proto_rawDescGZIP(), []int{130} } func (x *EscalateVHTLCRecoveryRequest) GetRecoveryId() string { @@ -11130,7 +11233,7 @@ type EscalateVHTLCRecoveryResponse struct { func (x *EscalateVHTLCRecoveryResponse) Reset() { *x = EscalateVHTLCRecoveryResponse{} - mi := &file_daemon_proto_msgTypes[129] + mi := &file_daemon_proto_msgTypes[131] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11142,7 +11245,7 @@ func (x *EscalateVHTLCRecoveryResponse) String() string { func (*EscalateVHTLCRecoveryResponse) ProtoMessage() {} func (x *EscalateVHTLCRecoveryResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[129] + mi := &file_daemon_proto_msgTypes[131] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11155,7 +11258,7 @@ func (x *EscalateVHTLCRecoveryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use EscalateVHTLCRecoveryResponse.ProtoReflect.Descriptor instead. func (*EscalateVHTLCRecoveryResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{129} + return file_daemon_proto_rawDescGZIP(), []int{131} } func (x *EscalateVHTLCRecoveryResponse) GetStatus() *VHTLCRecoveryStatus { @@ -11179,7 +11282,7 @@ type CancelVHTLCRecoveryRequest struct { func (x *CancelVHTLCRecoveryRequest) Reset() { *x = CancelVHTLCRecoveryRequest{} - mi := &file_daemon_proto_msgTypes[130] + mi := &file_daemon_proto_msgTypes[132] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11191,7 +11294,7 @@ func (x *CancelVHTLCRecoveryRequest) String() string { func (*CancelVHTLCRecoveryRequest) ProtoMessage() {} func (x *CancelVHTLCRecoveryRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[130] + mi := &file_daemon_proto_msgTypes[132] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11204,7 +11307,7 @@ func (x *CancelVHTLCRecoveryRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CancelVHTLCRecoveryRequest.ProtoReflect.Descriptor instead. func (*CancelVHTLCRecoveryRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{130} + return file_daemon_proto_rawDescGZIP(), []int{132} } func (x *CancelVHTLCRecoveryRequest) GetRecoveryId() string { @@ -11238,7 +11341,7 @@ type CancelVHTLCRecoveryResponse struct { func (x *CancelVHTLCRecoveryResponse) Reset() { *x = CancelVHTLCRecoveryResponse{} - mi := &file_daemon_proto_msgTypes[131] + mi := &file_daemon_proto_msgTypes[133] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11250,7 +11353,7 @@ func (x *CancelVHTLCRecoveryResponse) String() string { func (*CancelVHTLCRecoveryResponse) ProtoMessage() {} func (x *CancelVHTLCRecoveryResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[131] + mi := &file_daemon_proto_msgTypes[133] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11263,7 +11366,7 @@ func (x *CancelVHTLCRecoveryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use CancelVHTLCRecoveryResponse.ProtoReflect.Descriptor instead. func (*CancelVHTLCRecoveryResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{131} + return file_daemon_proto_rawDescGZIP(), []int{133} } func (x *CancelVHTLCRecoveryResponse) GetStatus() *VHTLCRecoveryStatus { @@ -11287,7 +11390,7 @@ type GetVHTLCRecoveryStatusRequest struct { func (x *GetVHTLCRecoveryStatusRequest) Reset() { *x = GetVHTLCRecoveryStatusRequest{} - mi := &file_daemon_proto_msgTypes[132] + mi := &file_daemon_proto_msgTypes[134] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11299,7 +11402,7 @@ func (x *GetVHTLCRecoveryStatusRequest) String() string { func (*GetVHTLCRecoveryStatusRequest) ProtoMessage() {} func (x *GetVHTLCRecoveryStatusRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[132] + mi := &file_daemon_proto_msgTypes[134] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11312,7 +11415,7 @@ func (x *GetVHTLCRecoveryStatusRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetVHTLCRecoveryStatusRequest.ProtoReflect.Descriptor instead. func (*GetVHTLCRecoveryStatusRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{132} + return file_daemon_proto_rawDescGZIP(), []int{134} } func (x *GetVHTLCRecoveryStatusRequest) GetRecoveryId() string { @@ -11341,7 +11444,7 @@ type GetVHTLCRecoveryStatusResponse struct { func (x *GetVHTLCRecoveryStatusResponse) Reset() { *x = GetVHTLCRecoveryStatusResponse{} - mi := &file_daemon_proto_msgTypes[133] + mi := &file_daemon_proto_msgTypes[135] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11353,7 +11456,7 @@ func (x *GetVHTLCRecoveryStatusResponse) String() string { func (*GetVHTLCRecoveryStatusResponse) ProtoMessage() {} func (x *GetVHTLCRecoveryStatusResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[133] + mi := &file_daemon_proto_msgTypes[135] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11366,7 +11469,7 @@ func (x *GetVHTLCRecoveryStatusResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetVHTLCRecoveryStatusResponse.ProtoReflect.Descriptor instead. func (*GetVHTLCRecoveryStatusResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{133} + return file_daemon_proto_rawDescGZIP(), []int{135} } func (x *GetVHTLCRecoveryStatusResponse) GetFound() bool { @@ -11393,7 +11496,7 @@ type ListVHTLCRecoveriesRequest struct { func (x *ListVHTLCRecoveriesRequest) Reset() { *x = ListVHTLCRecoveriesRequest{} - mi := &file_daemon_proto_msgTypes[134] + mi := &file_daemon_proto_msgTypes[136] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11405,7 +11508,7 @@ func (x *ListVHTLCRecoveriesRequest) String() string { func (*ListVHTLCRecoveriesRequest) ProtoMessage() {} func (x *ListVHTLCRecoveriesRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[134] + mi := &file_daemon_proto_msgTypes[136] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11418,7 +11521,7 @@ func (x *ListVHTLCRecoveriesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListVHTLCRecoveriesRequest.ProtoReflect.Descriptor instead. func (*ListVHTLCRecoveriesRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{134} + return file_daemon_proto_rawDescGZIP(), []int{136} } func (x *ListVHTLCRecoveriesRequest) GetIncludeTerminal() bool { @@ -11438,7 +11541,7 @@ type ListVHTLCRecoveriesResponse struct { func (x *ListVHTLCRecoveriesResponse) Reset() { *x = ListVHTLCRecoveriesResponse{} - mi := &file_daemon_proto_msgTypes[135] + mi := &file_daemon_proto_msgTypes[137] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11450,7 +11553,7 @@ func (x *ListVHTLCRecoveriesResponse) String() string { func (*ListVHTLCRecoveriesResponse) ProtoMessage() {} func (x *ListVHTLCRecoveriesResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[135] + mi := &file_daemon_proto_msgTypes[137] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11463,7 +11566,7 @@ func (x *ListVHTLCRecoveriesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListVHTLCRecoveriesResponse.ProtoReflect.Descriptor instead. func (*ListVHTLCRecoveriesResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{135} + return file_daemon_proto_rawDescGZIP(), []int{137} } func (x *ListVHTLCRecoveriesResponse) GetStatuses() []*VHTLCRecoveryStatus { @@ -11538,7 +11641,7 @@ type VHTLCRecoveryStatus struct { func (x *VHTLCRecoveryStatus) Reset() { *x = VHTLCRecoveryStatus{} - mi := &file_daemon_proto_msgTypes[136] + mi := &file_daemon_proto_msgTypes[138] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11550,7 +11653,7 @@ func (x *VHTLCRecoveryStatus) String() string { func (*VHTLCRecoveryStatus) ProtoMessage() {} func (x *VHTLCRecoveryStatus) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[136] + mi := &file_daemon_proto_msgTypes[138] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11563,7 +11666,7 @@ func (x *VHTLCRecoveryStatus) ProtoReflect() protoreflect.Message { // Deprecated: Use VHTLCRecoveryStatus.ProtoReflect.Descriptor instead. func (*VHTLCRecoveryStatus) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{136} + return file_daemon_proto_rawDescGZIP(), []int{138} } func (x *VHTLCRecoveryStatus) GetRecoveryId() string { @@ -11755,7 +11858,7 @@ type SignOutSwapHtlcAckRequest struct { func (x *SignOutSwapHtlcAckRequest) Reset() { *x = SignOutSwapHtlcAckRequest{} - mi := &file_daemon_proto_msgTypes[137] + mi := &file_daemon_proto_msgTypes[139] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11767,7 +11870,7 @@ func (x *SignOutSwapHtlcAckRequest) String() string { func (*SignOutSwapHtlcAckRequest) ProtoMessage() {} func (x *SignOutSwapHtlcAckRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[137] + mi := &file_daemon_proto_msgTypes[139] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11780,7 +11883,7 @@ func (x *SignOutSwapHtlcAckRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SignOutSwapHtlcAckRequest.ProtoReflect.Descriptor instead. func (*SignOutSwapHtlcAckRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{137} + return file_daemon_proto_rawDescGZIP(), []int{139} } func (x *SignOutSwapHtlcAckRequest) GetPaymentHash() []byte { @@ -11814,7 +11917,7 @@ type SignOutSwapHtlcAckResponse struct { func (x *SignOutSwapHtlcAckResponse) Reset() { *x = SignOutSwapHtlcAckResponse{} - mi := &file_daemon_proto_msgTypes[138] + mi := &file_daemon_proto_msgTypes[140] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11826,7 +11929,7 @@ func (x *SignOutSwapHtlcAckResponse) String() string { func (*SignOutSwapHtlcAckResponse) ProtoMessage() {} func (x *SignOutSwapHtlcAckResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[138] + mi := &file_daemon_proto_msgTypes[140] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11839,7 +11942,7 @@ func (x *SignOutSwapHtlcAckResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SignOutSwapHtlcAckResponse.ProtoReflect.Descriptor instead. func (*SignOutSwapHtlcAckResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{138} + return file_daemon_proto_rawDescGZIP(), []int{140} } func (x *SignOutSwapHtlcAckResponse) GetSignature() []byte { @@ -11867,7 +11970,7 @@ type SignCreditAccountAuthorizationRequest struct { func (x *SignCreditAccountAuthorizationRequest) Reset() { *x = SignCreditAccountAuthorizationRequest{} - mi := &file_daemon_proto_msgTypes[139] + mi := &file_daemon_proto_msgTypes[141] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11879,7 +11982,7 @@ func (x *SignCreditAccountAuthorizationRequest) String() string { func (*SignCreditAccountAuthorizationRequest) ProtoMessage() {} func (x *SignCreditAccountAuthorizationRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[139] + mi := &file_daemon_proto_msgTypes[141] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11892,7 +11995,7 @@ func (x *SignCreditAccountAuthorizationRequest) ProtoReflect() protoreflect.Mess // Deprecated: Use SignCreditAccountAuthorizationRequest.ProtoReflect.Descriptor instead. func (*SignCreditAccountAuthorizationRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{139} + return file_daemon_proto_rawDescGZIP(), []int{141} } func (x *SignCreditAccountAuthorizationRequest) GetRequestDigest() []byte { @@ -11933,7 +12036,7 @@ type SignCreditAccountAuthorizationResponse struct { func (x *SignCreditAccountAuthorizationResponse) Reset() { *x = SignCreditAccountAuthorizationResponse{} - mi := &file_daemon_proto_msgTypes[140] + mi := &file_daemon_proto_msgTypes[142] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11945,7 +12048,7 @@ func (x *SignCreditAccountAuthorizationResponse) String() string { func (*SignCreditAccountAuthorizationResponse) ProtoMessage() {} func (x *SignCreditAccountAuthorizationResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[140] + mi := &file_daemon_proto_msgTypes[142] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11958,7 +12061,7 @@ func (x *SignCreditAccountAuthorizationResponse) ProtoReflect() protoreflect.Mes // Deprecated: Use SignCreditAccountAuthorizationResponse.ProtoReflect.Descriptor instead. func (*SignCreditAccountAuthorizationResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{140} + return file_daemon_proto_rawDescGZIP(), []int{142} } func (x *SignCreditAccountAuthorizationResponse) GetSignature() []byte { @@ -11982,7 +12085,7 @@ type MacaroonPermission struct { func (x *MacaroonPermission) Reset() { *x = MacaroonPermission{} - mi := &file_daemon_proto_msgTypes[141] + mi := &file_daemon_proto_msgTypes[143] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11994,7 +12097,7 @@ func (x *MacaroonPermission) String() string { func (*MacaroonPermission) ProtoMessage() {} func (x *MacaroonPermission) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[141] + mi := &file_daemon_proto_msgTypes[143] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12007,7 +12110,7 @@ func (x *MacaroonPermission) ProtoReflect() protoreflect.Message { // Deprecated: Use MacaroonPermission.ProtoReflect.Descriptor instead. func (*MacaroonPermission) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{141} + return file_daemon_proto_rawDescGZIP(), []int{143} } func (x *MacaroonPermission) GetEntity() string { @@ -12037,7 +12140,7 @@ type BakeMacaroonRequest struct { func (x *BakeMacaroonRequest) Reset() { *x = BakeMacaroonRequest{} - mi := &file_daemon_proto_msgTypes[142] + mi := &file_daemon_proto_msgTypes[144] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12049,7 +12152,7 @@ func (x *BakeMacaroonRequest) String() string { func (*BakeMacaroonRequest) ProtoMessage() {} func (x *BakeMacaroonRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[142] + mi := &file_daemon_proto_msgTypes[144] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12062,7 +12165,7 @@ func (x *BakeMacaroonRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use BakeMacaroonRequest.ProtoReflect.Descriptor instead. func (*BakeMacaroonRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{142} + return file_daemon_proto_rawDescGZIP(), []int{144} } func (x *BakeMacaroonRequest) GetPermissions() []*MacaroonPermission { @@ -12089,7 +12192,7 @@ type BakeMacaroonResponse struct { func (x *BakeMacaroonResponse) Reset() { *x = BakeMacaroonResponse{} - mi := &file_daemon_proto_msgTypes[143] + mi := &file_daemon_proto_msgTypes[145] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12101,7 +12204,7 @@ func (x *BakeMacaroonResponse) String() string { func (*BakeMacaroonResponse) ProtoMessage() {} func (x *BakeMacaroonResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[143] + mi := &file_daemon_proto_msgTypes[145] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12114,7 +12217,7 @@ func (x *BakeMacaroonResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use BakeMacaroonResponse.ProtoReflect.Descriptor instead. func (*BakeMacaroonResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{143} + return file_daemon_proto_rawDescGZIP(), []int{145} } func (x *BakeMacaroonResponse) GetMacaroon() string { @@ -12133,7 +12236,7 @@ type MacaroonPermissionList struct { func (x *MacaroonPermissionList) Reset() { *x = MacaroonPermissionList{} - mi := &file_daemon_proto_msgTypes[144] + mi := &file_daemon_proto_msgTypes[146] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12145,7 +12248,7 @@ func (x *MacaroonPermissionList) String() string { func (*MacaroonPermissionList) ProtoMessage() {} func (x *MacaroonPermissionList) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[144] + mi := &file_daemon_proto_msgTypes[146] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12158,7 +12261,7 @@ func (x *MacaroonPermissionList) ProtoReflect() protoreflect.Message { // Deprecated: Use MacaroonPermissionList.ProtoReflect.Descriptor instead. func (*MacaroonPermissionList) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{144} + return file_daemon_proto_rawDescGZIP(), []int{146} } func (x *MacaroonPermissionList) GetPermissions() []*MacaroonPermission { @@ -12176,7 +12279,7 @@ type ListPermissionsRequest struct { func (x *ListPermissionsRequest) Reset() { *x = ListPermissionsRequest{} - mi := &file_daemon_proto_msgTypes[145] + mi := &file_daemon_proto_msgTypes[147] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12188,7 +12291,7 @@ func (x *ListPermissionsRequest) String() string { func (*ListPermissionsRequest) ProtoMessage() {} func (x *ListPermissionsRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[145] + mi := &file_daemon_proto_msgTypes[147] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12201,7 +12304,7 @@ func (x *ListPermissionsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListPermissionsRequest.ProtoReflect.Descriptor instead. func (*ListPermissionsRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{145} + return file_daemon_proto_rawDescGZIP(), []int{147} } type ListPermissionsResponse struct { @@ -12215,7 +12318,7 @@ type ListPermissionsResponse struct { func (x *ListPermissionsResponse) Reset() { *x = ListPermissionsResponse{} - mi := &file_daemon_proto_msgTypes[146] + mi := &file_daemon_proto_msgTypes[148] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12227,7 +12330,7 @@ func (x *ListPermissionsResponse) String() string { func (*ListPermissionsResponse) ProtoMessage() {} func (x *ListPermissionsResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[146] + mi := &file_daemon_proto_msgTypes[148] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12240,7 +12343,7 @@ func (x *ListPermissionsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListPermissionsResponse.ProtoReflect.Descriptor instead. func (*ListPermissionsResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{146} + return file_daemon_proto_rawDescGZIP(), []int{148} } func (x *ListPermissionsResponse) GetMethodPermissions() map[string]*MacaroonPermissionList { @@ -12260,7 +12363,7 @@ type DeriveSwapPreimageRequest struct { func (x *DeriveSwapPreimageRequest) Reset() { *x = DeriveSwapPreimageRequest{} - mi := &file_daemon_proto_msgTypes[147] + mi := &file_daemon_proto_msgTypes[149] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12272,7 +12375,7 @@ func (x *DeriveSwapPreimageRequest) String() string { func (*DeriveSwapPreimageRequest) ProtoMessage() {} func (x *DeriveSwapPreimageRequest) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[147] + mi := &file_daemon_proto_msgTypes[149] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12285,7 +12388,7 @@ func (x *DeriveSwapPreimageRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeriveSwapPreimageRequest.ProtoReflect.Descriptor instead. func (*DeriveSwapPreimageRequest) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{147} + return file_daemon_proto_rawDescGZIP(), []int{149} } func (x *DeriveSwapPreimageRequest) GetRecoveryParams() []byte { @@ -12305,7 +12408,7 @@ type DeriveSwapPreimageResponse struct { func (x *DeriveSwapPreimageResponse) Reset() { *x = DeriveSwapPreimageResponse{} - mi := &file_daemon_proto_msgTypes[148] + mi := &file_daemon_proto_msgTypes[150] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12317,7 +12420,7 @@ func (x *DeriveSwapPreimageResponse) String() string { func (*DeriveSwapPreimageResponse) ProtoMessage() {} func (x *DeriveSwapPreimageResponse) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[148] + mi := &file_daemon_proto_msgTypes[150] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12330,7 +12433,7 @@ func (x *DeriveSwapPreimageResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeriveSwapPreimageResponse.ProtoReflect.Descriptor instead. func (*DeriveSwapPreimageResponse) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{148} + return file_daemon_proto_rawDescGZIP(), []int{150} } func (x *DeriveSwapPreimageResponse) GetPreimage() []byte { @@ -12354,7 +12457,7 @@ type CooperativeOORPackage struct { func (x *CooperativeOORPackage) Reset() { *x = CooperativeOORPackage{} - mi := &file_daemon_proto_msgTypes[149] + mi := &file_daemon_proto_msgTypes[151] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12366,7 +12469,7 @@ func (x *CooperativeOORPackage) String() string { func (*CooperativeOORPackage) ProtoMessage() {} func (x *CooperativeOORPackage) ProtoReflect() protoreflect.Message { - mi := &file_daemon_proto_msgTypes[149] + mi := &file_daemon_proto_msgTypes[151] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12379,7 +12482,7 @@ func (x *CooperativeOORPackage) ProtoReflect() protoreflect.Message { // Deprecated: Use CooperativeOORPackage.ProtoReflect.Descriptor instead. func (*CooperativeOORPackage) Descriptor() ([]byte, []int) { - return file_daemon_proto_rawDescGZIP(), []int{149} + return file_daemon_proto_rawDescGZIP(), []int{151} } func (x *CooperativeOORPackage) GetCustomInput() *CustomOORInput { @@ -12414,7 +12517,7 @@ var File_daemon_proto protoreflect.FileDescriptor const file_daemon_proto_rawDesc = "" + "\n" + - "\fdaemon.proto\x12\awaverpc\"\x10\n" + + "\fdaemon.proto\x12\awaverpc\x1a#rpc/arkchannelrpc/ark_channel.proto\"\x10\n" + "\x0eGetInfoRequest\"\xb1\x03\n" + "\x0fGetInfoResponse\x12\x18\n" + "\aversion\x18\x01 \x01(\tR\aversion\x12\x16\n" + @@ -12544,10 +12647,11 @@ const file_daemon_proto_rawDesc = "" + "\x05vtxos\x18\x01 \x03(\v2\r.waverpc.VTXOR\x05vtxos\"\x13\n" + "\x11NewAddressRequest\".\n" + "\x12NewAddressResponse\x12\x18\n" + - "\aaddress\x18\x01 \x01(\tR\aaddress\"X\n" + + "\aaddress\x18\x01 \x01(\tR\aaddress\"{\n" + "\x17NewReceiveScriptRequest\x12\x14\n" + "\x05label\x18\x01 \x01(\tR\x05label\x12'\n" + - "\x0fidempotency_key\x18\x02 \x01(\tR\x0eidempotencyKey\"\xe5\x01\n" + + "\x0fidempotency_key\x18\x02 \x01(\tR\x0eidempotencyKey\x12!\n" + + "\fidentity_key\x18\x03 \x01(\bR\videntityKey\"\xe5\x01\n" + "\x18NewReceiveScriptResponse\x12\"\n" + "\rpk_script_hex\x18\x01 \x01(\tR\vpkScriptHex\x12(\n" + "\x10pubkey_xonly_hex\x18\x02 \x01(\tR\x0epubkeyXonlyHex\x12\x1d\n" + @@ -12675,7 +12779,11 @@ const file_daemon_proto_rawDesc = "" + "\x10checkpoint_psbts\x18\x02 \x03(\fR\x0fcheckpointPsbts\x12D\n" + "\rcustom_inputs\x18\x03 \x03(\v2\x1f.waverpc.PreparedOORCustomInputR\fcustomInputs\x12\x1d\n" + "\n" + - "session_id\x18\x04 \x01(\tR\tsessionId\"\xd1\x01\n" + + "session_id\x18\x04 \x01(\tR\tsessionId\"[\n" + + "\x1fExportOORRecoveryPackageRequest\x128\n" + + "\x06source\x18\x01 \x01(\v2 .arkchannelrpc.OORRecoverySourceR\x06source\"e\n" + + " ExportOORRecoveryPackageResponse\x12A\n" + + "\brecovery\x18\x01 \x01(\v2%.arkchannelrpc.ChannelRecoveryPackageR\brecovery\"\xd1\x01\n" + "\x19SignOORCustomInputRequest\x12:\n" + "\fcustom_input\x18\x01 \x01(\v2\x17.waverpc.CustomOORInputR\vcustomInput\x12'\n" + "\x0fcheckpoint_psbt\x18\x02 \x01(\fR\x0echeckpointPsbt\x12O\n" + @@ -13368,7 +13476,7 @@ const file_daemon_proto_rawDesc = "" + "\x1eVHTLC_RECOVERY_STATE_COMPLETED\x10\t\x12\"\n" + "\x1eVHTLC_RECOVERY_STATE_CANCELLED\x10\n" + "\x12\x1f\n" + - "\x1bVHTLC_RECOVERY_STATE_FAILED\x10\v2\x8d'\n" + + "\x1bVHTLC_RECOVERY_STATE_FAILED\x10\v2\xfe'\n" + "\rDaemonService\x12<\n" + "\aGetInfo\x12\x17.waverpc.GetInfoRequest\x1a\x18.waverpc.GetInfoResponse\x12<\n" + "\aGenSeed\x12\x17.waverpc.GenSeedRequest\x1a\x18.waverpc.GenSeedResponse\x12E\n" + @@ -13389,7 +13497,8 @@ const file_daemon_proto_rawDesc = "" + "\x12DeriveSwapPreimage\x12\".waverpc.DeriveSwapPreimageRequest\x1a#.waverpc.DeriveSwapPreimageResponse\x12o\n" + "\x18GetIndexedVTXOByPkScript\x12(.waverpc.GetIndexedVTXOByPkScriptRequest\x1a).waverpc.GetIndexedVTXOByPkScriptResponse\x12Z\n" + "\x11GetVTXOExpiryInfo\x12!.waverpc.GetVTXOExpiryInfoRequest\x1a\".waverpc.GetVTXOExpiryInfoResponse\x12u\n" + - "\x1aGetIndexedOORSessionByTxid\x12*.waverpc.GetIndexedOORSessionByTxidRequest\x1a+.waverpc.GetIndexedOORSessionByTxidResponse\x12?\n" + + "\x1aGetIndexedOORSessionByTxid\x12*.waverpc.GetIndexedOORSessionByTxidRequest\x1a+.waverpc.GetIndexedOORSessionByTxidResponse\x12o\n" + + "\x18ExportOORRecoveryPackage\x12(.waverpc.ExportOORRecoveryPackageRequest\x1a).waverpc.ExportOORRecoveryPackageResponse\x12?\n" + "\bSendVTXO\x12\x18.waverpc.SendVTXORequest\x1a\x19.waverpc.SendVTXOResponse\x12<\n" + "\aSendOOR\x12\x17.waverpc.SendOORRequest\x1a\x18.waverpc.SendOORResponse\x12E\n" + "\n" + @@ -13450,7 +13559,7 @@ func file_daemon_proto_rawDescGZIP() []byte { } var file_daemon_proto_enumTypes = make([]protoimpl.EnumInfo, 12) -var file_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 153) +var file_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 155) var file_daemon_proto_goTypes = []any{ (WalletState)(0), // 0: waverpc.WalletState (VTXOStatus)(0), // 1: waverpc.VTXOStatus @@ -13511,112 +13620,116 @@ var file_daemon_proto_goTypes = []any{ (*PrepareOORRequest)(nil), // 56: waverpc.PrepareOORRequest (*PreparedOORCustomInput)(nil), // 57: waverpc.PreparedOORCustomInput (*PrepareOORResponse)(nil), // 58: waverpc.PrepareOORResponse - (*SignOORCustomInputRequest)(nil), // 59: waverpc.SignOORCustomInputRequest - (*SignOORCustomInputResponse)(nil), // 60: waverpc.SignOORCustomInputResponse - (*SignVTXOForfeitRequest)(nil), // 61: waverpc.SignVTXOForfeitRequest - (*SignVTXOForfeitResponse)(nil), // 62: waverpc.SignVTXOForfeitResponse - (*ForfeitSigningContext)(nil), // 63: waverpc.ForfeitSigningContext - (*OutpointSelection)(nil), // 64: waverpc.OutpointSelection - (*RefreshVTXOsRequest)(nil), // 65: waverpc.RefreshVTXOsRequest - (*RefreshVTXOsResponse)(nil), // 66: waverpc.RefreshVTXOsResponse - (*RefreshFeeEstimate)(nil), // 67: waverpc.RefreshFeeEstimate - (*OutpointFeeEstimate)(nil), // 68: waverpc.OutpointFeeEstimate - (*CustomRefreshVTXOInput)(nil), // 69: waverpc.CustomRefreshVTXOInput - (*CustomRefreshVTXOOutput)(nil), // 70: waverpc.CustomRefreshVTXOOutput - (*RefreshCustomVTXOsRequest)(nil), // 71: waverpc.RefreshCustomVTXOsRequest - (*RefreshCustomVTXOsResponse)(nil), // 72: waverpc.RefreshCustomVTXOsResponse - (*PendingForfeitParticipantSignatureRequest)(nil), // 73: waverpc.PendingForfeitParticipantSignatureRequest - (*ListPendingForfeitParticipantSignatureRequestsRequest)(nil), // 74: waverpc.ListPendingForfeitParticipantSignatureRequestsRequest - (*ListPendingForfeitParticipantSignatureRequestsResponse)(nil), // 75: waverpc.ListPendingForfeitParticipantSignatureRequestsResponse - (*ForfeitParticipantSignature)(nil), // 76: waverpc.ForfeitParticipantSignature - (*SubmitForfeitParticipantSignaturesRequest)(nil), // 77: waverpc.SubmitForfeitParticipantSignaturesRequest - (*SubmitForfeitParticipantSignaturesResponse)(nil), // 78: waverpc.SubmitForfeitParticipantSignaturesResponse - (*LeaveDestination)(nil), // 79: waverpc.LeaveDestination - (*LeaveVTXOsRequest)(nil), // 80: waverpc.LeaveVTXOsRequest - (*LeaveVTXOsResponse)(nil), // 81: waverpc.LeaveVTXOsResponse - (*SendOnChainRequest)(nil), // 82: waverpc.SendOnChainRequest - (*SendOnChainResponse)(nil), // 83: waverpc.SendOnChainResponse - (*BoardRequest)(nil), // 84: waverpc.BoardRequest - (*BoardResponse)(nil), // 85: waverpc.BoardResponse - (*DepositAssetRequest)(nil), // 86: waverpc.DepositAssetRequest - (*ListAssetDepositsRequest)(nil), // 87: waverpc.ListAssetDepositsRequest - (*BoardAssetDepositRequest)(nil), // 88: waverpc.BoardAssetDepositRequest - (*ClaimAssetDepositRequest)(nil), // 89: waverpc.ClaimAssetDepositRequest - (*ListAssetDepositsResponse)(nil), // 90: waverpc.ListAssetDepositsResponse - (*AssetDeposit)(nil), // 91: waverpc.AssetDeposit - (*NewAssetReceiveKeysRequest)(nil), // 92: waverpc.NewAssetReceiveKeysRequest - (*AssetReceiveKeys)(nil), // 93: waverpc.AssetReceiveKeys - (*ImportAssetProofRequest)(nil), // 94: waverpc.ImportAssetProofRequest - (*NewAssetFundingAddressRequest)(nil), // 95: waverpc.NewAssetFundingAddressRequest - (*AssetFundingAddress)(nil), // 96: waverpc.AssetFundingAddress - (*ListOwnedAssetsRequest)(nil), // 97: waverpc.ListOwnedAssetsRequest - (*ListOwnedAssetsResponse)(nil), // 98: waverpc.ListOwnedAssetsResponse - (*OwnedAsset)(nil), // 99: waverpc.OwnedAsset - (*JoinNextRoundRequest)(nil), // 100: waverpc.JoinNextRoundRequest - (*JoinNextRoundResponse)(nil), // 101: waverpc.JoinNextRoundResponse - (*SweepBoardingUTXOsRequest)(nil), // 102: waverpc.SweepBoardingUTXOsRequest - (*BoardingSweepOutput)(nil), // 103: waverpc.BoardingSweepOutput - (*SweepBoardingUTXOsResponse)(nil), // 104: waverpc.SweepBoardingUTXOsResponse - (*ListBoardingSweepsRequest)(nil), // 105: waverpc.ListBoardingSweepsRequest - (*BoardingSweepInput)(nil), // 106: waverpc.BoardingSweepInput - (*BoardingSweep)(nil), // 107: waverpc.BoardingSweep - (*ListBoardingSweepsResponse)(nil), // 108: waverpc.ListBoardingSweepsResponse - (*RoundVTXOInfo)(nil), // 109: waverpc.RoundVTXOInfo - (*ScheduledBatchWindow)(nil), // 110: waverpc.ScheduledBatchWindow - (*RoundInfo)(nil), // 111: waverpc.RoundInfo - (*ListRoundsRequest)(nil), // 112: waverpc.ListRoundsRequest - (*GetRoundRequest)(nil), // 113: waverpc.GetRoundRequest - (*GetRoundResponse)(nil), // 114: waverpc.GetRoundResponse - (*ListRoundsResponse)(nil), // 115: waverpc.ListRoundsResponse - (*WatchRoundsRequest)(nil), // 116: waverpc.WatchRoundsRequest - (*WatchRoundsResponse)(nil), // 117: waverpc.WatchRoundsResponse - (*OORSessionInfo)(nil), // 118: waverpc.OORSessionInfo - (*ListOORSessionsRequest)(nil), // 119: waverpc.ListOORSessionsRequest - (*ListOORSessionsResponse)(nil), // 120: waverpc.ListOORSessionsResponse - (*GetOORSessionRequest)(nil), // 121: waverpc.GetOORSessionRequest - (*GetOORSessionResponse)(nil), // 122: waverpc.GetOORSessionResponse - (*EstimateFeeRequest)(nil), // 123: waverpc.EstimateFeeRequest - (*EstimateFeeResponse)(nil), // 124: waverpc.EstimateFeeResponse - (*GetFeeHistoryRequest)(nil), // 125: waverpc.GetFeeHistoryRequest - (*FeeHistoryEntry)(nil), // 126: waverpc.FeeHistoryEntry - (*GetFeeHistoryResponse)(nil), // 127: waverpc.GetFeeHistoryResponse - (*ListTransactionsRequest)(nil), // 128: waverpc.ListTransactionsRequest - (*TransactionHistoryEntry)(nil), // 129: waverpc.TransactionHistoryEntry - (*ListTransactionsResponse)(nil), // 130: waverpc.ListTransactionsResponse - (*UnrollRequest)(nil), // 131: waverpc.UnrollRequest - (*UnrollResponse)(nil), // 132: waverpc.UnrollResponse - (*GetUnrollStatusRequest)(nil), // 133: waverpc.GetUnrollStatusRequest - (*UnrollProgress)(nil), // 134: waverpc.UnrollProgress - (*UnrollCSV)(nil), // 135: waverpc.UnrollCSV - (*UnrollFees)(nil), // 136: waverpc.UnrollFees - (*GetUnrollStatusResponse)(nil), // 137: waverpc.GetUnrollStatusResponse - (*ArmVHTLCRecoveryRequest)(nil), // 138: waverpc.ArmVHTLCRecoveryRequest - (*ArmVHTLCRecoveryResponse)(nil), // 139: waverpc.ArmVHTLCRecoveryResponse - (*EscalateVHTLCRecoveryRequest)(nil), // 140: waverpc.EscalateVHTLCRecoveryRequest - (*EscalateVHTLCRecoveryResponse)(nil), // 141: waverpc.EscalateVHTLCRecoveryResponse - (*CancelVHTLCRecoveryRequest)(nil), // 142: waverpc.CancelVHTLCRecoveryRequest - (*CancelVHTLCRecoveryResponse)(nil), // 143: waverpc.CancelVHTLCRecoveryResponse - (*GetVHTLCRecoveryStatusRequest)(nil), // 144: waverpc.GetVHTLCRecoveryStatusRequest - (*GetVHTLCRecoveryStatusResponse)(nil), // 145: waverpc.GetVHTLCRecoveryStatusResponse - (*ListVHTLCRecoveriesRequest)(nil), // 146: waverpc.ListVHTLCRecoveriesRequest - (*ListVHTLCRecoveriesResponse)(nil), // 147: waverpc.ListVHTLCRecoveriesResponse - (*VHTLCRecoveryStatus)(nil), // 148: waverpc.VHTLCRecoveryStatus - (*SignOutSwapHtlcAckRequest)(nil), // 149: waverpc.SignOutSwapHtlcAckRequest - (*SignOutSwapHtlcAckResponse)(nil), // 150: waverpc.SignOutSwapHtlcAckResponse - (*SignCreditAccountAuthorizationRequest)(nil), // 151: waverpc.SignCreditAccountAuthorizationRequest - (*SignCreditAccountAuthorizationResponse)(nil), // 152: waverpc.SignCreditAccountAuthorizationResponse - (*MacaroonPermission)(nil), // 153: waverpc.MacaroonPermission - (*BakeMacaroonRequest)(nil), // 154: waverpc.BakeMacaroonRequest - (*BakeMacaroonResponse)(nil), // 155: waverpc.BakeMacaroonResponse - (*MacaroonPermissionList)(nil), // 156: waverpc.MacaroonPermissionList - (*ListPermissionsRequest)(nil), // 157: waverpc.ListPermissionsRequest - (*ListPermissionsResponse)(nil), // 158: waverpc.ListPermissionsResponse - (*DeriveSwapPreimageRequest)(nil), // 159: waverpc.DeriveSwapPreimageRequest - (*DeriveSwapPreimageResponse)(nil), // 160: waverpc.DeriveSwapPreimageResponse - (*CooperativeOORPackage)(nil), // 161: waverpc.CooperativeOORPackage - nil, // 162: waverpc.LeaveVTXOsRequest.DestinationsEntry - nil, // 163: waverpc.LeaveVTXOsResponse.ErrorsEntry - nil, // 164: waverpc.ListPermissionsResponse.MethodPermissionsEntry + (*ExportOORRecoveryPackageRequest)(nil), // 59: waverpc.ExportOORRecoveryPackageRequest + (*ExportOORRecoveryPackageResponse)(nil), // 60: waverpc.ExportOORRecoveryPackageResponse + (*SignOORCustomInputRequest)(nil), // 61: waverpc.SignOORCustomInputRequest + (*SignOORCustomInputResponse)(nil), // 62: waverpc.SignOORCustomInputResponse + (*SignVTXOForfeitRequest)(nil), // 63: waverpc.SignVTXOForfeitRequest + (*SignVTXOForfeitResponse)(nil), // 64: waverpc.SignVTXOForfeitResponse + (*ForfeitSigningContext)(nil), // 65: waverpc.ForfeitSigningContext + (*OutpointSelection)(nil), // 66: waverpc.OutpointSelection + (*RefreshVTXOsRequest)(nil), // 67: waverpc.RefreshVTXOsRequest + (*RefreshVTXOsResponse)(nil), // 68: waverpc.RefreshVTXOsResponse + (*RefreshFeeEstimate)(nil), // 69: waverpc.RefreshFeeEstimate + (*OutpointFeeEstimate)(nil), // 70: waverpc.OutpointFeeEstimate + (*CustomRefreshVTXOInput)(nil), // 71: waverpc.CustomRefreshVTXOInput + (*CustomRefreshVTXOOutput)(nil), // 72: waverpc.CustomRefreshVTXOOutput + (*RefreshCustomVTXOsRequest)(nil), // 73: waverpc.RefreshCustomVTXOsRequest + (*RefreshCustomVTXOsResponse)(nil), // 74: waverpc.RefreshCustomVTXOsResponse + (*PendingForfeitParticipantSignatureRequest)(nil), // 75: waverpc.PendingForfeitParticipantSignatureRequest + (*ListPendingForfeitParticipantSignatureRequestsRequest)(nil), // 76: waverpc.ListPendingForfeitParticipantSignatureRequestsRequest + (*ListPendingForfeitParticipantSignatureRequestsResponse)(nil), // 77: waverpc.ListPendingForfeitParticipantSignatureRequestsResponse + (*ForfeitParticipantSignature)(nil), // 78: waverpc.ForfeitParticipantSignature + (*SubmitForfeitParticipantSignaturesRequest)(nil), // 79: waverpc.SubmitForfeitParticipantSignaturesRequest + (*SubmitForfeitParticipantSignaturesResponse)(nil), // 80: waverpc.SubmitForfeitParticipantSignaturesResponse + (*LeaveDestination)(nil), // 81: waverpc.LeaveDestination + (*LeaveVTXOsRequest)(nil), // 82: waverpc.LeaveVTXOsRequest + (*LeaveVTXOsResponse)(nil), // 83: waverpc.LeaveVTXOsResponse + (*SendOnChainRequest)(nil), // 84: waverpc.SendOnChainRequest + (*SendOnChainResponse)(nil), // 85: waverpc.SendOnChainResponse + (*BoardRequest)(nil), // 86: waverpc.BoardRequest + (*BoardResponse)(nil), // 87: waverpc.BoardResponse + (*DepositAssetRequest)(nil), // 88: waverpc.DepositAssetRequest + (*ListAssetDepositsRequest)(nil), // 89: waverpc.ListAssetDepositsRequest + (*BoardAssetDepositRequest)(nil), // 90: waverpc.BoardAssetDepositRequest + (*ClaimAssetDepositRequest)(nil), // 91: waverpc.ClaimAssetDepositRequest + (*ListAssetDepositsResponse)(nil), // 92: waverpc.ListAssetDepositsResponse + (*AssetDeposit)(nil), // 93: waverpc.AssetDeposit + (*NewAssetReceiveKeysRequest)(nil), // 94: waverpc.NewAssetReceiveKeysRequest + (*AssetReceiveKeys)(nil), // 95: waverpc.AssetReceiveKeys + (*ImportAssetProofRequest)(nil), // 96: waverpc.ImportAssetProofRequest + (*NewAssetFundingAddressRequest)(nil), // 97: waverpc.NewAssetFundingAddressRequest + (*AssetFundingAddress)(nil), // 98: waverpc.AssetFundingAddress + (*ListOwnedAssetsRequest)(nil), // 99: waverpc.ListOwnedAssetsRequest + (*ListOwnedAssetsResponse)(nil), // 100: waverpc.ListOwnedAssetsResponse + (*OwnedAsset)(nil), // 101: waverpc.OwnedAsset + (*JoinNextRoundRequest)(nil), // 102: waverpc.JoinNextRoundRequest + (*JoinNextRoundResponse)(nil), // 103: waverpc.JoinNextRoundResponse + (*SweepBoardingUTXOsRequest)(nil), // 104: waverpc.SweepBoardingUTXOsRequest + (*BoardingSweepOutput)(nil), // 105: waverpc.BoardingSweepOutput + (*SweepBoardingUTXOsResponse)(nil), // 106: waverpc.SweepBoardingUTXOsResponse + (*ListBoardingSweepsRequest)(nil), // 107: waverpc.ListBoardingSweepsRequest + (*BoardingSweepInput)(nil), // 108: waverpc.BoardingSweepInput + (*BoardingSweep)(nil), // 109: waverpc.BoardingSweep + (*ListBoardingSweepsResponse)(nil), // 110: waverpc.ListBoardingSweepsResponse + (*RoundVTXOInfo)(nil), // 111: waverpc.RoundVTXOInfo + (*ScheduledBatchWindow)(nil), // 112: waverpc.ScheduledBatchWindow + (*RoundInfo)(nil), // 113: waverpc.RoundInfo + (*ListRoundsRequest)(nil), // 114: waverpc.ListRoundsRequest + (*GetRoundRequest)(nil), // 115: waverpc.GetRoundRequest + (*GetRoundResponse)(nil), // 116: waverpc.GetRoundResponse + (*ListRoundsResponse)(nil), // 117: waverpc.ListRoundsResponse + (*WatchRoundsRequest)(nil), // 118: waverpc.WatchRoundsRequest + (*WatchRoundsResponse)(nil), // 119: waverpc.WatchRoundsResponse + (*OORSessionInfo)(nil), // 120: waverpc.OORSessionInfo + (*ListOORSessionsRequest)(nil), // 121: waverpc.ListOORSessionsRequest + (*ListOORSessionsResponse)(nil), // 122: waverpc.ListOORSessionsResponse + (*GetOORSessionRequest)(nil), // 123: waverpc.GetOORSessionRequest + (*GetOORSessionResponse)(nil), // 124: waverpc.GetOORSessionResponse + (*EstimateFeeRequest)(nil), // 125: waverpc.EstimateFeeRequest + (*EstimateFeeResponse)(nil), // 126: waverpc.EstimateFeeResponse + (*GetFeeHistoryRequest)(nil), // 127: waverpc.GetFeeHistoryRequest + (*FeeHistoryEntry)(nil), // 128: waverpc.FeeHistoryEntry + (*GetFeeHistoryResponse)(nil), // 129: waverpc.GetFeeHistoryResponse + (*ListTransactionsRequest)(nil), // 130: waverpc.ListTransactionsRequest + (*TransactionHistoryEntry)(nil), // 131: waverpc.TransactionHistoryEntry + (*ListTransactionsResponse)(nil), // 132: waverpc.ListTransactionsResponse + (*UnrollRequest)(nil), // 133: waverpc.UnrollRequest + (*UnrollResponse)(nil), // 134: waverpc.UnrollResponse + (*GetUnrollStatusRequest)(nil), // 135: waverpc.GetUnrollStatusRequest + (*UnrollProgress)(nil), // 136: waverpc.UnrollProgress + (*UnrollCSV)(nil), // 137: waverpc.UnrollCSV + (*UnrollFees)(nil), // 138: waverpc.UnrollFees + (*GetUnrollStatusResponse)(nil), // 139: waverpc.GetUnrollStatusResponse + (*ArmVHTLCRecoveryRequest)(nil), // 140: waverpc.ArmVHTLCRecoveryRequest + (*ArmVHTLCRecoveryResponse)(nil), // 141: waverpc.ArmVHTLCRecoveryResponse + (*EscalateVHTLCRecoveryRequest)(nil), // 142: waverpc.EscalateVHTLCRecoveryRequest + (*EscalateVHTLCRecoveryResponse)(nil), // 143: waverpc.EscalateVHTLCRecoveryResponse + (*CancelVHTLCRecoveryRequest)(nil), // 144: waverpc.CancelVHTLCRecoveryRequest + (*CancelVHTLCRecoveryResponse)(nil), // 145: waverpc.CancelVHTLCRecoveryResponse + (*GetVHTLCRecoveryStatusRequest)(nil), // 146: waverpc.GetVHTLCRecoveryStatusRequest + (*GetVHTLCRecoveryStatusResponse)(nil), // 147: waverpc.GetVHTLCRecoveryStatusResponse + (*ListVHTLCRecoveriesRequest)(nil), // 148: waverpc.ListVHTLCRecoveriesRequest + (*ListVHTLCRecoveriesResponse)(nil), // 149: waverpc.ListVHTLCRecoveriesResponse + (*VHTLCRecoveryStatus)(nil), // 150: waverpc.VHTLCRecoveryStatus + (*SignOutSwapHtlcAckRequest)(nil), // 151: waverpc.SignOutSwapHtlcAckRequest + (*SignOutSwapHtlcAckResponse)(nil), // 152: waverpc.SignOutSwapHtlcAckResponse + (*SignCreditAccountAuthorizationRequest)(nil), // 153: waverpc.SignCreditAccountAuthorizationRequest + (*SignCreditAccountAuthorizationResponse)(nil), // 154: waverpc.SignCreditAccountAuthorizationResponse + (*MacaroonPermission)(nil), // 155: waverpc.MacaroonPermission + (*BakeMacaroonRequest)(nil), // 156: waverpc.BakeMacaroonRequest + (*BakeMacaroonResponse)(nil), // 157: waverpc.BakeMacaroonResponse + (*MacaroonPermissionList)(nil), // 158: waverpc.MacaroonPermissionList + (*ListPermissionsRequest)(nil), // 159: waverpc.ListPermissionsRequest + (*ListPermissionsResponse)(nil), // 160: waverpc.ListPermissionsResponse + (*DeriveSwapPreimageRequest)(nil), // 161: waverpc.DeriveSwapPreimageRequest + (*DeriveSwapPreimageResponse)(nil), // 162: waverpc.DeriveSwapPreimageResponse + (*CooperativeOORPackage)(nil), // 163: waverpc.CooperativeOORPackage + nil, // 164: waverpc.LeaveVTXOsRequest.DestinationsEntry + nil, // 165: waverpc.LeaveVTXOsResponse.ErrorsEntry + nil, // 166: waverpc.ListPermissionsResponse.MethodPermissionsEntry + (*arkchannelrpc.OORRecoverySource)(nil), // 167: arkchannelrpc.OORRecoverySource + (*arkchannelrpc.ChannelRecoveryPackage)(nil), // 168: arkchannelrpc.ChannelRecoveryPackage } var file_daemon_proto_depIdxs = []int32{ 0, // 0: waverpc.GetInfoResponse.wallet_state:type_name -> waverpc.WalletState @@ -13642,191 +13755,195 @@ var file_daemon_proto_depIdxs = []int32{ 49, // 20: waverpc.PrepareOORRequest.recipient:type_name -> waverpc.Output 53, // 21: waverpc.PrepareOORRequest.custom_inputs:type_name -> waverpc.CustomOORInput 57, // 22: waverpc.PrepareOORResponse.custom_inputs:type_name -> waverpc.PreparedOORCustomInput - 53, // 23: waverpc.SignOORCustomInputRequest.custom_input:type_name -> waverpc.CustomOORInput - 161, // 24: waverpc.SignOORCustomInputRequest.cooperative_package:type_name -> waverpc.CooperativeOORPackage - 54, // 25: waverpc.SignOORCustomInputResponse.signature:type_name -> waverpc.TaprootScriptSignature - 54, // 26: waverpc.SignOORCustomInputResponse.payout_signature:type_name -> waverpc.TaprootScriptSignature - 3, // 27: waverpc.ForfeitSigningContext.signing_route:type_name -> waverpc.ForfeitSigningRoute - 64, // 28: waverpc.RefreshVTXOsRequest.outpoints:type_name -> waverpc.OutpointSelection - 67, // 29: waverpc.RefreshVTXOsResponse.fee_estimate:type_name -> waverpc.RefreshFeeEstimate - 68, // 30: waverpc.RefreshFeeEstimate.outpoints:type_name -> waverpc.OutpointFeeEstimate - 63, // 31: waverpc.CustomRefreshVTXOInput.forfeit_signing_context:type_name -> waverpc.ForfeitSigningContext - 69, // 32: waverpc.RefreshCustomVTXOsRequest.inputs:type_name -> waverpc.CustomRefreshVTXOInput - 70, // 33: waverpc.RefreshCustomVTXOsRequest.outputs:type_name -> waverpc.CustomRefreshVTXOOutput - 3, // 34: waverpc.PendingForfeitParticipantSignatureRequest.signing_route:type_name -> waverpc.ForfeitSigningRoute - 73, // 35: waverpc.ListPendingForfeitParticipantSignatureRequestsResponse.requests:type_name -> waverpc.PendingForfeitParticipantSignatureRequest - 76, // 36: waverpc.SubmitForfeitParticipantSignaturesRequest.signatures:type_name -> waverpc.ForfeitParticipantSignature - 64, // 37: waverpc.LeaveVTXOsRequest.outpoints:type_name -> waverpc.OutpointSelection - 79, // 38: waverpc.LeaveVTXOsRequest.default_destination:type_name -> waverpc.LeaveDestination - 162, // 39: waverpc.LeaveVTXOsRequest.destinations:type_name -> waverpc.LeaveVTXOsRequest.DestinationsEntry - 163, // 40: waverpc.LeaveVTXOsResponse.errors:type_name -> waverpc.LeaveVTXOsResponse.ErrorsEntry - 79, // 41: waverpc.SendOnChainRequest.destination:type_name -> waverpc.LeaveDestination - 91, // 42: waverpc.ListAssetDepositsResponse.deposits:type_name -> waverpc.AssetDeposit - 4, // 43: waverpc.AssetDeposit.status:type_name -> waverpc.AssetDepositStatus - 99, // 44: waverpc.ListOwnedAssetsResponse.assets:type_name -> waverpc.OwnedAsset - 103, // 45: waverpc.SweepBoardingUTXOsResponse.sweepable_outputs:type_name -> waverpc.BoardingSweepOutput - 106, // 46: waverpc.BoardingSweep.inputs:type_name -> waverpc.BoardingSweepInput - 107, // 47: waverpc.ListBoardingSweepsResponse.sweeps:type_name -> waverpc.BoardingSweep - 5, // 48: waverpc.RoundInfo.state:type_name -> waverpc.RoundState - 109, // 49: waverpc.RoundInfo.vtxos:type_name -> waverpc.RoundVTXOInfo - 110, // 50: waverpc.RoundInfo.batch_window:type_name -> waverpc.ScheduledBatchWindow - 5, // 51: waverpc.ListRoundsRequest.state_filter:type_name -> waverpc.RoundState - 111, // 52: waverpc.GetRoundResponse.round:type_name -> waverpc.RoundInfo - 111, // 53: waverpc.ListRoundsResponse.rounds:type_name -> waverpc.RoundInfo - 111, // 54: waverpc.WatchRoundsResponse.round:type_name -> waverpc.RoundInfo - 6, // 55: waverpc.OORSessionInfo.direction:type_name -> waverpc.OORSessionDirection - 7, // 56: waverpc.OORSessionInfo.status:type_name -> waverpc.OORSessionStatus - 6, // 57: waverpc.ListOORSessionsRequest.direction_filter:type_name -> waverpc.OORSessionDirection - 7, // 58: waverpc.ListOORSessionsRequest.status_filter:type_name -> waverpc.OORSessionStatus - 118, // 59: waverpc.ListOORSessionsResponse.sessions:type_name -> waverpc.OORSessionInfo - 118, // 60: waverpc.GetOORSessionResponse.session:type_name -> waverpc.OORSessionInfo - 126, // 61: waverpc.GetFeeHistoryResponse.entries:type_name -> waverpc.FeeHistoryEntry - 129, // 62: waverpc.ListTransactionsResponse.transactions:type_name -> waverpc.TransactionHistoryEntry - 8, // 63: waverpc.GetUnrollStatusResponse.status:type_name -> waverpc.UnrollJobStatus - 134, // 64: waverpc.GetUnrollStatusResponse.progress:type_name -> waverpc.UnrollProgress - 135, // 65: waverpc.GetUnrollStatusResponse.csv:type_name -> waverpc.UnrollCSV - 136, // 66: waverpc.GetUnrollStatusResponse.fees:type_name -> waverpc.UnrollFees - 9, // 67: waverpc.ArmVHTLCRecoveryRequest.direction:type_name -> waverpc.VHTLCRecoveryDirection - 10, // 68: waverpc.ArmVHTLCRecoveryRequest.action:type_name -> waverpc.VHTLCRecoveryAction - 148, // 69: waverpc.ArmVHTLCRecoveryResponse.status:type_name -> waverpc.VHTLCRecoveryStatus - 148, // 70: waverpc.EscalateVHTLCRecoveryResponse.status:type_name -> waverpc.VHTLCRecoveryStatus - 148, // 71: waverpc.CancelVHTLCRecoveryResponse.status:type_name -> waverpc.VHTLCRecoveryStatus - 148, // 72: waverpc.GetVHTLCRecoveryStatusResponse.status:type_name -> waverpc.VHTLCRecoveryStatus - 148, // 73: waverpc.ListVHTLCRecoveriesResponse.statuses:type_name -> waverpc.VHTLCRecoveryStatus - 9, // 74: waverpc.VHTLCRecoveryStatus.direction:type_name -> waverpc.VHTLCRecoveryDirection - 10, // 75: waverpc.VHTLCRecoveryStatus.action:type_name -> waverpc.VHTLCRecoveryAction - 11, // 76: waverpc.VHTLCRecoveryStatus.state:type_name -> waverpc.VHTLCRecoveryState - 8, // 77: waverpc.VHTLCRecoveryStatus.unroll_status:type_name -> waverpc.UnrollJobStatus - 153, // 78: waverpc.BakeMacaroonRequest.permissions:type_name -> waverpc.MacaroonPermission - 153, // 79: waverpc.MacaroonPermissionList.permissions:type_name -> waverpc.MacaroonPermission - 164, // 80: waverpc.ListPermissionsResponse.method_permissions:type_name -> waverpc.ListPermissionsResponse.MethodPermissionsEntry - 53, // 81: waverpc.CooperativeOORPackage.custom_input:type_name -> waverpc.CustomOORInput - 49, // 82: waverpc.CooperativeOORPackage.recipient:type_name -> waverpc.Output - 79, // 83: waverpc.LeaveVTXOsRequest.DestinationsEntry.value:type_name -> waverpc.LeaveDestination - 156, // 84: waverpc.ListPermissionsResponse.MethodPermissionsEntry.value:type_name -> waverpc.MacaroonPermissionList - 12, // 85: waverpc.DaemonService.GetInfo:input_type -> waverpc.GetInfoRequest - 15, // 86: waverpc.DaemonService.GenSeed:input_type -> waverpc.GenSeedRequest - 17, // 87: waverpc.DaemonService.InitWallet:input_type -> waverpc.InitWalletRequest - 19, // 88: waverpc.DaemonService.UnlockWallet:input_type -> waverpc.UnlockWalletRequest - 21, // 89: waverpc.DaemonService.GetBalance:input_type -> waverpc.GetBalanceRequest - 27, // 90: waverpc.DaemonService.ListVTXOs:input_type -> waverpc.ListVTXOsRequest - 29, // 91: waverpc.DaemonService.NewAddress:input_type -> waverpc.NewAddressRequest - 31, // 92: waverpc.DaemonService.NewReceiveScript:input_type -> waverpc.NewReceiveScriptRequest - 33, // 93: waverpc.DaemonService.ReceiveAuthKey:input_type -> waverpc.ReceiveAuthKeyRequest - 35, // 94: waverpc.DaemonService.SignReceiveAuthMessage:input_type -> waverpc.SignReceiveAuthMessageRequest - 37, // 95: waverpc.DaemonService.SignReceiveAuthMessageCompact:input_type -> waverpc.SignReceiveAuthMessageCompactRequest - 39, // 96: waverpc.DaemonService.SignIdentitySchnorr:input_type -> waverpc.SignIdentitySchnorrRequest - 41, // 97: waverpc.DaemonService.ReceiveAuthECDH:input_type -> waverpc.ReceiveAuthECDHRequest - 159, // 98: waverpc.DaemonService.DeriveSwapPreimage:input_type -> waverpc.DeriveSwapPreimageRequest - 43, // 99: waverpc.DaemonService.GetIndexedVTXOByPkScript:input_type -> waverpc.GetIndexedVTXOByPkScriptRequest - 45, // 100: waverpc.DaemonService.GetVTXOExpiryInfo:input_type -> waverpc.GetVTXOExpiryInfoRequest - 47, // 101: waverpc.DaemonService.GetIndexedOORSessionByTxid:input_type -> waverpc.GetIndexedOORSessionByTxidRequest - 50, // 102: waverpc.DaemonService.SendVTXO:input_type -> waverpc.SendVTXORequest - 52, // 103: waverpc.DaemonService.SendOOR:input_type -> waverpc.SendOORRequest - 56, // 104: waverpc.DaemonService.PrepareOOR:input_type -> waverpc.PrepareOORRequest - 59, // 105: waverpc.DaemonService.SignOORCustomInput:input_type -> waverpc.SignOORCustomInputRequest - 61, // 106: waverpc.DaemonService.SignVTXOForfeit:input_type -> waverpc.SignVTXOForfeitRequest - 65, // 107: waverpc.DaemonService.RefreshVTXOs:input_type -> waverpc.RefreshVTXOsRequest - 71, // 108: waverpc.DaemonService.RefreshCustomVTXOs:input_type -> waverpc.RefreshCustomVTXOsRequest - 74, // 109: waverpc.DaemonService.ListPendingForfeitParticipantSignatureRequests:input_type -> waverpc.ListPendingForfeitParticipantSignatureRequestsRequest - 77, // 110: waverpc.DaemonService.SubmitForfeitParticipantSignatures:input_type -> waverpc.SubmitForfeitParticipantSignaturesRequest - 80, // 111: waverpc.DaemonService.LeaveVTXOs:input_type -> waverpc.LeaveVTXOsRequest - 82, // 112: waverpc.DaemonService.SendOnChain:input_type -> waverpc.SendOnChainRequest - 84, // 113: waverpc.DaemonService.Board:input_type -> waverpc.BoardRequest - 86, // 114: waverpc.DaemonService.DepositAsset:input_type -> waverpc.DepositAssetRequest - 87, // 115: waverpc.DaemonService.ListAssetDeposits:input_type -> waverpc.ListAssetDepositsRequest - 88, // 116: waverpc.DaemonService.BoardAssetDeposit:input_type -> waverpc.BoardAssetDepositRequest - 89, // 117: waverpc.DaemonService.ClaimAssetDeposit:input_type -> waverpc.ClaimAssetDepositRequest - 92, // 118: waverpc.DaemonService.NewAssetReceiveKeys:input_type -> waverpc.NewAssetReceiveKeysRequest - 94, // 119: waverpc.DaemonService.ImportAssetProof:input_type -> waverpc.ImportAssetProofRequest - 97, // 120: waverpc.DaemonService.ListOwnedAssets:input_type -> waverpc.ListOwnedAssetsRequest - 95, // 121: waverpc.DaemonService.NewAssetFundingAddress:input_type -> waverpc.NewAssetFundingAddressRequest - 100, // 122: waverpc.DaemonService.JoinNextRound:input_type -> waverpc.JoinNextRoundRequest - 102, // 123: waverpc.DaemonService.SweepBoardingUTXOs:input_type -> waverpc.SweepBoardingUTXOsRequest - 105, // 124: waverpc.DaemonService.ListBoardingSweeps:input_type -> waverpc.ListBoardingSweepsRequest - 112, // 125: waverpc.DaemonService.ListRounds:input_type -> waverpc.ListRoundsRequest - 113, // 126: waverpc.DaemonService.GetRound:input_type -> waverpc.GetRoundRequest - 116, // 127: waverpc.DaemonService.WatchRounds:input_type -> waverpc.WatchRoundsRequest - 119, // 128: waverpc.DaemonService.ListOORSessions:input_type -> waverpc.ListOORSessionsRequest - 121, // 129: waverpc.DaemonService.GetOORSession:input_type -> waverpc.GetOORSessionRequest - 123, // 130: waverpc.DaemonService.EstimateFee:input_type -> waverpc.EstimateFeeRequest - 125, // 131: waverpc.DaemonService.GetFeeHistory:input_type -> waverpc.GetFeeHistoryRequest - 128, // 132: waverpc.DaemonService.ListTransactions:input_type -> waverpc.ListTransactionsRequest - 131, // 133: waverpc.DaemonService.Unroll:input_type -> waverpc.UnrollRequest - 133, // 134: waverpc.DaemonService.GetUnrollStatus:input_type -> waverpc.GetUnrollStatusRequest - 138, // 135: waverpc.DaemonService.ArmVHTLCRecovery:input_type -> waverpc.ArmVHTLCRecoveryRequest - 140, // 136: waverpc.DaemonService.EscalateVHTLCRecovery:input_type -> waverpc.EscalateVHTLCRecoveryRequest - 142, // 137: waverpc.DaemonService.CancelVHTLCRecovery:input_type -> waverpc.CancelVHTLCRecoveryRequest - 144, // 138: waverpc.DaemonService.GetVHTLCRecoveryStatus:input_type -> waverpc.GetVHTLCRecoveryStatusRequest - 146, // 139: waverpc.DaemonService.ListVHTLCRecoveries:input_type -> waverpc.ListVHTLCRecoveriesRequest - 149, // 140: waverpc.DaemonService.SignOutSwapHtlcAck:input_type -> waverpc.SignOutSwapHtlcAckRequest - 151, // 141: waverpc.DaemonService.SignCreditAccountAuthorization:input_type -> waverpc.SignCreditAccountAuthorizationRequest - 154, // 142: waverpc.MacaroonService.BakeMacaroon:input_type -> waverpc.BakeMacaroonRequest - 157, // 143: waverpc.MacaroonService.ListPermissions:input_type -> waverpc.ListPermissionsRequest - 13, // 144: waverpc.DaemonService.GetInfo:output_type -> waverpc.GetInfoResponse - 16, // 145: waverpc.DaemonService.GenSeed:output_type -> waverpc.GenSeedResponse - 18, // 146: waverpc.DaemonService.InitWallet:output_type -> waverpc.InitWalletResponse - 20, // 147: waverpc.DaemonService.UnlockWallet:output_type -> waverpc.UnlockWalletResponse - 22, // 148: waverpc.DaemonService.GetBalance:output_type -> waverpc.GetBalanceResponse - 28, // 149: waverpc.DaemonService.ListVTXOs:output_type -> waverpc.ListVTXOsResponse - 30, // 150: waverpc.DaemonService.NewAddress:output_type -> waverpc.NewAddressResponse - 32, // 151: waverpc.DaemonService.NewReceiveScript:output_type -> waverpc.NewReceiveScriptResponse - 34, // 152: waverpc.DaemonService.ReceiveAuthKey:output_type -> waverpc.ReceiveAuthKeyResponse - 36, // 153: waverpc.DaemonService.SignReceiveAuthMessage:output_type -> waverpc.SignReceiveAuthMessageResponse - 38, // 154: waverpc.DaemonService.SignReceiveAuthMessageCompact:output_type -> waverpc.SignReceiveAuthMessageCompactResponse - 40, // 155: waverpc.DaemonService.SignIdentitySchnorr:output_type -> waverpc.SignIdentitySchnorrResponse - 42, // 156: waverpc.DaemonService.ReceiveAuthECDH:output_type -> waverpc.ReceiveAuthECDHResponse - 160, // 157: waverpc.DaemonService.DeriveSwapPreimage:output_type -> waverpc.DeriveSwapPreimageResponse - 44, // 158: waverpc.DaemonService.GetIndexedVTXOByPkScript:output_type -> waverpc.GetIndexedVTXOByPkScriptResponse - 46, // 159: waverpc.DaemonService.GetVTXOExpiryInfo:output_type -> waverpc.GetVTXOExpiryInfoResponse - 48, // 160: waverpc.DaemonService.GetIndexedOORSessionByTxid:output_type -> waverpc.GetIndexedOORSessionByTxidResponse - 51, // 161: waverpc.DaemonService.SendVTXO:output_type -> waverpc.SendVTXOResponse - 55, // 162: waverpc.DaemonService.SendOOR:output_type -> waverpc.SendOORResponse - 58, // 163: waverpc.DaemonService.PrepareOOR:output_type -> waverpc.PrepareOORResponse - 60, // 164: waverpc.DaemonService.SignOORCustomInput:output_type -> waverpc.SignOORCustomInputResponse - 62, // 165: waverpc.DaemonService.SignVTXOForfeit:output_type -> waverpc.SignVTXOForfeitResponse - 66, // 166: waverpc.DaemonService.RefreshVTXOs:output_type -> waverpc.RefreshVTXOsResponse - 72, // 167: waverpc.DaemonService.RefreshCustomVTXOs:output_type -> waverpc.RefreshCustomVTXOsResponse - 75, // 168: waverpc.DaemonService.ListPendingForfeitParticipantSignatureRequests:output_type -> waverpc.ListPendingForfeitParticipantSignatureRequestsResponse - 78, // 169: waverpc.DaemonService.SubmitForfeitParticipantSignatures:output_type -> waverpc.SubmitForfeitParticipantSignaturesResponse - 81, // 170: waverpc.DaemonService.LeaveVTXOs:output_type -> waverpc.LeaveVTXOsResponse - 83, // 171: waverpc.DaemonService.SendOnChain:output_type -> waverpc.SendOnChainResponse - 85, // 172: waverpc.DaemonService.Board:output_type -> waverpc.BoardResponse - 91, // 173: waverpc.DaemonService.DepositAsset:output_type -> waverpc.AssetDeposit - 90, // 174: waverpc.DaemonService.ListAssetDeposits:output_type -> waverpc.ListAssetDepositsResponse - 91, // 175: waverpc.DaemonService.BoardAssetDeposit:output_type -> waverpc.AssetDeposit - 91, // 176: waverpc.DaemonService.ClaimAssetDeposit:output_type -> waverpc.AssetDeposit - 93, // 177: waverpc.DaemonService.NewAssetReceiveKeys:output_type -> waverpc.AssetReceiveKeys - 99, // 178: waverpc.DaemonService.ImportAssetProof:output_type -> waverpc.OwnedAsset - 98, // 179: waverpc.DaemonService.ListOwnedAssets:output_type -> waverpc.ListOwnedAssetsResponse - 96, // 180: waverpc.DaemonService.NewAssetFundingAddress:output_type -> waverpc.AssetFundingAddress - 101, // 181: waverpc.DaemonService.JoinNextRound:output_type -> waverpc.JoinNextRoundResponse - 104, // 182: waverpc.DaemonService.SweepBoardingUTXOs:output_type -> waverpc.SweepBoardingUTXOsResponse - 108, // 183: waverpc.DaemonService.ListBoardingSweeps:output_type -> waverpc.ListBoardingSweepsResponse - 115, // 184: waverpc.DaemonService.ListRounds:output_type -> waverpc.ListRoundsResponse - 114, // 185: waverpc.DaemonService.GetRound:output_type -> waverpc.GetRoundResponse - 117, // 186: waverpc.DaemonService.WatchRounds:output_type -> waverpc.WatchRoundsResponse - 120, // 187: waverpc.DaemonService.ListOORSessions:output_type -> waverpc.ListOORSessionsResponse - 122, // 188: waverpc.DaemonService.GetOORSession:output_type -> waverpc.GetOORSessionResponse - 124, // 189: waverpc.DaemonService.EstimateFee:output_type -> waverpc.EstimateFeeResponse - 127, // 190: waverpc.DaemonService.GetFeeHistory:output_type -> waverpc.GetFeeHistoryResponse - 130, // 191: waverpc.DaemonService.ListTransactions:output_type -> waverpc.ListTransactionsResponse - 132, // 192: waverpc.DaemonService.Unroll:output_type -> waverpc.UnrollResponse - 137, // 193: waverpc.DaemonService.GetUnrollStatus:output_type -> waverpc.GetUnrollStatusResponse - 139, // 194: waverpc.DaemonService.ArmVHTLCRecovery:output_type -> waverpc.ArmVHTLCRecoveryResponse - 141, // 195: waverpc.DaemonService.EscalateVHTLCRecovery:output_type -> waverpc.EscalateVHTLCRecoveryResponse - 143, // 196: waverpc.DaemonService.CancelVHTLCRecovery:output_type -> waverpc.CancelVHTLCRecoveryResponse - 145, // 197: waverpc.DaemonService.GetVHTLCRecoveryStatus:output_type -> waverpc.GetVHTLCRecoveryStatusResponse - 147, // 198: waverpc.DaemonService.ListVHTLCRecoveries:output_type -> waverpc.ListVHTLCRecoveriesResponse - 150, // 199: waverpc.DaemonService.SignOutSwapHtlcAck:output_type -> waverpc.SignOutSwapHtlcAckResponse - 152, // 200: waverpc.DaemonService.SignCreditAccountAuthorization:output_type -> waverpc.SignCreditAccountAuthorizationResponse - 155, // 201: waverpc.MacaroonService.BakeMacaroon:output_type -> waverpc.BakeMacaroonResponse - 158, // 202: waverpc.MacaroonService.ListPermissions:output_type -> waverpc.ListPermissionsResponse - 144, // [144:203] is the sub-list for method output_type - 85, // [85:144] is the sub-list for method input_type - 85, // [85:85] is the sub-list for extension type_name - 85, // [85:85] is the sub-list for extension extendee - 0, // [0:85] is the sub-list for field type_name + 167, // 23: waverpc.ExportOORRecoveryPackageRequest.source:type_name -> arkchannelrpc.OORRecoverySource + 168, // 24: waverpc.ExportOORRecoveryPackageResponse.recovery:type_name -> arkchannelrpc.ChannelRecoveryPackage + 53, // 25: waverpc.SignOORCustomInputRequest.custom_input:type_name -> waverpc.CustomOORInput + 163, // 26: waverpc.SignOORCustomInputRequest.cooperative_package:type_name -> waverpc.CooperativeOORPackage + 54, // 27: waverpc.SignOORCustomInputResponse.signature:type_name -> waverpc.TaprootScriptSignature + 54, // 28: waverpc.SignOORCustomInputResponse.payout_signature:type_name -> waverpc.TaprootScriptSignature + 3, // 29: waverpc.ForfeitSigningContext.signing_route:type_name -> waverpc.ForfeitSigningRoute + 66, // 30: waverpc.RefreshVTXOsRequest.outpoints:type_name -> waverpc.OutpointSelection + 69, // 31: waverpc.RefreshVTXOsResponse.fee_estimate:type_name -> waverpc.RefreshFeeEstimate + 70, // 32: waverpc.RefreshFeeEstimate.outpoints:type_name -> waverpc.OutpointFeeEstimate + 65, // 33: waverpc.CustomRefreshVTXOInput.forfeit_signing_context:type_name -> waverpc.ForfeitSigningContext + 71, // 34: waverpc.RefreshCustomVTXOsRequest.inputs:type_name -> waverpc.CustomRefreshVTXOInput + 72, // 35: waverpc.RefreshCustomVTXOsRequest.outputs:type_name -> waverpc.CustomRefreshVTXOOutput + 3, // 36: waverpc.PendingForfeitParticipantSignatureRequest.signing_route:type_name -> waverpc.ForfeitSigningRoute + 75, // 37: waverpc.ListPendingForfeitParticipantSignatureRequestsResponse.requests:type_name -> waverpc.PendingForfeitParticipantSignatureRequest + 78, // 38: waverpc.SubmitForfeitParticipantSignaturesRequest.signatures:type_name -> waverpc.ForfeitParticipantSignature + 66, // 39: waverpc.LeaveVTXOsRequest.outpoints:type_name -> waverpc.OutpointSelection + 81, // 40: waverpc.LeaveVTXOsRequest.default_destination:type_name -> waverpc.LeaveDestination + 164, // 41: waverpc.LeaveVTXOsRequest.destinations:type_name -> waverpc.LeaveVTXOsRequest.DestinationsEntry + 165, // 42: waverpc.LeaveVTXOsResponse.errors:type_name -> waverpc.LeaveVTXOsResponse.ErrorsEntry + 81, // 43: waverpc.SendOnChainRequest.destination:type_name -> waverpc.LeaveDestination + 93, // 44: waverpc.ListAssetDepositsResponse.deposits:type_name -> waverpc.AssetDeposit + 4, // 45: waverpc.AssetDeposit.status:type_name -> waverpc.AssetDepositStatus + 101, // 46: waverpc.ListOwnedAssetsResponse.assets:type_name -> waverpc.OwnedAsset + 105, // 47: waverpc.SweepBoardingUTXOsResponse.sweepable_outputs:type_name -> waverpc.BoardingSweepOutput + 108, // 48: waverpc.BoardingSweep.inputs:type_name -> waverpc.BoardingSweepInput + 109, // 49: waverpc.ListBoardingSweepsResponse.sweeps:type_name -> waverpc.BoardingSweep + 5, // 50: waverpc.RoundInfo.state:type_name -> waverpc.RoundState + 111, // 51: waverpc.RoundInfo.vtxos:type_name -> waverpc.RoundVTXOInfo + 112, // 52: waverpc.RoundInfo.batch_window:type_name -> waverpc.ScheduledBatchWindow + 5, // 53: waverpc.ListRoundsRequest.state_filter:type_name -> waverpc.RoundState + 113, // 54: waverpc.GetRoundResponse.round:type_name -> waverpc.RoundInfo + 113, // 55: waverpc.ListRoundsResponse.rounds:type_name -> waverpc.RoundInfo + 113, // 56: waverpc.WatchRoundsResponse.round:type_name -> waverpc.RoundInfo + 6, // 57: waverpc.OORSessionInfo.direction:type_name -> waverpc.OORSessionDirection + 7, // 58: waverpc.OORSessionInfo.status:type_name -> waverpc.OORSessionStatus + 6, // 59: waverpc.ListOORSessionsRequest.direction_filter:type_name -> waverpc.OORSessionDirection + 7, // 60: waverpc.ListOORSessionsRequest.status_filter:type_name -> waverpc.OORSessionStatus + 120, // 61: waverpc.ListOORSessionsResponse.sessions:type_name -> waverpc.OORSessionInfo + 120, // 62: waverpc.GetOORSessionResponse.session:type_name -> waverpc.OORSessionInfo + 128, // 63: waverpc.GetFeeHistoryResponse.entries:type_name -> waverpc.FeeHistoryEntry + 131, // 64: waverpc.ListTransactionsResponse.transactions:type_name -> waverpc.TransactionHistoryEntry + 8, // 65: waverpc.GetUnrollStatusResponse.status:type_name -> waverpc.UnrollJobStatus + 136, // 66: waverpc.GetUnrollStatusResponse.progress:type_name -> waverpc.UnrollProgress + 137, // 67: waverpc.GetUnrollStatusResponse.csv:type_name -> waverpc.UnrollCSV + 138, // 68: waverpc.GetUnrollStatusResponse.fees:type_name -> waverpc.UnrollFees + 9, // 69: waverpc.ArmVHTLCRecoveryRequest.direction:type_name -> waverpc.VHTLCRecoveryDirection + 10, // 70: waverpc.ArmVHTLCRecoveryRequest.action:type_name -> waverpc.VHTLCRecoveryAction + 150, // 71: waverpc.ArmVHTLCRecoveryResponse.status:type_name -> waverpc.VHTLCRecoveryStatus + 150, // 72: waverpc.EscalateVHTLCRecoveryResponse.status:type_name -> waverpc.VHTLCRecoveryStatus + 150, // 73: waverpc.CancelVHTLCRecoveryResponse.status:type_name -> waverpc.VHTLCRecoveryStatus + 150, // 74: waverpc.GetVHTLCRecoveryStatusResponse.status:type_name -> waverpc.VHTLCRecoveryStatus + 150, // 75: waverpc.ListVHTLCRecoveriesResponse.statuses:type_name -> waverpc.VHTLCRecoveryStatus + 9, // 76: waverpc.VHTLCRecoveryStatus.direction:type_name -> waverpc.VHTLCRecoveryDirection + 10, // 77: waverpc.VHTLCRecoveryStatus.action:type_name -> waverpc.VHTLCRecoveryAction + 11, // 78: waverpc.VHTLCRecoveryStatus.state:type_name -> waverpc.VHTLCRecoveryState + 8, // 79: waverpc.VHTLCRecoveryStatus.unroll_status:type_name -> waverpc.UnrollJobStatus + 155, // 80: waverpc.BakeMacaroonRequest.permissions:type_name -> waverpc.MacaroonPermission + 155, // 81: waverpc.MacaroonPermissionList.permissions:type_name -> waverpc.MacaroonPermission + 166, // 82: waverpc.ListPermissionsResponse.method_permissions:type_name -> waverpc.ListPermissionsResponse.MethodPermissionsEntry + 53, // 83: waverpc.CooperativeOORPackage.custom_input:type_name -> waverpc.CustomOORInput + 49, // 84: waverpc.CooperativeOORPackage.recipient:type_name -> waverpc.Output + 81, // 85: waverpc.LeaveVTXOsRequest.DestinationsEntry.value:type_name -> waverpc.LeaveDestination + 158, // 86: waverpc.ListPermissionsResponse.MethodPermissionsEntry.value:type_name -> waverpc.MacaroonPermissionList + 12, // 87: waverpc.DaemonService.GetInfo:input_type -> waverpc.GetInfoRequest + 15, // 88: waverpc.DaemonService.GenSeed:input_type -> waverpc.GenSeedRequest + 17, // 89: waverpc.DaemonService.InitWallet:input_type -> waverpc.InitWalletRequest + 19, // 90: waverpc.DaemonService.UnlockWallet:input_type -> waverpc.UnlockWalletRequest + 21, // 91: waverpc.DaemonService.GetBalance:input_type -> waverpc.GetBalanceRequest + 27, // 92: waverpc.DaemonService.ListVTXOs:input_type -> waverpc.ListVTXOsRequest + 29, // 93: waverpc.DaemonService.NewAddress:input_type -> waverpc.NewAddressRequest + 31, // 94: waverpc.DaemonService.NewReceiveScript:input_type -> waverpc.NewReceiveScriptRequest + 33, // 95: waverpc.DaemonService.ReceiveAuthKey:input_type -> waverpc.ReceiveAuthKeyRequest + 35, // 96: waverpc.DaemonService.SignReceiveAuthMessage:input_type -> waverpc.SignReceiveAuthMessageRequest + 37, // 97: waverpc.DaemonService.SignReceiveAuthMessageCompact:input_type -> waverpc.SignReceiveAuthMessageCompactRequest + 39, // 98: waverpc.DaemonService.SignIdentitySchnorr:input_type -> waverpc.SignIdentitySchnorrRequest + 41, // 99: waverpc.DaemonService.ReceiveAuthECDH:input_type -> waverpc.ReceiveAuthECDHRequest + 161, // 100: waverpc.DaemonService.DeriveSwapPreimage:input_type -> waverpc.DeriveSwapPreimageRequest + 43, // 101: waverpc.DaemonService.GetIndexedVTXOByPkScript:input_type -> waverpc.GetIndexedVTXOByPkScriptRequest + 45, // 102: waverpc.DaemonService.GetVTXOExpiryInfo:input_type -> waverpc.GetVTXOExpiryInfoRequest + 47, // 103: waverpc.DaemonService.GetIndexedOORSessionByTxid:input_type -> waverpc.GetIndexedOORSessionByTxidRequest + 59, // 104: waverpc.DaemonService.ExportOORRecoveryPackage:input_type -> waverpc.ExportOORRecoveryPackageRequest + 50, // 105: waverpc.DaemonService.SendVTXO:input_type -> waverpc.SendVTXORequest + 52, // 106: waverpc.DaemonService.SendOOR:input_type -> waverpc.SendOORRequest + 56, // 107: waverpc.DaemonService.PrepareOOR:input_type -> waverpc.PrepareOORRequest + 61, // 108: waverpc.DaemonService.SignOORCustomInput:input_type -> waverpc.SignOORCustomInputRequest + 63, // 109: waverpc.DaemonService.SignVTXOForfeit:input_type -> waverpc.SignVTXOForfeitRequest + 67, // 110: waverpc.DaemonService.RefreshVTXOs:input_type -> waverpc.RefreshVTXOsRequest + 73, // 111: waverpc.DaemonService.RefreshCustomVTXOs:input_type -> waverpc.RefreshCustomVTXOsRequest + 76, // 112: waverpc.DaemonService.ListPendingForfeitParticipantSignatureRequests:input_type -> waverpc.ListPendingForfeitParticipantSignatureRequestsRequest + 79, // 113: waverpc.DaemonService.SubmitForfeitParticipantSignatures:input_type -> waverpc.SubmitForfeitParticipantSignaturesRequest + 82, // 114: waverpc.DaemonService.LeaveVTXOs:input_type -> waverpc.LeaveVTXOsRequest + 84, // 115: waverpc.DaemonService.SendOnChain:input_type -> waverpc.SendOnChainRequest + 86, // 116: waverpc.DaemonService.Board:input_type -> waverpc.BoardRequest + 88, // 117: waverpc.DaemonService.DepositAsset:input_type -> waverpc.DepositAssetRequest + 89, // 118: waverpc.DaemonService.ListAssetDeposits:input_type -> waverpc.ListAssetDepositsRequest + 90, // 119: waverpc.DaemonService.BoardAssetDeposit:input_type -> waverpc.BoardAssetDepositRequest + 91, // 120: waverpc.DaemonService.ClaimAssetDeposit:input_type -> waverpc.ClaimAssetDepositRequest + 94, // 121: waverpc.DaemonService.NewAssetReceiveKeys:input_type -> waverpc.NewAssetReceiveKeysRequest + 96, // 122: waverpc.DaemonService.ImportAssetProof:input_type -> waverpc.ImportAssetProofRequest + 99, // 123: waverpc.DaemonService.ListOwnedAssets:input_type -> waverpc.ListOwnedAssetsRequest + 97, // 124: waverpc.DaemonService.NewAssetFundingAddress:input_type -> waverpc.NewAssetFundingAddressRequest + 102, // 125: waverpc.DaemonService.JoinNextRound:input_type -> waverpc.JoinNextRoundRequest + 104, // 126: waverpc.DaemonService.SweepBoardingUTXOs:input_type -> waverpc.SweepBoardingUTXOsRequest + 107, // 127: waverpc.DaemonService.ListBoardingSweeps:input_type -> waverpc.ListBoardingSweepsRequest + 114, // 128: waverpc.DaemonService.ListRounds:input_type -> waverpc.ListRoundsRequest + 115, // 129: waverpc.DaemonService.GetRound:input_type -> waverpc.GetRoundRequest + 118, // 130: waverpc.DaemonService.WatchRounds:input_type -> waverpc.WatchRoundsRequest + 121, // 131: waverpc.DaemonService.ListOORSessions:input_type -> waverpc.ListOORSessionsRequest + 123, // 132: waverpc.DaemonService.GetOORSession:input_type -> waverpc.GetOORSessionRequest + 125, // 133: waverpc.DaemonService.EstimateFee:input_type -> waverpc.EstimateFeeRequest + 127, // 134: waverpc.DaemonService.GetFeeHistory:input_type -> waverpc.GetFeeHistoryRequest + 130, // 135: waverpc.DaemonService.ListTransactions:input_type -> waverpc.ListTransactionsRequest + 133, // 136: waverpc.DaemonService.Unroll:input_type -> waverpc.UnrollRequest + 135, // 137: waverpc.DaemonService.GetUnrollStatus:input_type -> waverpc.GetUnrollStatusRequest + 140, // 138: waverpc.DaemonService.ArmVHTLCRecovery:input_type -> waverpc.ArmVHTLCRecoveryRequest + 142, // 139: waverpc.DaemonService.EscalateVHTLCRecovery:input_type -> waverpc.EscalateVHTLCRecoveryRequest + 144, // 140: waverpc.DaemonService.CancelVHTLCRecovery:input_type -> waverpc.CancelVHTLCRecoveryRequest + 146, // 141: waverpc.DaemonService.GetVHTLCRecoveryStatus:input_type -> waverpc.GetVHTLCRecoveryStatusRequest + 148, // 142: waverpc.DaemonService.ListVHTLCRecoveries:input_type -> waverpc.ListVHTLCRecoveriesRequest + 151, // 143: waverpc.DaemonService.SignOutSwapHtlcAck:input_type -> waverpc.SignOutSwapHtlcAckRequest + 153, // 144: waverpc.DaemonService.SignCreditAccountAuthorization:input_type -> waverpc.SignCreditAccountAuthorizationRequest + 156, // 145: waverpc.MacaroonService.BakeMacaroon:input_type -> waverpc.BakeMacaroonRequest + 159, // 146: waverpc.MacaroonService.ListPermissions:input_type -> waverpc.ListPermissionsRequest + 13, // 147: waverpc.DaemonService.GetInfo:output_type -> waverpc.GetInfoResponse + 16, // 148: waverpc.DaemonService.GenSeed:output_type -> waverpc.GenSeedResponse + 18, // 149: waverpc.DaemonService.InitWallet:output_type -> waverpc.InitWalletResponse + 20, // 150: waverpc.DaemonService.UnlockWallet:output_type -> waverpc.UnlockWalletResponse + 22, // 151: waverpc.DaemonService.GetBalance:output_type -> waverpc.GetBalanceResponse + 28, // 152: waverpc.DaemonService.ListVTXOs:output_type -> waverpc.ListVTXOsResponse + 30, // 153: waverpc.DaemonService.NewAddress:output_type -> waverpc.NewAddressResponse + 32, // 154: waverpc.DaemonService.NewReceiveScript:output_type -> waverpc.NewReceiveScriptResponse + 34, // 155: waverpc.DaemonService.ReceiveAuthKey:output_type -> waverpc.ReceiveAuthKeyResponse + 36, // 156: waverpc.DaemonService.SignReceiveAuthMessage:output_type -> waverpc.SignReceiveAuthMessageResponse + 38, // 157: waverpc.DaemonService.SignReceiveAuthMessageCompact:output_type -> waverpc.SignReceiveAuthMessageCompactResponse + 40, // 158: waverpc.DaemonService.SignIdentitySchnorr:output_type -> waverpc.SignIdentitySchnorrResponse + 42, // 159: waverpc.DaemonService.ReceiveAuthECDH:output_type -> waverpc.ReceiveAuthECDHResponse + 162, // 160: waverpc.DaemonService.DeriveSwapPreimage:output_type -> waverpc.DeriveSwapPreimageResponse + 44, // 161: waverpc.DaemonService.GetIndexedVTXOByPkScript:output_type -> waverpc.GetIndexedVTXOByPkScriptResponse + 46, // 162: waverpc.DaemonService.GetVTXOExpiryInfo:output_type -> waverpc.GetVTXOExpiryInfoResponse + 48, // 163: waverpc.DaemonService.GetIndexedOORSessionByTxid:output_type -> waverpc.GetIndexedOORSessionByTxidResponse + 60, // 164: waverpc.DaemonService.ExportOORRecoveryPackage:output_type -> waverpc.ExportOORRecoveryPackageResponse + 51, // 165: waverpc.DaemonService.SendVTXO:output_type -> waverpc.SendVTXOResponse + 55, // 166: waverpc.DaemonService.SendOOR:output_type -> waverpc.SendOORResponse + 58, // 167: waverpc.DaemonService.PrepareOOR:output_type -> waverpc.PrepareOORResponse + 62, // 168: waverpc.DaemonService.SignOORCustomInput:output_type -> waverpc.SignOORCustomInputResponse + 64, // 169: waverpc.DaemonService.SignVTXOForfeit:output_type -> waverpc.SignVTXOForfeitResponse + 68, // 170: waverpc.DaemonService.RefreshVTXOs:output_type -> waverpc.RefreshVTXOsResponse + 74, // 171: waverpc.DaemonService.RefreshCustomVTXOs:output_type -> waverpc.RefreshCustomVTXOsResponse + 77, // 172: waverpc.DaemonService.ListPendingForfeitParticipantSignatureRequests:output_type -> waverpc.ListPendingForfeitParticipantSignatureRequestsResponse + 80, // 173: waverpc.DaemonService.SubmitForfeitParticipantSignatures:output_type -> waverpc.SubmitForfeitParticipantSignaturesResponse + 83, // 174: waverpc.DaemonService.LeaveVTXOs:output_type -> waverpc.LeaveVTXOsResponse + 85, // 175: waverpc.DaemonService.SendOnChain:output_type -> waverpc.SendOnChainResponse + 87, // 176: waverpc.DaemonService.Board:output_type -> waverpc.BoardResponse + 93, // 177: waverpc.DaemonService.DepositAsset:output_type -> waverpc.AssetDeposit + 92, // 178: waverpc.DaemonService.ListAssetDeposits:output_type -> waverpc.ListAssetDepositsResponse + 93, // 179: waverpc.DaemonService.BoardAssetDeposit:output_type -> waverpc.AssetDeposit + 93, // 180: waverpc.DaemonService.ClaimAssetDeposit:output_type -> waverpc.AssetDeposit + 95, // 181: waverpc.DaemonService.NewAssetReceiveKeys:output_type -> waverpc.AssetReceiveKeys + 101, // 182: waverpc.DaemonService.ImportAssetProof:output_type -> waverpc.OwnedAsset + 100, // 183: waverpc.DaemonService.ListOwnedAssets:output_type -> waverpc.ListOwnedAssetsResponse + 98, // 184: waverpc.DaemonService.NewAssetFundingAddress:output_type -> waverpc.AssetFundingAddress + 103, // 185: waverpc.DaemonService.JoinNextRound:output_type -> waverpc.JoinNextRoundResponse + 106, // 186: waverpc.DaemonService.SweepBoardingUTXOs:output_type -> waverpc.SweepBoardingUTXOsResponse + 110, // 187: waverpc.DaemonService.ListBoardingSweeps:output_type -> waverpc.ListBoardingSweepsResponse + 117, // 188: waverpc.DaemonService.ListRounds:output_type -> waverpc.ListRoundsResponse + 116, // 189: waverpc.DaemonService.GetRound:output_type -> waverpc.GetRoundResponse + 119, // 190: waverpc.DaemonService.WatchRounds:output_type -> waverpc.WatchRoundsResponse + 122, // 191: waverpc.DaemonService.ListOORSessions:output_type -> waverpc.ListOORSessionsResponse + 124, // 192: waverpc.DaemonService.GetOORSession:output_type -> waverpc.GetOORSessionResponse + 126, // 193: waverpc.DaemonService.EstimateFee:output_type -> waverpc.EstimateFeeResponse + 129, // 194: waverpc.DaemonService.GetFeeHistory:output_type -> waverpc.GetFeeHistoryResponse + 132, // 195: waverpc.DaemonService.ListTransactions:output_type -> waverpc.ListTransactionsResponse + 134, // 196: waverpc.DaemonService.Unroll:output_type -> waverpc.UnrollResponse + 139, // 197: waverpc.DaemonService.GetUnrollStatus:output_type -> waverpc.GetUnrollStatusResponse + 141, // 198: waverpc.DaemonService.ArmVHTLCRecovery:output_type -> waverpc.ArmVHTLCRecoveryResponse + 143, // 199: waverpc.DaemonService.EscalateVHTLCRecovery:output_type -> waverpc.EscalateVHTLCRecoveryResponse + 145, // 200: waverpc.DaemonService.CancelVHTLCRecovery:output_type -> waverpc.CancelVHTLCRecoveryResponse + 147, // 201: waverpc.DaemonService.GetVHTLCRecoveryStatus:output_type -> waverpc.GetVHTLCRecoveryStatusResponse + 149, // 202: waverpc.DaemonService.ListVHTLCRecoveries:output_type -> waverpc.ListVHTLCRecoveriesResponse + 152, // 203: waverpc.DaemonService.SignOutSwapHtlcAck:output_type -> waverpc.SignOutSwapHtlcAckResponse + 154, // 204: waverpc.DaemonService.SignCreditAccountAuthorization:output_type -> waverpc.SignCreditAccountAuthorizationResponse + 157, // 205: waverpc.MacaroonService.BakeMacaroon:output_type -> waverpc.BakeMacaroonResponse + 160, // 206: waverpc.MacaroonService.ListPermissions:output_type -> waverpc.ListPermissionsResponse + 147, // [147:207] is the sub-list for method output_type + 87, // [87:147] is the sub-list for method input_type + 87, // [87:87] is the sub-list for extension type_name + 87, // [87:87] is the sub-list for extension extendee + 0, // [0:87] is the sub-list for field type_name } func init() { file_daemon_proto_init() } @@ -13843,31 +13960,31 @@ func file_daemon_proto_init() { (*Output_Pubkey)(nil), (*Output_PolicyTemplate)(nil), } - file_daemon_proto_msgTypes[53].OneofWrappers = []any{ + file_daemon_proto_msgTypes[55].OneofWrappers = []any{ (*RefreshVTXOsRequest_Outpoints)(nil), (*RefreshVTXOsRequest_All)(nil), } - file_daemon_proto_msgTypes[55].OneofWrappers = []any{} - file_daemon_proto_msgTypes[67].OneofWrappers = []any{ + file_daemon_proto_msgTypes[57].OneofWrappers = []any{} + file_daemon_proto_msgTypes[69].OneofWrappers = []any{ (*LeaveDestination_Address)(nil), (*LeaveDestination_PkScript)(nil), } - file_daemon_proto_msgTypes[68].OneofWrappers = []any{ + file_daemon_proto_msgTypes[70].OneofWrappers = []any{ (*LeaveVTXOsRequest_Outpoints)(nil), (*LeaveVTXOsRequest_All)(nil), } - file_daemon_proto_msgTypes[70].OneofWrappers = []any{ + file_daemon_proto_msgTypes[72].OneofWrappers = []any{ (*SendOnChainRequest_AmountSat)(nil), (*SendOnChainRequest_SweepAll)(nil), } - file_daemon_proto_msgTypes[114].OneofWrappers = []any{} + file_daemon_proto_msgTypes[116].OneofWrappers = []any{} type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_daemon_proto_rawDesc), len(file_daemon_proto_rawDesc)), NumEnums: 12, - NumMessages: 153, + NumMessages: 155, NumExtensions: 0, NumServices: 2, }, diff --git a/waverpc/daemon.pb.gw.go b/waverpc/daemon.pb.gw.go index 0e5074274..a2ec3c8ed 100644 --- a/waverpc/daemon.pb.gw.go +++ b/waverpc/daemon.pb.gw.go @@ -494,6 +494,33 @@ func local_request_DaemonService_GetIndexedOORSessionByTxid_0(ctx context.Contex return msg, metadata, err } +func request_DaemonService_ExportOORRecoveryPackage_0(ctx context.Context, marshaler runtime.Marshaler, client DaemonServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq ExportOORRecoveryPackageRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } + msg, err := client.ExportOORRecoveryPackage(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_DaemonService_ExportOORRecoveryPackage_0(ctx context.Context, marshaler runtime.Marshaler, server DaemonServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq ExportOORRecoveryPackageRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + msg, err := server.ExportOORRecoveryPackage(ctx, &protoReq) + return msg, metadata, err +} + func request_DaemonService_SendVTXO_0(ctx context.Context, marshaler runtime.Marshaler, client DaemonServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq SendVTXORequest @@ -1964,6 +1991,26 @@ func RegisterDaemonServiceHandlerServer(ctx context.Context, mux *runtime.ServeM } forward_DaemonService_GetIndexedOORSessionByTxid_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) + mux.Handle(http.MethodPost, pattern_DaemonService_ExportOORRecoveryPackage_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/waverpc.DaemonService/ExportOORRecoveryPackage", runtime.WithHTTPPathPattern("/v1/daemon/export-oor-recovery-package")) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_DaemonService_ExportOORRecoveryPackage_0(annotatedContext, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) + if err != nil { + runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) + return + } + forward_DaemonService_ExportOORRecoveryPackage_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) mux.Handle(http.MethodPost, pattern_DaemonService_SendVTXO_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -3130,6 +3177,23 @@ func RegisterDaemonServiceHandlerClient(ctx context.Context, mux *runtime.ServeM } forward_DaemonService_GetIndexedOORSessionByTxid_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) + mux.Handle(http.MethodPost, pattern_DaemonService_ExportOORRecoveryPackage_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/waverpc.DaemonService/ExportOORRecoveryPackage", runtime.WithHTTPPathPattern("/v1/daemon/export-oor-recovery-package")) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_DaemonService_ExportOORRecoveryPackage_0(annotatedContext, inboundMarshaler, client, req, pathParams) + annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) + if err != nil { + runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) + return + } + forward_DaemonService_ExportOORRecoveryPackage_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) mux.Handle(http.MethodPost, pattern_DaemonService_SendVTXO_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -3831,6 +3895,7 @@ var ( pattern_DaemonService_GetIndexedVTXOByPkScript_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "daemon", "get-indexed-vtxo-by-pk-script"}, "")) pattern_DaemonService_GetVTXOExpiryInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "daemon", "get-vtxo-expiry-info"}, "")) pattern_DaemonService_GetIndexedOORSessionByTxid_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "daemon", "get-indexed-oor-session-by-txid"}, "")) + pattern_DaemonService_ExportOORRecoveryPackage_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "daemon", "export-oor-recovery-package"}, "")) pattern_DaemonService_SendVTXO_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "daemon", "send-vtxo"}, "")) pattern_DaemonService_SendOOR_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "daemon", "send-oor"}, "")) pattern_DaemonService_PrepareOOR_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "daemon", "prepare-oor"}, "")) @@ -3891,6 +3956,7 @@ var ( forward_DaemonService_GetIndexedVTXOByPkScript_0 = runtime.ForwardResponseMessage forward_DaemonService_GetVTXOExpiryInfo_0 = runtime.ForwardResponseMessage forward_DaemonService_GetIndexedOORSessionByTxid_0 = runtime.ForwardResponseMessage + forward_DaemonService_ExportOORRecoveryPackage_0 = runtime.ForwardResponseMessage forward_DaemonService_SendVTXO_0 = runtime.ForwardResponseMessage forward_DaemonService_SendOOR_0 = runtime.ForwardResponseMessage forward_DaemonService_PrepareOOR_0 = runtime.ForwardResponseMessage diff --git a/waverpc/daemon.proto b/waverpc/daemon.proto index 0ac018362..fa73f2c81 100644 --- a/waverpc/daemon.proto +++ b/waverpc/daemon.proto @@ -2,6 +2,8 @@ syntax = "proto3"; package waverpc; +import "rpc/arkchannelrpc/ark_channel.proto"; + option go_package = "github.com/lightninglabs/wavelength/waverpc"; // DaemonService is the client daemon's own gRPC API. External tools such as @@ -90,6 +92,12 @@ service DaemonService { rpc GetIndexedOORSessionByTxid (GetIndexedOORSessionByTxidRequest) returns (GetIndexedOORSessionByTxidResponse); + // ExportOORRecoveryPackage returns the immutable local OOR package and + // round ancestry for one exact output. The caller must already know the + // output tuple; the daemon verifies it against its finalized artifacts. + rpc ExportOORRecoveryPackage (ExportOORRecoveryPackageRequest) + returns (ExportOORRecoveryPackageResponse); + // SendVTXO initiates an in-round transfer by submitting a refresh // request to the round coordinator. The transfer completes when the // next round commits. @@ -919,6 +927,11 @@ message NewReceiveScriptRequest { // prefix keys with an application or tenant identity when they share one // daemon. string idempotency_key = 2; + + // identity_key registers the daemon's durable identity key instead of + // deriving a fresh receive key. This is reserved for restart-stable + // protocol destinations such as Ark channel refresh payouts. + bool identity_key = 3; } message NewReceiveScriptResponse { @@ -1331,6 +1344,17 @@ message PrepareOORResponse { string session_id = 4; } +message ExportOORRecoveryPackageRequest { + // source identifies one exact output in a sender-owned finalized OOR + // package. + arkchannelrpc.OORRecoverySource source = 1; +} + +message ExportOORRecoveryPackageResponse { + // recovery contains the complete endpoint-neutral source lineage. + arkchannelrpc.ChannelRecoveryPackage recovery = 1; +} + message SignOORCustomInputRequest { // custom_input describes the vHTLC/custom VTXO and selected spend path. CustomOORInput custom_input = 1; diff --git a/waverpc/daemon.yaml b/waverpc/daemon.yaml index a808b26c1..ee5384f52 100644 --- a/waverpc/daemon.yaml +++ b/waverpc/daemon.yaml @@ -65,6 +65,9 @@ http: - selector: waverpc.DaemonService.GetIndexedOORSessionByTxid post: /v1/daemon/get-indexed-oor-session-by-txid body: "*" + - selector: waverpc.DaemonService.ExportOORRecoveryPackage + post: /v1/daemon/export-oor-recovery-package + body: "*" - selector: waverpc.DaemonService.SendVTXO post: /v1/daemon/send-vtxo body: "*" diff --git a/waverpc/daemon_grpc.pb.go b/waverpc/daemon_grpc.pb.go index 77f8e6467..afa8a4276 100644 --- a/waverpc/daemon_grpc.pb.go +++ b/waverpc/daemon_grpc.pb.go @@ -36,6 +36,7 @@ const ( DaemonService_GetIndexedVTXOByPkScript_FullMethodName = "/waverpc.DaemonService/GetIndexedVTXOByPkScript" DaemonService_GetVTXOExpiryInfo_FullMethodName = "/waverpc.DaemonService/GetVTXOExpiryInfo" DaemonService_GetIndexedOORSessionByTxid_FullMethodName = "/waverpc.DaemonService/GetIndexedOORSessionByTxid" + DaemonService_ExportOORRecoveryPackage_FullMethodName = "/waverpc.DaemonService/ExportOORRecoveryPackage" DaemonService_SendVTXO_FullMethodName = "/waverpc.DaemonService/SendVTXO" DaemonService_SendOOR_FullMethodName = "/waverpc.DaemonService/SendOOR" DaemonService_PrepareOOR_FullMethodName = "/waverpc.DaemonService/PrepareOOR" @@ -142,6 +143,10 @@ type DaemonServiceClient interface { // GetIndexedOORSessionByTxid queries the authoritative indexer for one // OOR session using a spent script proof and deterministic session txid. GetIndexedOORSessionByTxid(ctx context.Context, in *GetIndexedOORSessionByTxidRequest, opts ...grpc.CallOption) (*GetIndexedOORSessionByTxidResponse, error) + // ExportOORRecoveryPackage returns the immutable local OOR package and + // round ancestry for one exact output. The caller must already know the + // output tuple; the daemon verifies it against its finalized artifacts. + ExportOORRecoveryPackage(ctx context.Context, in *ExportOORRecoveryPackageRequest, opts ...grpc.CallOption) (*ExportOORRecoveryPackageResponse, error) // SendVTXO initiates an in-round transfer by submitting a refresh // request to the round coordinator. The transfer completes when the // next round commits. @@ -499,6 +504,16 @@ func (c *daemonServiceClient) GetIndexedOORSessionByTxid(ctx context.Context, in return out, nil } +func (c *daemonServiceClient) ExportOORRecoveryPackage(ctx context.Context, in *ExportOORRecoveryPackageRequest, opts ...grpc.CallOption) (*ExportOORRecoveryPackageResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ExportOORRecoveryPackageResponse) + err := c.cc.Invoke(ctx, DaemonService_ExportOORRecoveryPackage_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *daemonServiceClient) SendVTXO(ctx context.Context, in *SendVTXORequest, opts ...grpc.CallOption) (*SendVTXOResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(SendVTXOResponse) @@ -972,6 +987,10 @@ type DaemonServiceServer interface { // GetIndexedOORSessionByTxid queries the authoritative indexer for one // OOR session using a spent script proof and deterministic session txid. GetIndexedOORSessionByTxid(context.Context, *GetIndexedOORSessionByTxidRequest) (*GetIndexedOORSessionByTxidResponse, error) + // ExportOORRecoveryPackage returns the immutable local OOR package and + // round ancestry for one exact output. The caller must already know the + // output tuple; the daemon verifies it against its finalized artifacts. + ExportOORRecoveryPackage(context.Context, *ExportOORRecoveryPackageRequest) (*ExportOORRecoveryPackageResponse, error) // SendVTXO initiates an in-round transfer by submitting a refresh // request to the round coordinator. The transfer completes when the // next round commits. @@ -1210,6 +1229,9 @@ func (UnimplementedDaemonServiceServer) GetVTXOExpiryInfo(context.Context, *GetV func (UnimplementedDaemonServiceServer) GetIndexedOORSessionByTxid(context.Context, *GetIndexedOORSessionByTxidRequest) (*GetIndexedOORSessionByTxidResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method GetIndexedOORSessionByTxid not implemented") } +func (UnimplementedDaemonServiceServer) ExportOORRecoveryPackage(context.Context, *ExportOORRecoveryPackageRequest) (*ExportOORRecoveryPackageResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ExportOORRecoveryPackage not implemented") +} func (UnimplementedDaemonServiceServer) SendVTXO(context.Context, *SendVTXORequest) (*SendVTXOResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method SendVTXO not implemented") } @@ -1657,6 +1679,24 @@ func _DaemonService_GetIndexedOORSessionByTxid_Handler(srv interface{}, ctx cont return interceptor(ctx, in, info, handler) } +func _DaemonService_ExportOORRecoveryPackage_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ExportOORRecoveryPackageRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DaemonServiceServer).ExportOORRecoveryPackage(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: DaemonService_ExportOORRecoveryPackage_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DaemonServiceServer).ExportOORRecoveryPackage(ctx, req.(*ExportOORRecoveryPackageRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _DaemonService_SendVTXO_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SendVTXORequest) if err := dec(in); err != nil { @@ -2445,6 +2485,10 @@ var DaemonService_ServiceDesc = grpc.ServiceDesc{ MethodName: "GetIndexedOORSessionByTxid", Handler: _DaemonService_GetIndexedOORSessionByTxid_Handler, }, + { + MethodName: "ExportOORRecoveryPackage", + Handler: _DaemonService_ExportOORRecoveryPackage_Handler, + }, { MethodName: "SendVTXO", Handler: _DaemonService_SendVTXO_Handler, diff --git a/waverpc/daemon_mailboxrpc.pb.go b/waverpc/daemon_mailboxrpc.pb.go index 2e9a93e93..34fb36753 100644 --- a/waverpc/daemon_mailboxrpc.pb.go +++ b/waverpc/daemon_mailboxrpc.pb.go @@ -58,6 +58,8 @@ type DaemonServiceMailboxServer interface { GetVTXOExpiryInfo(ctx context.Context, req *GetVTXOExpiryInfoRequest) (*GetVTXOExpiryInfoResponse, error) // GetIndexedOORSessionByTxid handles GetIndexedOORSessionByTxid. GetIndexedOORSessionByTxid(ctx context.Context, req *GetIndexedOORSessionByTxidRequest) (*GetIndexedOORSessionByTxidResponse, error) + // ExportOORRecoveryPackage handles ExportOORRecoveryPackage. + ExportOORRecoveryPackage(ctx context.Context, req *ExportOORRecoveryPackageRequest) (*ExportOORRecoveryPackageResponse, error) // SendVTXO handles SendVTXO. SendVTXO(ctx context.Context, req *SendVTXORequest) (*SendVTXOResponse, error) // SendOOR handles SendOOR. @@ -312,6 +314,16 @@ func RegisterDaemonServiceMailboxServer(r rpc.Router, impl DaemonServiceMailboxS return impl.GetIndexedOORSessionByTxid(ctx, req) }) + r.Handle("waverpc.DaemonService", "ExportOORRecoveryPackage", func() proto.Message { + return &ExportOORRecoveryPackageRequest{} + }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { + req, ok := msg.(*ExportOORRecoveryPackageRequest) + if !ok { + return nil, fmt.Errorf("unexpected request type: %T", msg) + } + + return impl.ExportOORRecoveryPackage(ctx, req) + }) r.Handle("waverpc.DaemonService", "SendVTXO", func() proto.Message { return &SendVTXORequest{} }, func(ctx context.Context, msg proto.Message) (proto.Message, error) { @@ -1105,6 +1117,29 @@ func (c *DaemonServiceMailboxClient) GetIndexedOORSessionByTxid(ctx context.Cont return resp, nil } +// ExportOORRecoveryPackage calls the ExportOORRecoveryPackage RPC. +func (c *DaemonServiceMailboxClient) ExportOORRecoveryPackage(ctx context.Context, req *ExportOORRecoveryPackageRequest, opts ...rpc.RPCOptions) (*ExportOORRecoveryPackageResponse, error) { + var opt rpc.RPCOptions + if len(opts) > 0 { + opt = opts[0] + } + + result, err := c.C.SendRPC(ctx, rpc.ServiceMethod{ + Service: "waverpc.DaemonService", + Method: "ExportOORRecoveryPackage", + }, req, opt) + if err != nil { + return nil, err + } + + resp := new(ExportOORRecoveryPackageResponse) + if err := c.C.AwaitRPC(ctx, result.CorrelationID, resp); err != nil { + return nil, err + } + + return resp, nil +} + // SendVTXO calls the SendVTXO RPC. func (c *DaemonServiceMailboxClient) SendVTXO(ctx context.Context, req *SendVTXORequest, opts ...rpc.RPCOptions) (*SendVTXOResponse, error) { var opt rpc.RPCOptions