Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .github/workflows/mobile-bindings.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ on:
pull_request:
paths:
- "sdk/wavewalletdk/**"
- "cmd/wavewalletdk-wasm/**"
- "arkchannel/**"
- "lnruntime/**"
- "rpc/arkchannelrpc/**"
- "rpc/wavewalletrpc/**"
- "waved/*ark_channel*"
- "sdk/swaps/**"
- "db/**"
- "lwwallet/**"
Expand Down Expand Up @@ -125,6 +131,16 @@ jobs:
-exec="$(go env GOROOT)/lib/wasm/go_js_wasm_exec" \
-run '^TestWASM.*OpenRetry$' ./db ./lwwallet

- name: Test channel bindings and persistent storage under WASM
if: matrix.sqlite == 'host'
run: |
go mod download github.com/lightninglabs/go-wasmsqlite
sqlite_dir=$(go list -m -f '{{.Dir}}' github.com/lightninglabs/go-wasmsqlite)
GOOS=js GOARCH=wasm go test -tags="${MOBILE_TAGS}" \
-exec="node ${sqlite_dir}/scripts/node-wasm-test-exec.cjs" \
-run '^Test(ChannelSQLReopen|WASMArkChannelDispatch|ArkChannelBindingDispatch)$' \
./db ./cmd/wavewalletdk-wasm ./sdk/wavewalletdk/mobile

- name: Test mobile facade and SQLite stores
env:
SQLITE_TAGS: ${{ matrix.tags }}
Expand Down
1 change: 1 addition & 0 deletions cmd/wavecli/waveclicommands/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ Every command prints the raw protobuf JSON response.
| `channel create <amount-sat>` | `PromoteVTXO` | Promote wallet value into a channel; the daemon derives the protocol terms from capacity |
| `channel get <channel-id>` | `GetChannel` | Show one durable channel snapshot and live balances when available |
| `channel list` | `ListChannels` | List channels that still need recovery, observation, or operator action |
| `channel receive <amount-sat>` | `StartReceive` | Issue an invoice on an existing active channel; requires `--swap.arkchannelsenabled` |
| `channel pay <bolt11>` | `PayLightningInvoice` | Hold the private channel leg while the hub pays a public Lightning invoice; `--max-fee-sat` defaults to 1,000 |
| `channel close <channel-id>` | `RequestCooperativeClose` | Start or resume the client-owned cooperative close |
| `channel force-close <channel-id>` | `MaterializeAndForceClose` | Publish the Ark ancestry, signed backing, and latest commitment |
Expand Down
1 change: 1 addition & 0 deletions cmd/wavecli/waveclicommands/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ Every command prints the raw protobuf JSON response.
| `channel create <amount-sat>` | `PromoteVTXO` | Promote wallet value into a channel; the daemon derives the protocol terms from capacity |
| `channel get <channel-id>` | `GetChannel` | Show one durable channel snapshot and live balances when available |
| `channel list` | `ListChannels` | List channels that still need recovery, observation, or operator action |
| `channel receive <amount-sat>` | `StartReceive` | Issue an invoice on an existing active channel; requires `--swap.arkchannelsenabled` |
| `channel pay <bolt11>` | `PayLightningInvoice` | Hold the private channel leg while the hub pays a public Lightning invoice; `--max-fee-sat` defaults to 1,000 |
| `channel close <channel-id>` | `RequestCooperativeClose` | Start or resume the client-owned cooperative close |
| `channel force-close <channel-id>` | `MaterializeAndForceClose` | Publish the Ark ancestry, signed backing, and latest commitment |
Expand Down
51 changes: 49 additions & 2 deletions cmd/wavecli/waveclicommands/cmd_channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"time"

"github.com/lightninglabs/wavelength/rpc/arkchannelrpc"
"github.com/lightninglabs/wavelength/rpc/swapclientrpc"
"github.com/spf13/cobra"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
Expand Down Expand Up @@ -44,8 +45,8 @@ func newChannelCmd() *cobra.Command {
}
cmd.AddCommand(
newChannelCreateCmd(), newChannelGetCmd(), newChannelListCmd(),
newChannelPayCmd(), newChannelRefreshCmd(),
newChannelForceCloseCmd(),
newChannelPayCmd(), newChannelReceiveCmd(),
newChannelRefreshCmd(), newChannelForceCloseCmd(),
)

return cmd
Expand Down Expand Up @@ -269,6 +270,52 @@ func newChannelPayCmd() *cobra.Command {
return cmd
}

// newChannelReceiveCmd obtains an invoice bound to an existing active channel.
func newChannelReceiveCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "receive <amount-sat>",
Short: "Receive Lightning over an active channel",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
amount, err := parsePositiveChannelAmount(args[0])
if err != nil {
return err
}
conn, err := getDaemonConn(cmd)
if err != nil {
return err
}
defer conn.Close()
ctx, cancel := rpcContext(cmd)
defer cancel()
memo, _ := cmd.Flags().GetString("memo")
client := swapclientrpc.NewSwapClientServiceClient(conn)
resp, err := client.StartReceive(
ctx, &swapclientrpc.StartReceiveRequest{
AmountSat: amount,
Memo: memo,
ActiveChannelOnly: true,
},
)
if err != nil {
return err
}
// Older daemons ignore the request flag. Do not publish
// a swap invoice if the daemon did not reserve a
// channel.
if len(resp.GetSwap().GetChannelId()) != 32 {
return fmt.Errorf("daemon did not reserve an " +
"active channel")
}

return printJSON(resp)
},
}
cmd.Flags().String("memo", "", "invoice description")

return cmd
}

// newChannelRefreshCmd settles one clean channel into replacement VTXOs.
func newChannelRefreshCmd() *cobra.Command {
return channelIDCommand(
Expand Down
10 changes: 6 additions & 4 deletions cmd/wavecli/waveclicommands/cmd_channel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,10 +161,12 @@ func TestChannelCommandRecoveryFlags(t *testing.T) {
_, _, err = root.Find([]string{"close"})
require.ErrorContains(t, err, "unknown command")

for _, method := range []string{"send", "receive"} {
_, _, err := root.Find([]string{method})
require.ErrorContains(t, err, "unknown command")
}
receive, _, err := root.Find([]string{"receive"})
require.NoError(t, err)
require.Equal(t, "receive", receive.Name())
require.NotNil(t, receive.Flags().Lookup("memo"))
_, _, err = root.Find([]string{"send"})
require.ErrorContains(t, err, "unknown command")

pay := newChannelPayCmd()
maxFee, err := pay.Flags().GetUint64("max-fee-sat")
Expand Down
7 changes: 7 additions & 0 deletions cmd/wavecli/waveclicommands/devrpc/registry_generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

137 changes: 137 additions & 0 deletions cmd/wavewalletdk-wasm/ark_channel_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
//go:build js && wasm

package main

import (
"errors"
"syscall/js"
"testing"

"github.com/stretchr/testify/require"
)

// callWalletJS invokes the registered function from JS and waits for its
// Promise, retaining both callbacks until the Promise settles.
func callWalletJS(method string, body map[string]any) (js.Value, error) {
type result struct {
value js.Value
err error
}
done := make(chan result, 1)
resolve := js.FuncOf(func(_ js.Value, args []js.Value) any {
done <- result{value: args[0]}

return nil
})
defer resolve.Release()
reject := js.FuncOf(func(_ js.Value, args []js.Value) any {
done <- result{err: errors.New(args[0].Get("message").String())}

return nil
})
defer reject.Release()
js.Global().Call("wavewalletdkCall", method, body).Call(
"then", resolve, reject,
)
res := <-done

return res.value, res.err
}

// TestWASMArkChannelDispatch runs the JS -> mobile -> embedded RPC path on a
// fresh wallet. Specific handler rejections prove that valid request fields
// reached a registered RPC; unknown verbs or generic failures do not suffice.
func TestWASMArkChannelDispatch(t *testing.T) {
call := installWalletCall()
defer call.Release()
cfg := map[string]any{
"data_dir": t.TempDir(),
"network": "regtest",
"wallet_type": "lwwallet",
"wallet_esplora_url": "http://127.0.0.1:1",
"server_address": "http://127.0.0.1:1",
"server_transport": "rest",
"server_insecure": true,
"swap_server_address": "http://127.0.0.1:1",
"swap_server_transport": "rest",
"swap_server_insecure": true,
}
_, err := callWalletJS("start", cfg)
require.NoError(t, err)
_, err = callWalletJS("promoteVTXO", map[string]any{
"AmountSat": 5000, "IdempotencyKey": "not-admitted",
})
require.ErrorContains(t, err, "operations are disabled")
_, err = callWalletJS("payOnActiveChannel", map[string]any{
"Invoice": "ln-pay",
})
require.ErrorContains(t, err, "operations are disabled")
_, err = callWalletJS("stop", nil)
require.NoError(t, err)
cfg["ark_channels_enabled"] = true
_, err = callWalletJS("start", cfg)
require.NoError(t, err)
defer func() {
_, err := callWalletJS("stop", nil)
require.NoError(t, err)
}()

for _, tc := range []struct {
method string
req map[string]any
want string
}{
{
"promoteVTXO",
map[string]any{
"AmountSat": 5000,
},
"idempotency key is required",
},
{
"promoteVTXO",
map[string]any{
"AmountSat": 5000,
"IdempotencyKey": "one",
},
"runtime is not ready",
},
{
"payOnActiveChannel",
map[string]any{},
"payment request is required",
},
{
"payOnActiveChannel",
map[string]any{
"Invoice": "ln-pay",
"MaxFeeSat": 1,
},
"runtime is not ready",
},
{
"receiveOnActiveChannel",
map[string]any{
"AmountSat": 5000,
},
"create active-channel receive invoice:",
},
{
"receive",
map[string]any{
"AmountSat": 5000,
},
"create receive invoice:",
},
} {
t.Run(tc.method, func(t *testing.T) {
_, err := callWalletJS(tc.method, tc.req)
require.ErrorContains(t, err, tc.want)
if tc.method == "receive" || tc.method == "receiveOnActiveChannel" {
require.ErrorContains(
t, err, "wallet is not ready",
)
}
})
}
}
19 changes: 18 additions & 1 deletion cmd/wavewalletdk-wasm/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,22 @@ import (
// main installs the private browser transport entry point and then parks the Go
// runtime so the exported callbacks stay live for the lifetime of the page.
func main() {
js.Global().Set("wavewalletdkCall", js.FuncOf(walletCall))
installWalletCall()
js.Global().Call("dispatchEvent", js.Global().Get("CustomEvent").New(
"wavewalletdk-ready",
))

select {}
}

// installWalletCall exposes the dispatch callback for the lifetime of the VM.
func installWalletCall() js.Func {
call := js.FuncOf(walletCall)
js.Global().Set("wavewalletdkCall", call)

return call
}

// walletCall is the private JS transport dispatcher used by a typed host SDK.
// It takes a method name and an optional request object and returns a Promise
// that resolves with the verb's JSON response decoded into a JS value (or
Expand Down Expand Up @@ -135,6 +143,15 @@ func walletCall(_ js.Value, args []js.Value) any {
case "lookupReceive":
return promise(jsonVerb(req, mobile.LookupReceive))

case "promoteVTXO":
return promise(jsonVerb(req, mobile.PromoteVTXO))

case "receiveOnActiveChannel":
return promise(jsonVerb(req, mobile.ReceiveOnActiveChannel))

case "payOnActiveChannel":
return promise(jsonVerb(req, mobile.PayOnActiveChannel))

case "prepareSend":
return promise(jsonVerb(req, mobile.PrepareSend))

Expand Down
66 changes: 66 additions & 0 deletions docs/ark-channel-lifecycle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Ark channels: open first, pay on an active channel

Opening a channel and receiving a payment are separate operations. The client
can promote wallet VTXOs through the prepared out-of-round (OOR) transfer.
The funding wallet must not release that transfer until both lnd endpoints
have enforceable commitments and the signed VTXO-to-channel backing. Neither
the funding script nor its delays change.

Only the client opens the channel. It uses the authenticated hub mailbox to
register the promotion, coordinate signatures, and install the finalized
source recovery package. The separate Lightning peer transport carries lnd's
opening messages, commitment updates, and reestablishment in both directions.
After installation, either endpoint can materialize and force close using its
own durable state without a request to the other.

An invoice can use an existing channel with inbound capacity. Selecting that
channel does not reserve its balance until the payer arrives. If capacity
changes, the payment can fail; it cannot fund a new channel or switch to a
vHTLC under the same invoice. A wallet without a suitable channel can receive
through the ordinary vHTLC flow and later promote its wallet funds.

## Cooperative settlement

1. The client asks for the hub's payout destination and saves both destinations.
This first query does not stop either link.
2. The client quiesces its lnd link and proposes the payout from its clean
commitment. The hub checks its own clean lnd balances, commitment height,
source, and destination. It saves the exact signed authorization before
returning it. A lost signing reply is not permission to reopen the link.
3. The client saves the authorization and returns a digest of the two hub
signatures. The unsigned transaction ID would not prove receipt. Only
then may the client submit the 3-of-3 spend through the usual OOR flow.
4. The client records the completed OOR and reports its ID. A hub with a
payout checks the wallet's completed OOR session for its exact output,
not today's list of spendable VTXOs. A hub without a payout needs the
authenticated client report. Each endpoint archives its own lnd record.
No subsequent acknowledgment of local archival is needed.

This close unrolls nothing. The wallets retain their replacement VTXOs and
ancestry watches. On a force close, Ark instead materializes the pre-agreed
funding outpoint. lnd's chain arbitrator and sweeper resolve the channel.

## Two boundaries to keep

**Transport.** Ark commands still need authenticated, durable delivery. A
retry of an exact close proposal, signature receipt, or OOR result goes to
the channel FSM, not a second execution journal. An unsigned abort is
different: a delayed duplicate must not abort a later attempt.

A live connection for Lightning frames is a separate transport change.
The current sender promises durable admission; a WebSocket write cannot
satisfy that promise. A replacement could carry ordered binary frames over
an outbound authenticated connection, bind it to one peer, fence its old
connection on resume, and start with lnd's channel reestablishment. Only
then could it replace the per-frame mailbox and ingress receipts. It would
not replace durable Ark commands, lnd's circuit database, or chain watches
while a device sleeps.

**Forwarding.** SwapDK's public lnd is reached through RPC; its private Ark
links share a different in-process lnd switch. The payment bridge therefore
still owns the relationship between two HTLCs, including their hash, nested
deadlines, and settlement after restart. To remove the bridge, the operator
would need to host its public and Ark links in the same switch and circuit
database, with consistent peer identities, channel aliases, fees, and
onion forwarding. That experiment belongs on the operator. It needs no
second switch, public graph, or pathfinder in the client.
Loading
Loading