diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4bbb938..7904501 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,6 +71,7 @@ jobs: - run: pnpm --filter @lightninglabs/wavelength-core test - run: pnpm --filter @lightninglabs/wavelength-web test - run: pnpm --filter @lightninglabs/wavelength-react test + - run: pnpm --filter @lightninglabs/wavelength-react-native test # Validate the packed packages: publint for packaging mistakes, attw for # type/runtime resolution across consumer modes (Node ESM, bundlers). - run: pnpm check:packages diff --git a/packages/core/src/base-client.test.ts b/packages/core/src/base-client.test.ts index 1347335..2dc1ff2 100644 --- a/packages/core/src/base-client.test.ts +++ b/packages/core/src/base-client.test.ts @@ -24,7 +24,9 @@ class FakeClient extends BaseWavelengthClient { params: unknown = {}, ): Promise { this.calls.push({ method, params }); - return Promise.resolve((this.responses.get(method) ?? {}) as T); + const response = this.responses.get(method); + if (response instanceof Error) return Promise.reject(response); + return Promise.resolve((response ?? {}) as T); } protected openActivityStream(opts: ActivityStreamOptions): Promise { @@ -224,6 +226,115 @@ describe('BaseWavelengthClient', () => { assert.equal(result.paymentHash, 'ph'); }); + describe('explicit Ark channel calls', () => { + const channelId = '01'.repeat(32); + const amountSat = 4_294_967_297; // Must survive a 32-bit boundary. + const idempotencyKey = ' promotion-1 '; + const invoice = 'ln-channel-invoice'; + + it('preserves the promotion amount and caller key across explicit retries', async () => { + const client = new FakeClient(); + client.responses.set('promoteVTXO', { + ChannelID: channelId, Phase: 'Active', CapacitySat: amountSat, + }); + for (let i = 0; i < 2; i++) { + assert.deepEqual(await client.promoteVTXO({ amountSat, idempotencyKey }), { + channelId, phase: 'Active', capacitySat: amountSat, + }); + } + const call = { + method: 'promoteVTXO', + params: { AmountSat: amountSat, IdempotencyKey: idempotencyKey }, + }; + assert.deepEqual(client.calls, [call, call]); + }); + + it('dispatches the exact fee cap and returns the normalized payment proof', async () => { + const client = new FakeClient(); + const paymentHash = 'ab'.repeat(32); + const preimage = 'cd'.repeat(32); + for (const feeSat of [0, 5]) { + client.responses.set('payOnActiveChannel', { + ChannelID: channelId, PaymentHash: paymentHash, Preimage: preimage, + PrivateAmountSat: amountSat, FeeSat: feeSat, + }); + assert.deepEqual(await client.payOnActiveChannel({ invoice, maxFeeSat: feeSat }), { + channelId, paymentHash, preimage, privateAmountSat: amountSat, feeSat, + }); + } + assert.deepEqual(client.calls, [0, 5].map((maxFeeSat) => ({ + method: 'payOnActiveChannel', params: { Invoice: invoice, MaxFeeSat: maxFeeSat }, + }))); + }); + + it('issues a channel invoice and normalizes its nested activity entry', async () => { + const client = new FakeClient(); + client.responses.set('receiveOnActiveChannel', { + Invoice: invoice, Entry: { ID: 'receive-1', Progress: null, Request: null }, + }); + const memo = 'inbound'; + assert.deepEqual(await client.receiveOnActiveChannel({ amountSat, memo }), { + invoice, entry: { id: 'receive-1', progress: undefined, request: undefined }, + }); + assert.deepEqual(client.calls, [{ + method: 'receiveOnActiveChannel', params: { AmountSat: amountSat, Memo: memo }, + }]); + }); + + it('rejects non-JSON and inexact satoshis before dispatch', async () => { + const client = new FakeClient(); + const invalid = { code: 'invalid_channel_request' }; + for (const value of [-1, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1, + 1n, 2n ** 63n, '123', null, undefined]) { + // Untyped hosts can pass values that TS would have rejected. + const sats = value as number; + await assert.rejects(client.promoteVTXO({ amountSat: sats, idempotencyKey }), invalid); + await assert.rejects(client.receiveOnActiveChannel({ amountSat: sats }), invalid); + await assert.rejects(client.payOnActiveChannel({ invoice, maxFeeSat: sats }), invalid); + } + await assert.rejects(client.promoteVTXO({ amountSat: 0, idempotencyKey }), invalid); + await assert.rejects(client.receiveOnActiveChannel({ amountSat: 0 }), invalid); + assert.deepEqual(client.calls, []); + }); + + it('requires a wire-stable caller key and a nonempty invoice', async () => { + const client = new FakeClient(); + const invalid = { code: 'invalid_channel_request' }; + // U+1F511 takes two JS code units but four UTF-8 bytes. + const boundaryKey = '\u{1F511}'.repeat(32); + for (const key of ['', undefined, 1, 'x'.repeat(129), boundaryKey + 'x', '\uD800']) { + await assert.rejects(client.promoteVTXO({ amountSat, idempotencyKey: key as string }), invalid); + } + await assert.rejects(client.payOnActiveChannel({ invoice: '', maxFeeSat: 0 }), invalid); + await assert.rejects(client.receiveOnActiveChannel({ amountSat, memo: 1n as never }), invalid); + assert.deepEqual(client.calls, []); + await client.promoteVTXO({ amountSat, idempotencyKey: boundaryKey }); + assert.deepEqual(client.calls, [{ + method: 'promoteVTXO', params: { AmountSat: amountSat, IdempotencyKey: boundaryKey }, + }]); + }); + + it('propagates daemon and older-runtime errors without retry or fallback', async () => { + const client = new FakeClient(); + const operations = { + promoteVTXO: () => client.promoteVTXO({ amountSat, idempotencyKey }), + payOnActiveChannel: () => client.payOnActiveChannel({ invoice, maxFeeSat: 0 }), + receiveOnActiveChannel: () => client.receiveOnActiveChannel({ amountSat }), + }; + for (const [method, invoke] of Object.entries(operations)) { + for (const error of [ + new Error('rpc error: code = FailedPrecondition desc = no liquidity'), + new WavelengthError(`unsupported facade method: ${method}`, 'unsupported_facade_method'), + ]) { + client.responses.set(method, error); + client.calls.length = 0; + await assert.rejects(invoke, (err) => err === error); + assert.deepEqual(client.calls.map((call) => call.method), [method]); + } + } + }); + }); + it('forwards list kinds and both exit variants exactly', async () => { const client = new FakeClient(); await client.list({ view: 'activity', kinds: ['send', 'exit'] }); diff --git a/packages/core/src/base-client.ts b/packages/core/src/base-client.ts index 1dba78b..2379924 100644 --- a/packages/core/src/base-client.ts +++ b/packages/core/src/base-client.ts @@ -8,6 +8,8 @@ import type { GetExitPlanRequest, ListRequest, OpenWalletFromPasskeyRequest, + PayOnActiveChannelRequest, + PromoteVTXORequest, ReceiveRequest, SendRequest, SweepWalletRequest, @@ -25,14 +27,16 @@ import type { GetExitPlanResult, ListResult, OpenWalletFromPasskeyResult, + PayOnActiveChannelResult, PrepareSendResult, + PromoteVTXOResult, ReceiveResult, SendResult, SweepWalletResult, UnlockWalletResult, } from './results.ts'; import { validateRuntimeConfig, type RuntimeConfig } from './config.ts'; -import type { ExternalSeedWalletClient } from './client.ts'; +import type { ArkChannelClient, ExternalSeedWalletClient } from './client.ts'; import type { WavelengthEvent, WavelengthListener } from './events.ts'; import type { WalletInfo, WalletStatus } from './state.ts'; import type { FacadeMethod, ServerTransport } from './facade.ts'; @@ -40,6 +44,9 @@ import { assertFacadeMethod, toExternalSeedWalletStartParams, toGoCreateWalletReq, + toGoPayOnActiveChannelReq, + toGoPromoteVTXOReq, + toGoReceiveOnActiveChannelReq, toGoUnlockWalletReq, toMobileConfig, } from './facade.ts'; @@ -55,8 +62,8 @@ import { } from './activity-options.ts'; /** - * Implements the transport-agnostic half of - * {@link ExternalSeedWalletClient}: every RPC verb is expressed in terms of + * Implements {@link ExternalSeedWalletClient} and {@link ArkChannelClient} + * across transports: every RPC verb is expressed in terms of * the abstract invokeFacade, so a transport (web wasm, React Native gomobile, * or a future one) supplies only the pipe: invokeFacade, ready, the * activity-stream plumbing, and its {@link ServerTransport} flavor. The shared @@ -64,7 +71,8 @@ import { * catalog, public contract, native dispatch, and response normalization remain * separate synchronization points. */ -export abstract class BaseWavelengthClient implements ExternalSeedWalletClient { +export abstract class BaseWavelengthClient + implements ExternalSeedWalletClient, ArkChannelClient { protected readonly listeners = new Set(); // Serializes runtime lifecycle operations for transports that route start and @@ -269,6 +277,26 @@ export abstract class BaseWavelengthClient implements ExternalSeedWalletClient { return this.callFacade('receive', req); } + async promoteVTXO(req: PromoteVTXORequest): Promise { + return this.callFacade( + 'promoteVTXO', toGoPromoteVTXOReq(req), + ); + } + + async payOnActiveChannel( + req: PayOnActiveChannelRequest, + ): Promise { + return this.callFacade( + 'payOnActiveChannel', toGoPayOnActiveChannelReq(req), + ); + } + + async receiveOnActiveChannel(req: ReceiveRequest): Promise { + return this.callFacade( + 'receiveOnActiveChannel', toGoReceiveOnActiveChannelReq(req), + ); + } + // prepareSend quotes a payment without dispatching it, returning the fee and a // single-use sendIntentId. Pair it with sendPrepared for a quote -> confirm -> // pay flow; send() folds the two steps into one. diff --git a/packages/core/src/casing.ts b/packages/core/src/casing.ts index f37add6..6c4bf6b 100644 --- a/packages/core/src/casing.ts +++ b/packages/core/src/casing.ts @@ -10,6 +10,7 @@ export const ACRONYM_OVERRIDES: Record = { ID: 'id', VTXOs: 'vtxos', SendIntentID: 'sendIntentId', + ChannelID: 'channelId', }; // camelKey converts one Go/PascalCase field name to camelCase. Most names just diff --git a/packages/core/src/client.ts b/packages/core/src/client.ts index c3df088..00af781 100644 --- a/packages/core/src/client.ts +++ b/packages/core/src/client.ts @@ -13,6 +13,8 @@ import type { GetExitPlanRequest, ListRequest, OpenWalletFromPasskeyRequest, + PayOnActiveChannelRequest, + PromoteVTXORequest, ReceiveRequest, SendRequest, SweepWalletRequest, @@ -29,7 +31,9 @@ import type { GetExitPlanResult, ListResult, OpenWalletFromPasskeyResult, + PayOnActiveChannelResult, PrepareSendResult, + PromoteVTXOResult, ReceiveResult, SendResult, SweepWalletResult, @@ -41,8 +45,8 @@ import type { * wraps the embedded daemon's lifecycle, wallet operations, and activity * stream behind typed, camelCase-normalized methods. * - * External-seed startup is an additive transport capability; - * see {@link ExternalSeedWalletClient}. + * External-seed startup and Ark channel operations are additive capabilities; + * see {@link ExternalSeedWalletClient} and {@link ArkChannelClient}. */ export interface WavelengthClient { /** Resolves once the runtime assets are loaded and the client is usable. */ @@ -156,3 +160,20 @@ export interface ExternalSeedWalletClient extends WavelengthClient { req: ExternalSeedWalletRequest, ): Promise; } + +/** + * Explicit Ark channel operations on the official web and React Native clients. + * Enable them with {@link RuntimeConfig.arkChannelsEnabled} and a supporting + * runtime. Errors, including unsupported methods on older runtimes, reject + * the call. No method retries or falls back to a wallet swap. + */ +export interface ArkChannelClient extends WavelengthClient { + /** Promotes wallet funds under a caller-owned idempotency key. */ + promoteVTXO(req: PromoteVTXORequest): Promise; + /** Pays a BOLT-11 invoice from outbound channel liquidity up to the fee cap. */ + payOnActiveChannel( + req: PayOnActiveChannelRequest, + ): Promise; + /** Issues an invoice for a positive amount against existing inbound liquidity. */ + receiveOnActiveChannel(req: ReceiveRequest): Promise; +} diff --git a/packages/core/src/config.test.ts b/packages/core/src/config.test.ts index aab0e30..929a08f 100644 --- a/packages/core/src/config.test.ts +++ b/packages/core/src/config.test.ts @@ -75,6 +75,9 @@ describe('validateRuntimeConfig', () => { ], ['web Ark cert path', { arkServerTlsCertPath: '/tmp/ark.pem' }, 'rest'], ['web swap cert path', { swapServerTlsCertPath: '/tmp/swap.pem' }, 'rest'], + ['channels without swaps', { arkChannelsEnabled: true, disableSwaps: true }, 'rest'], + ['channels with btcwallet', { arkChannelsEnabled: true, walletType: 'btcwallet' }, 'grpc'], + ['nonboolean channel opt-in', { arkChannelsEnabled: 'true' as never }, 'grpc'], ['fractional buffer', { bufferSize: 1.5 }, 'grpc'], ['negative workers', { signingWorkers: -1 }, 'grpc'], ['unsafe fee', { maxOperatorFeeSat: Number.MAX_SAFE_INTEGER + 1 }, 'grpc'], diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index 7b69a42..87a6bdd 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -115,6 +115,11 @@ export type RuntimeConfig = { swapDatabaseFileName?: string; /** Disables Lightning swaps and omits every swap configuration field. */ disableSwaps?: boolean; + /** + * Enables explicit Ark channel operations with a supporting runtime. + * Requires the lwwallet backend and swaps. Defaults to false. + */ + arkChannelsEnabled?: boolean; /** * Maximum per-round operator fee the daemon accepts, in satoshis. Must be a * nonnegative safe integer. @@ -168,6 +173,17 @@ export function validateRuntimeConfig( if (walletType !== 'lwwallet' && walletType !== 'btcwallet') { invalidConfig(`unsupported walletType: ${String(walletType)}`); } + if ( + config.arkChannelsEnabled !== undefined && + typeof config.arkChannelsEnabled !== 'boolean' + ) { + invalidConfig('arkChannelsEnabled must be a boolean'); + } + if ( + config.arkChannelsEnabled && (config.disableSwaps || walletType !== 'lwwallet') + ) { + invalidConfig('arkChannelsEnabled requires swaps and walletType lwwallet'); + } if (config.network === 'mainnet' && config.allowMainnet !== true) { invalidConfig('mainnet requires allowMainnet: true'); } diff --git a/packages/core/src/errors.ts b/packages/core/src/errors.ts index c45c271..d30a64c 100644 --- a/packages/core/src/errors.ts +++ b/packages/core/src/errors.ts @@ -25,8 +25,10 @@ * `'asset_load_failed'` cover a downloaded, verified module that fails to * compile, which is not an asset problem and surfaces as `'wavelength_error'` * too. `'invalid_external_seed'` means an external-seed wallet request failed - * local validation. `'runtime_active'` means the client already has a runtime - * active and must stop it before selecting another external-seed profile. + * local validation. `'invalid_channel_request'` means a typed Ark channel + * request failed validation before dispatch. `'runtime_active'` means the client + * already has a runtime active and must stop it before selecting another + * external-seed profile. * The `(string & {})` arm keeps the union open for forward * compatibility while still offering autocomplete on the known codes. */ @@ -41,6 +43,7 @@ export type WavelengthErrorCode = | 'unsupported_facade_method' | 'invalid_cursor' | 'invalid_config' + | 'invalid_channel_request' | 'invalid_external_seed' | 'runtime_active' | (string & {}); diff --git a/packages/core/src/facade.test.ts b/packages/core/src/facade.test.ts index 570025c..5f5e14c 100644 --- a/packages/core/src/facade.test.ts +++ b/packages/core/src/facade.test.ts @@ -115,6 +115,16 @@ describe('toMobileConfig', () => { assert.equal(Object.hasOwn(defaulted, 'max_payment_cltv'), false); }); + it('forwards an explicit channel toggle and omits it for legacy configs', () => { + for (const transport of ['rest', 'grpc'] as const) { + for (const enabled of [true, false]) { + const config = toMobileConfig({ arkChannelsEnabled: enabled }, transport); + assert.equal(config.ark_channels_enabled, enabled); + } + assert.equal(Object.hasOwn(toMobileConfig({}, transport), 'ark_channels_enabled'), false); + } + }); + it('omits every swap field when swaps are disabled', () => { const out = toMobileConfig( { diff --git a/packages/core/src/facade.ts b/packages/core/src/facade.ts index 9de65eb..84ea1f2 100644 --- a/packages/core/src/facade.ts +++ b/packages/core/src/facade.ts @@ -2,6 +2,9 @@ import type { RuntimeConfig } from './config.ts'; import type { CreateWalletRequest, ExternalSeedWalletRequest, + PayOnActiveChannelRequest, + PromoteVTXORequest, + ReceiveRequest, UnlockWalletRequest, } from './requests.ts'; import { WavelengthError } from './errors.ts'; @@ -22,6 +25,9 @@ export const FACADE_METHODS = [ 'openWalletFromPasskey', 'deposit', 'receive', + 'promoteVTXO', + 'payOnActiveChannel', + 'receiveOnActiveChannel', 'prepareSend', 'sendPrepared', 'list', @@ -88,6 +94,7 @@ export type MobileConfig = { swap_server_transport?: ServerTransport; swap_server_insecure?: boolean; swap_database_file_name?: string; + ark_channels_enabled?: boolean; max_operator_fee_sat?: number; max_payment_cltv?: number; signing_workers?: number; @@ -130,6 +137,7 @@ export function toMobileConfig( network: config.network, debug_level: config.debugLevel, allow_mainnet: config.allowMainnet, + ark_channels_enabled: config.arkChannelsEnabled, server_address: config.arkServerAddress, server_tls_cert_path: config.arkServerTlsCertPath, server_transport: serverTransport, @@ -194,6 +202,10 @@ const BASE64_ALPHABET = * TextEncoder so it behaves identically in the browser, a worker, and Hermes. */ export function base64FromUtf8(value: string): string { + return base64FromBytes(utf8Bytes(value)); +} + +function utf8Bytes(value: string): Uint8Array { const bytes: number[] = []; for (const ch of value) { const cp = ch.codePointAt(0) as number; @@ -217,7 +229,7 @@ export function base64FromUtf8(value: string): string { } } - return base64FromBytes(Uint8Array.from(bytes)); + return Uint8Array.from(bytes); } /** @@ -270,3 +282,48 @@ export function toGoUnlockWalletReq(req: UnlockWalletRequest) { WalletPassword: req.password ? base64FromUtf8(req.password) : undefined, }; } + +// JSON cannot carry bigint and can silently round unsafe numbers. Check the +// caller's amount or fee cap before either transport serializes the request. +function channelSats(field: 'amountSat' | 'maxFeeSat', value: number): number { + const amount = field === 'amountSat'; + if (!Number.isSafeInteger(value) || value < (amount ? 1 : 0)) { + const range = amount ? 'positive' : 'nonnegative'; + throw new WavelengthError( + `${field} must be a ${range} safe integer`, 'invalid_channel_request', + ); + } + return value; +} + +/** Maps a promotion without deriving or rewriting its replay identity. */ +export function toGoPromoteVTXOReq({ amountSat, idempotencyKey }: PromoteVTXORequest) { + // Go enforces the key limit in bytes, not JS code units. Unpaired surrogates + // would decode as replacement characters and change the key on the wire. + if ( + typeof idempotencyKey !== 'string' || idempotencyKey.length === 0 || + idempotencyKey.length > 128 || /[\uD800-\uDFFF]/u.test(idempotencyKey) || + utf8Bytes(idempotencyKey).length > 128 + ) { + throw new WavelengthError( + 'idempotencyKey must be 1 to 128 UTF-8 bytes', 'invalid_channel_request', + ); + } + return { AmountSat: channelSats('amountSat', amountSat), IdempotencyKey: idempotencyKey }; +} + +/** Maps an explicit channel payment, including a zero fee cap. */ +export function toGoPayOnActiveChannelReq({ invoice, maxFeeSat }: PayOnActiveChannelRequest) { + if (typeof invoice !== 'string' || !invoice) { + throw new WavelengthError('invoice is required', 'invalid_channel_request'); + } + return { Invoice: invoice, MaxFeeSat: channelSats('maxFeeSat', maxFeeSat) }; +} + +/** Maps the same receive fields the daemon uses for an ordinary invoice. */ +export function toGoReceiveOnActiveChannelReq({ amountSat, memo }: ReceiveRequest) { + if (memo !== undefined && typeof memo !== 'string') { + throw new WavelengthError('memo must be a string', 'invalid_channel_request'); + } + return { AmountSat: channelSats('amountSat', amountSat), Memo: memo }; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index b5004d2..c5786d0 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -55,6 +55,8 @@ export type { GetExitPlanRequest, ListRequest, OpenWalletFromPasskeyRequest, + PayOnActiveChannelRequest, + PromoteVTXORequest, ReceiveRequest, RestoreWalletRequest, SendRequest, @@ -100,7 +102,9 @@ export type { OnchainHistory, OnchainTx, OpenWalletFromPasskeyResult, + PayOnActiveChannelResult, PrepareSendResult, + PromoteVTXOResult, ReceiveResult, SendRail, SendQuoteStatus, @@ -177,8 +181,9 @@ export type { } from './exit.ts'; // The stable client contract every transport implements, plus the additive -// capability used by caller-owned external-seed startup. +// capabilities for Ark channels and caller-owned external-seed startup. export type { + ArkChannelClient, ExternalSeedWalletClient, WavelengthClient, } from './client.ts'; diff --git a/packages/core/src/public-api-assertions.ts b/packages/core/src/public-api-assertions.ts index 94f77d9..0b9b5e5 100644 --- a/packages/core/src/public-api-assertions.ts +++ b/packages/core/src/public-api-assertions.ts @@ -16,6 +16,7 @@ import { } from './index.ts'; import type { ActivityStreamOptions, + ArkChannelClient, CreditPreview, DebugLevel, EntryFailureCode, @@ -33,6 +34,12 @@ import type { FacadeMethod, OnchainHistory, OnchainTx, + PayOnActiveChannelRequest, + PayOnActiveChannelResult, + PromoteVTXORequest, + PromoteVTXOResult, + ReceiveRequest, + ReceiveResult, RuntimeConfig, WavelengthClient, SendQuoteStatus, @@ -95,3 +102,16 @@ const _externalSeedClientIsLegacy: WavelengthClient = null as unknown as ExternalSeedWalletClient; void _legacyClientHasNoExternalSeedStart; void _externalSeedClientIsLegacy; + +// Ark channel calls are additive too; keep their root exports and signatures +// available without requiring custom clients to implement them. +type ChannelMethods = 'promoteVTXO' | 'payOnActiveChannel' | 'receiveOnActiveChannel'; +const _legacyClientHasNoChannels: + Extract extends never ? true : false = true; +const _channelMethods: { + promoteVTXO(req: PromoteVTXORequest): Promise; + payOnActiveChannel(req: PayOnActiveChannelRequest): Promise; + receiveOnActiveChannel(req: ReceiveRequest): Promise; +} = null as unknown as ArkChannelClient; +void _legacyClientHasNoChannels; +void _channelMethods; diff --git a/packages/core/src/requests.ts b/packages/core/src/requests.ts index 2b0e382..7d3605b 100644 --- a/packages/core/src/requests.ts +++ b/packages/core/src/requests.ts @@ -135,6 +135,25 @@ export type ReceiveRequest = { memo?: string; }; +/** Selects wallet liquidity to promote into an Ark channel. */ +export type PromoteVTXORequest = { + /** Amount to promote, in satoshis. Must be a positive safe integer. */ + amountSat: number; + /** + * Caller-owned key (1 to 128 UTF-8 bytes). Persist it before dispatch and + * reuse it unchanged when retrying the same promotion. + */ + idempotencyKey: string; +}; + +/** Authorizes payment of an invoice from existing outbound channel liquidity. */ +export type PayOnActiveChannelRequest = { + /** The signed BOLT-11 invoice to pay. */ + invoice: string; + /** Maximum fee in satoshis. A nonnegative safe integer; zero is explicit. */ + maxFeeSat: number; +}; + /** * Parameters for sending a payment, as a discriminated union: supply an * `invoice` for a Lightning send or an `onchainAddress` for an on-chain send. diff --git a/packages/core/src/response-normalization.ts b/packages/core/src/response-normalization.ts index 7ba7129..2f971ce 100644 --- a/packages/core/src/response-normalization.ts +++ b/packages/core/src/response-normalization.ts @@ -111,6 +111,7 @@ export function normalizeFacadeResult( return { ...result, inputs: nilSlice(result.inputs) } as T; case 'deposit': case 'receive': + case 'receiveOnActiveChannel': case 'sendPrepared': return { ...result, diff --git a/packages/core/src/results.ts b/packages/core/src/results.ts index d6725cc..0ad5050 100644 --- a/packages/core/src/results.ts +++ b/packages/core/src/results.ts @@ -9,6 +9,30 @@ import type { */ export type OpenWalletFromPasskeyResult = OpenWalletResult; +/** The durable channel state returned by a promotion. */ +export type PromoteVTXOResult = { + /** Hex-encoded channel identifier. */ + channelId: string; + /** The channel's lifecycle phase at the time of the reply. */ + phase: string; + /** Funded capacity in satoshis. */ + capacitySat: number; +}; + +/** A settled payment made from an active Ark channel. */ +export type PayOnActiveChannelResult = { + /** Hex-encoded identifier of the paying channel. */ + channelId: string; + /** Hex-encoded payment hash from the invoice. */ + paymentHash: string; + /** Hex-encoded proof of payment, verified by the daemon. */ + preimage: string; + /** Amount settled on the private channel leg, in satoshis. */ + privateAmountSat: number; + /** Fee paid, in satoshis. */ + feeSat: number; +}; + /** Result of atomically starting and opening an external-seed daemon wallet. */ export type ExternalSeedWalletOpenResult = { /** True when the seed was imported into a new local profile. */ diff --git a/packages/react-native/WavelengthReactNative.podspec b/packages/react-native/WavelengthReactNative.podspec index 1d7490e..3bebe87 100644 --- a/packages/react-native/WavelengthReactNative.podspec +++ b/packages/react-native/WavelengthReactNative.podspec @@ -11,7 +11,8 @@ Pod::Spec.new do |s| s.authors = "Lightning Labs" s.platforms = { :ios => "15.1" } s.source = { :git => "https://github.com/lightninglabs/wavelength-sdk.git" } - s.source_files = "ios/**/*.{h,mm,swift}" + s.source_files = "ios/**/*.{h,hpp,mm,swift}" + s.private_header_files = "ios/*.hpp" s.pod_target_xcconfig = { "DEFINES_MODULE" => "YES" } # The gomobile-built daemon. Not shipped in the npm package and gitignored diff --git a/packages/react-native/android/build.gradle b/packages/react-native/android/build.gradle index 1d04570..1a5b603 100644 --- a/packages/react-native/android/build.gradle +++ b/packages/react-native/android/build.gradle @@ -13,6 +13,7 @@ android { compileSdkVersion rootProject.hasProperty("compileSdkVersion") ? rootProject.ext.compileSdkVersion : 35 defaultConfig { + consumerProguardFiles "consumer-rules.pro" // The gomobile bindings are built with -androidapi 21; RN itself floors // higher, so inherit the app's minSdk when present. minSdkVersion rootProject.hasProperty("minSdkVersion") ? rootProject.ext.minSdkVersion : 24 diff --git a/packages/react-native/android/consumer-rules.pro b/packages/react-native/android/consumer-rules.pro new file mode 100644 index 0000000..d034350 --- /dev/null +++ b/packages/react-native/android/consumer-rules.pro @@ -0,0 +1,6 @@ +# Public gomobile methods looked up by name on channel-capable artifacts. +-keepclassmembers class engineering.lightning.wavewalletdk.mobile.Mobile { + public static byte[] promoteVTXO(byte[]); + public static byte[] payOnActiveChannel(byte[]); + public static byte[] receiveOnActiveChannel(byte[]); +} diff --git a/packages/react-native/android/src/main/java/engineering/lightning/wavelength/reactnative/ArkChannelBindings.kt b/packages/react-native/android/src/main/java/engineering/lightning/wavelength/reactnative/ArkChannelBindings.kt new file mode 100644 index 0000000..cab6086 --- /dev/null +++ b/packages/react-native/android/src/main/java/engineering/lightning/wavelength/reactnative/ArkChannelBindings.kt @@ -0,0 +1,37 @@ +package engineering.lightning.wavelength.reactnative + +import java.lang.reflect.InvocationTargetException +import java.lang.reflect.Modifier + +// v0.2.1 does not export these methods. Resolve only the public gomobile +// byte[] ABI, and require the whole feature before starting a channel wallet. +internal class ArkChannelBindings(facade: Class<*>) { + private val calls = listOf( + "promoteVTXO", "payOnActiveChannel", "receiveOnActiveChannel", + ).associateWith { name -> + try { + facade.getMethod(name, ByteArray::class.java).takeIf { + Modifier.isStatic(it.modifiers) && it.returnType == ByteArray::class.java + } + } catch (_: NoSuchMethodException) { + null + } + } + + val supported = calls.values.all { it != null } + + fun call(name: String, params: ByteArray): String { + val method = calls.getValue(name) + if (!supported || method == null) throw MissingArkChannels() + val bytes = try { + method.invoke(null, params) as ByteArray? + } catch (e: InvocationTargetException) { + // Reflection wraps the actual daemon exception, often with no message. + throw e.targetException + } + check(bytes != null && bytes.isNotEmpty()) { "$name returned no JSON" } + return bytes.decodeToString(throwOnInvalidSequence = true) + } +} + +internal class MissingArkChannels : Exception("Native bindings do not support Ark channels") diff --git a/packages/react-native/android/src/main/java/engineering/lightning/wavelength/reactnative/WavelengthModule.kt b/packages/react-native/android/src/main/java/engineering/lightning/wavelength/reactnative/WavelengthModule.kt index 0b4a1bb..a2441a7 100644 --- a/packages/react-native/android/src/main/java/engineering/lightning/wavelength/reactnative/WavelengthModule.kt +++ b/packages/react-native/android/src/main/java/engineering/lightning/wavelength/reactnative/WavelengthModule.kt @@ -37,9 +37,14 @@ class WavelengthModule(reactContext: ReactApplicationContext) : NativeWavelengthSpec(reactContext) { private val executor: ExecutorService = Executors.newCachedThreadPool() + private val arkChannels = ArkChannelBindings(Mobile::class.java) override fun getName(): String = NAME + override fun supportsArkChannels(promise: Promise) { + promise.resolve(arkChannels.supported) + } + override fun getDefaultDataDir(promise: Promise) { promise.resolve(File(reactApplicationContext.filesDir, "wavelength").absolutePath) } @@ -145,6 +150,8 @@ class WavelengthModule(reactContext: ReactApplicationContext) : executor.execute { try { promise.resolve(dispatch(method, paramsJson)) + } catch (e: MissingArkChannels) { + promise.reject("unsupported_facade_method", e.message, e) } catch (e: Throwable) { promise.reject(ERROR_CODE, e.message ?: "wavelength call failed", e) } @@ -168,6 +175,8 @@ class WavelengthModule(reactContext: ReactApplicationContext) : "openWalletFromPasskey" -> Mobile.openWalletFromPasskey(params).toString(Charsets.UTF_8) "deposit" -> Mobile.deposit(params).toString(Charsets.UTF_8) "receive" -> Mobile.receive(params).toString(Charsets.UTF_8) + "promoteVTXO", "payOnActiveChannel", "receiveOnActiveChannel" -> + arkChannels.call(method, params) "prepareSend" -> Mobile.prepareSend(params).toString(Charsets.UTF_8) "sendPrepared" -> Mobile.sendPrepared(params).toString(Charsets.UTF_8) "list" -> Mobile.list(params).toString(Charsets.UTF_8) diff --git a/packages/react-native/ios/WavelengthArkBindings.hpp b/packages/react-native/ios/WavelengthArkBindings.hpp new file mode 100644 index 0000000..d46d04d --- /dev/null +++ b/packages/react-native/ios/WavelengthArkBindings.hpp @@ -0,0 +1,32 @@ +#pragma once + +#import +#include + +// gomobile exports C functions in a static framework. Check the actual public +// header so supported functions get strong references (even with dead stripping), +// while v0.2.1 never references an absent symbol. +template +struct WavelengthArkBindings { + static constexpr bool supported = requires(Bytes *req, NSError *__autoreleasing *error) { + { MobilePromoteVTXO(req, error) } -> std::same_as; + { MobilePayOnActiveChannel(req, error) } -> std::same_as; + { MobileReceiveOnActiveChannel(req, error) } -> std::same_as; + }; + + // Returns false only for names outside this feature. A recognized call on + // incomplete bindings does no work; the bridge rejects it as unsupported. + static bool dispatch(NSString *method, Bytes *req, NSData **result, NSError **error) + { + if ([method isEqualToString:@"promoteVTXO"]) { + if constexpr (supported) *result = MobilePromoteVTXO(req, error); + } else if ([method isEqualToString:@"payOnActiveChannel"]) { + if constexpr (supported) *result = MobilePayOnActiveChannel(req, error); + } else if ([method isEqualToString:@"receiveOnActiveChannel"]) { + if constexpr (supported) *result = MobileReceiveOnActiveChannel(req, error); + } else { + return false; + } + return true; + } +}; diff --git a/packages/react-native/ios/WavelengthModule.mm b/packages/react-native/ios/WavelengthModule.mm index 1d02f2f..e717d27 100644 --- a/packages/react-native/ios/WavelengthModule.mm +++ b/packages/react-native/ios/WavelengthModule.mm @@ -1,4 +1,5 @@ #import "WavelengthModule.h" +#import "WavelengthArkBindings.hpp" #import #import @@ -46,6 +47,12 @@ - (void)passkeySupported:(RCTPromiseResolveBlock)resolve resolve(@([WavelengthPasskey prfSupported])); } +- (void)supportsArkChannels:(RCTPromiseResolveBlock)resolve + reject:(RCTPromiseRejectBlock)reject +{ + resolve(@(WavelengthArkBindings<>::supported)); +} + - (void)passkeyCreate:(NSString *)requestJson resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject @@ -104,7 +111,16 @@ - (void)call:(NSString *)method NSString *json = @""; NSData *params = [paramsJson dataUsingEncoding:NSUTF8StringEncoding]; - if ([method isEqualToString:@"start"]) { + if (WavelengthArkBindings<>::dispatch(method, params, &result, &error)) { + if (!WavelengthArkBindings<>::supported) { + reject(@"unsupported_facade_method", @"Native bindings do not support Ark channels", nil); + return; + } + if (error == nil && result.length == 0) { + reject(kWavelengthErrorCode, [method stringByAppendingString:@" returned no JSON"], nil); + return; + } + } else if ([method isEqualToString:@"start"]) { MobileStart(paramsJson, &error); } else if ([method isEqualToString:@"startExternalSeedWallet"]) { result = MobileStartExternalSeedWallet(params, &error); @@ -171,8 +187,12 @@ - (void)call:(NSString *)method } if (result != nil) { json = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding]; + if (json == nil) { + reject(kWavelengthErrorCode, [method stringByAppendingString:@" returned invalid UTF-8"], nil); + return; + } } - resolve(json ?: @""); + resolve(json); }); } diff --git a/packages/react-native/src/NativeWavelength.ts b/packages/react-native/src/NativeWavelength.ts index 95437c6..5336213 100644 --- a/packages/react-native/src/NativeWavelength.ts +++ b/packages/react-native/src/NativeWavelength.ts @@ -11,6 +11,8 @@ import { TurboModuleRegistry } from 'react-native'; export interface Spec extends TurboModule { /** Invokes a facade verb by name with a JSON payload, returning JSON. */ call(method: string, paramsJson: string): Promise; + /** True only if all three Ark channel calls exist in the linked bindings. */ + supportsArkChannels(): Promise; /** Opens the activity subscription; entries arrive as device events. */ startActivity(reqJson: string): Promise; /** Closes the activity subscription; a no-op when none is open. */ diff --git a/packages/react-native/src/client.test.ts b/packages/react-native/src/client.test.ts index 99a5b55..ff602b2 100644 --- a/packages/react-native/src/client.test.ts +++ b/packages/react-native/src/client.test.ts @@ -142,6 +142,7 @@ describe('NativeWavelengthClient', () => { it('startExternalSeedWallet preserves the final profile config', async () => { const fake = makeFake(); + fake.native.supportsArkChannels = () => Promise.resolve(true); const client = new NativeWavelengthClient(fake.native, fake.subscribe); fake.responses.set('startExternalSeedWallet', JSON.stringify({ Imported: true, @@ -159,6 +160,7 @@ describe('NativeWavelengthClient', () => { network: 'regtest', dataDir: FINAL_PROFILE_DATA_DIR, arkServerAddress: 'h:7070', + arkChannelsEnabled: true, }, { seedEntropy: Uint8Array.from({ length: 16 }, (_, index) => index), @@ -175,6 +177,7 @@ describe('NativeWavelengthClient', () => { data_dir: FINAL_PROFILE_DATA_DIR, network: 'regtest', server_address: 'h:7070', + ark_channels_enabled: true, server_transport: 'grpc', swap_server_transport: 'grpc', wallet_type: 'lwwallet', @@ -197,6 +200,86 @@ describe('NativeWavelengthClient', () => { }); }); + it('forwards channel opt-in, exact verbs and JSON without a fallback', async () => { + const fake = makeFake(); + fake.native.supportsArkChannels = () => Promise.resolve(true); + const client = new NativeWavelengthClient(fake.native, fake.subscribe); + const channelId = 'ab'.repeat(32); + const preimage = '00'.repeat(32); + const paymentHash = '66687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925'; + fake.responses.set('getInfo', '{}'); + fake.responses.set('promoteVTXO', JSON.stringify({ + ChannelID: channelId, Phase: 'Active', CapacitySat: 500, + })); + fake.responses.set('payOnActiveChannel', JSON.stringify({ + ChannelID: channelId, Preimage: preimage, PaymentHash: paymentHash, + PrivateAmountSat: 200, FeeSat: 0, + })); + fake.responses.set('receiveOnActiveChannel', JSON.stringify({ + Invoice: 'ln-in', Entry: { Progress: null, Request: null }, + })); + + await client.start({ network: 'regtest', arkChannelsEnabled: true }); + assert.equal(JSON.parse(fake.calls[0].paramsJson).ark_channels_enabled, true); + assert.deepEqual(await client.promoteVTXO({ amountSat: 500, idempotencyKey: 'p1' }), { + channelId, phase: 'Active', capacitySat: 500, + }); + assert.deepEqual(await client.payOnActiveChannel({ invoice: 'ln-out', maxFeeSat: 0 }), { + channelId, preimage, paymentHash, privateAmountSat: 200, feeSat: 0, + }); + assert.deepEqual(await client.receiveOnActiveChannel({ amountSat: 70, memo: 'inbound' }), { + invoice: 'ln-in', entry: { progress: undefined, request: undefined }, + }); + assert.deepEqual(fake.calls.slice(2).map(({ method, paramsJson }) => + [method, JSON.parse(paramsJson)]), [ + ['promoteVTXO', { AmountSat: 500, IdempotencyKey: 'p1' }], + ['payOnActiveChannel', { Invoice: 'ln-out', MaxFeeSat: 0 }], + ['receiveOnActiveChannel', { AmountSat: 70, Memo: 'inbound' }], + ]); + }); + + for (const binary of ['old RN bridge', 'old gomobile bindings']) { + it(`rejects channel operations before dispatch on ${binary}`, async () => { + const fake = makeFake(); + if (binary === 'old gomobile bindings') { + fake.native.supportsArkChannels = () => Promise.resolve(false); + } + const client = new NativeWavelengthClient(fake.native, fake.subscribe); + const config = { + network: 'regtest' as const, dataDir: FINAL_PROFILE_DATA_DIR, arkChannelsEnabled: true, + }; + const unsupported = { name: 'WavelengthError', code: 'unsupported_facade_method' }; + await assert.rejects(client.start(config), unsupported); + await assert.rejects(client.startExternalSeedWallet(config, { + seedEntropy: new Uint8Array(16), + }), unsupported); + await assert.rejects(client.promoteVTXO({ amountSat: 20, idempotencyKey: 'p' }), unsupported); + await assert.rejects(client.payOnActiveChannel({ invoice: 'inv', maxFeeSat: 1 }), unsupported); + await assert.rejects(client.receiveOnActiveChannel({ amountSat: 1 }), unsupported); + assert.deepEqual(fake.calls, []); + fake.responses.set('getInfo', '{}'); + await client.start({ ...config, arkChannelsEnabled: false }); + assert.deepEqual(fake.calls.map(({ method }) => method), ['start', 'getInfo']); + }); + } + + it('preserves channel errors, including native causes, without retrying the payment', async () => { + for (const [code, message] of [ + ['wavelength_error', 'rpc error: no liquidity'], + ['unsupported_facade_method', 'Native bindings do not support Ark channels'], + ]) { + const fake = makeFake(); + const cause = Object.assign(new Error(message), { code }); + const methods: string[] = []; + fake.native.supportsArkChannels = () => Promise.resolve(true); + fake.native.call = async (method) => { methods.push(method); throw cause; }; + const client = new NativeWavelengthClient(fake.native, fake.subscribe); + await assert.rejects(client.payOnActiveChannel({ invoice: 'inv', maxFeeSat: 1 }), + { name: 'WavelengthError', code, message, cause }); + assert.deepEqual(methods, ['payOnActiveChannel']); + } + }); + it('wraps native rejections in WavelengthError', async () => { const fake = makeFake(); const client = new NativeWavelengthClient(fake.native, fake.subscribe); diff --git a/packages/react-native/src/client.ts b/packages/react-native/src/client.ts index 08c111b..4094683 100644 --- a/packages/react-native/src/client.ts +++ b/packages/react-native/src/client.ts @@ -19,6 +19,8 @@ import type { export type WavelengthNativeModule = { /** Invokes a facade verb by name with a JSON payload, returning JSON. */ call(method: string, paramsJson: string): Promise; + /** Absent on an older app binary after a JS-only update. */ + supportsArkChannels?(): Promise; /** Opens the native activity subscription. */ startActivity(reqJson: string): Promise; /** Closes the native activity subscription. */ @@ -47,6 +49,25 @@ export type SubscribeToNativeEvents = ( listener: (event: NativeActivityEvent) => void, ) => () => void; +// Older gomobile runtimes ignore unknown config fields. Check before either +// lifecycle verb can open a wallet with the requested feature silently off. +function needsArkChannels(method: FacadeMethod, params: unknown): boolean { + switch (method) { + case 'promoteVTXO': + case 'payOnActiveChannel': + case 'receiveOnActiveChannel': + return true; + case 'startExternalSeedWallet': + params = (params as { config: unknown }).config; + break; + case 'start': + break; + default: + return false; + } + return (params as { ark_channels_enabled?: boolean }).ark_channels_enabled === true; +} + /** * The React Native transport: implements {@link BaseWavelengthClient}'s pipe * over the gomobile Turbo Module. JSON strings cross the RN bridge, then the @@ -103,6 +124,12 @@ export class NativeWavelengthClient extends BaseWavelengthClient { params: unknown = {}, ): Promise { try { + if (needsArkChannels(method, params) && !(await this.native.supportsArkChannels?.())) { + throw new WavelengthError( + 'Native bindings do not support Ark channels', + 'unsupported_facade_method', + ); + } const resultJson = await this.native.call( method, JSON.stringify(params ?? {}), @@ -110,9 +137,14 @@ export class NativeWavelengthClient extends BaseWavelengthClient { return (resultJson ? JSON.parse(resultJson) : null) as T; } catch (err) { - throw new WavelengthError(errorMessage(err), 'wavelength_error', { - cause: err, - }); + if (err instanceof WavelengthError) throw err; + const unsupported = err !== null && typeof err === 'object' && + 'code' in err && err.code === 'unsupported_facade_method'; + throw new WavelengthError( + errorMessage(err), + unsupported ? 'unsupported_facade_method' : 'wavelength_error', + { cause: err }, + ); } } diff --git a/packages/react-native/src/index.ts b/packages/react-native/src/index.ts index 3fb07fc..ad2fa8a 100644 --- a/packages/react-native/src/index.ts +++ b/packages/react-native/src/index.ts @@ -2,6 +2,7 @@ import { NativeEventEmitter, NativeModules } from 'react-native'; import { createWalletEngine, type ExternalSeedWalletClient, + type ArkChannelClient, type PasskeyCeremony, type DistributiveOmit, type WalletEngine, @@ -20,7 +21,7 @@ import { * no options today; an options parameter can be added later without a breaking * change. */ -export function createNativeClient(): ExternalSeedWalletClient { +export function createNativeClient(): ExternalSeedWalletClient & ArkChannelClient { // NativeModules.Wavelength is the interop view of the Turbo Module; the // emitter needs it (or any module carrying addListener/removeListeners) to // route 'wavelengthActivity' device events on both platforms. diff --git a/packages/react-native/src/native-dispatch.test.ts b/packages/react-native/src/native-dispatch.test.ts index c2fd404..bf86603 100644 --- a/packages/react-native/src/native-dispatch.test.ts +++ b/packages/react-native/src/native-dispatch.test.ts @@ -8,6 +8,7 @@ const android = new URL( import.meta.url, ); const ios = new URL('../ios/WavelengthModule.mm', import.meta.url); +const iosArk = new URL('../ios/WavelengthArkBindings.hpp', import.meta.url); const nativeMethods = { start: ['Mobile.start', 'MobileStart'], @@ -27,6 +28,9 @@ const nativeMethods = { ], deposit: ['Mobile.deposit', 'MobileDeposit'], receive: ['Mobile.receive', 'MobileReceive'], + promoteVTXO: ['promoteVTXO', 'MobilePromoteVTXO'], + payOnActiveChannel: ['payOnActiveChannel', 'MobilePayOnActiveChannel'], + receiveOnActiveChannel: ['receiveOnActiveChannel', 'MobileReceiveOnActiveChannel'], prepareSend: ['Mobile.prepareSend', 'MobilePrepareSend'], sendPrepared: ['Mobile.sendPrepared', 'MobileSendPrepared'], list: ['Mobile.list', 'MobileList'], @@ -63,10 +67,15 @@ async function readNativeSources(): Promise<{ kt: string; mm: string }> { } function androidDispatch(source: string): Record { - return Object.fromEntries( + const direct = Object.fromEntries( [...source.matchAll(/^\s*"([^"]+)"\s*->\s*(?:\{\s*)?(Mobile\.\w+)\(/gm)] .map((match) => [match[1], match[2]]), ); + const optional = source.match(/^\s*("[^"\n]+"(?:, "[^"\n]+")*) ->\s*arkChannels\.call\(method, params\)/m); + for (const [, name] of optional?.[1].matchAll(/"([^"]+)"/g) ?? []) { + direct[name] = name; + } + return direct; } function iosDispatch(source: string): Record { @@ -97,7 +106,10 @@ describe('native facade dispatch', () => { ); assert.deepEqual(androidDispatch(kt), expectedAndroid); - assert.deepEqual(iosDispatch(mm), expectedIos); + assert.match(mm, /WavelengthArkBindings<>::dispatch\(method, params, &result, &error\)/); + assert.deepEqual({ + ...iosDispatch(mm), ...iosDispatch(await readFile(iosArk, 'utf8')), + }, expectedIos); }); it('forwards external-seed starts as byte request and result values', async () => { diff --git a/packages/react-native/test-native/ArkChannelBindingsCheck.kt b/packages/react-native/test-native/ArkChannelBindingsCheck.kt new file mode 100644 index 0000000..184053a --- /dev/null +++ b/packages/react-native/test-native/ArkChannelBindingsCheck.kt @@ -0,0 +1,36 @@ +package engineering.lightning.wavelength.reactnative + +import engineering.lightning.wavewalletdk.mobile.Mobile + +object Paired { + val rejected = Exception("rpc error: no liquidity") + @JvmStatic fun promoteVTXO(req: ByteArray) = req + @JvmStatic fun payOnActiveChannel(req: ByteArray): ByteArray = + if (req.isEmpty()) throw rejected else "pay:".encodeToByteArray() + req + @JvmStatic fun receiveOnActiveChannel(req: ByteArray) = "receive:".encodeToByteArray() + req +} + +object WrongABI { + @JvmStatic fun promoteVTXO(req: ByteArray) = req + @JvmStatic fun payOnActiveChannel(req: ByteArray) = req + @JvmStatic fun receiveOnActiveChannel(req: ByteArray) = req.size +} + +fun main() { + // The released class can be inspected without initializing the Android JNI. + for (facade in listOf(Mobile::class.java, WrongABI::class.java)) { + val old = ArkChannelBindings(facade) + check(!old.supported) + check(runCatching { old.call("promoteVTXO", byteArrayOf()) }.exceptionOrNull() is MissingArkChannels) + } + val paired = ArkChannelBindings(Paired::class.java) + check(paired.supported) + val json = "{\"memo\":\"caf\u00e9\"}" + val req = json.encodeToByteArray() + check(paired.call("promoteVTXO", req) == json) + check(paired.call("payOnActiveChannel", req) == "pay:$json") + check(paired.call("receiveOnActiveChannel", req) == "receive:$json") + check(runCatching { paired.call("payOnActiveChannel", byteArrayOf()) }.exceptionOrNull() === Paired.rejected) + check(runCatching { paired.call("promoteVTXO", byteArrayOf()) }.isFailure) + check(runCatching { paired.call("promoteVTXO", byteArrayOf(0xff.toByte())) }.isFailure) +} diff --git a/packages/react-native/test-native/ark-bindings.mm b/packages/react-native/test-native/ark-bindings.mm new file mode 100644 index 0000000..2eed13c --- /dev/null +++ b/packages/react-native/test-native/ark-bindings.mm @@ -0,0 +1,45 @@ +#import +#include + +// Mode 0 uses the actual released header. Modes 1 and 2 add the public +// gomobile signatures for partial and complete builds, respectively. +#if ARK_ABI >= 1 +static NSData *MobilePromoteVTXO(NSData *req, NSError **) { return req; } +#endif +#if ARK_ABI == 2 +static NSData *MobilePayOnActiveChannel(NSData *, NSError **error) +{ + *error = [NSError errorWithDomain:@"daemon" code:7 userInfo:nil]; + return nil; +} +static NSData *MobileReceiveOnActiveChannel(NSData *, NSError **) { return [NSData data]; } +#endif + +#include "../ios/WavelengthArkBindings.hpp" + +int main() +{ + @autoreleasepool { +#ifdef LINK_RELEASED_RUNTIME + // Force the static archive into the device/simulator link. + (void)MobileIsRunning(); +#endif + using Bindings = WavelengthArkBindings<>; + static_assert(Bindings::supported == (ARK_ABI == 2)); + NSData *req = [@"{\"memo\":\"caf\u00e9\"}" dataUsingEncoding:NSUTF8StringEncoding]; + NSError *error = nil; + NSData *result = nil; + assert(!Bindings::dispatch(@"receive", req, &result, &error)); + assert(Bindings::dispatch(@"promoteVTXO", req, &result, &error)); + assert(error == nil && result == (Bindings::supported ? req : nil)); + assert(Bindings::dispatch(@"receiveOnActiveChannel", req, &result, &error)); + assert(error == nil && (result != nil) == Bindings::supported && result.length == 0); + assert(Bindings::dispatch(@"payOnActiveChannel", req, &result, &error)); + assert(result == nil); + if (Bindings::supported) { + assert([error.domain isEqualToString:@"daemon"] && error.code == 7); + } else { + assert(error == nil); + } + } +} diff --git a/packages/react-native/test-native/check-ark-bindings.sh b/packages/react-native/test-native/check-ark-bindings.sh new file mode 100644 index 0000000..b92ef41 --- /dev/null +++ b/packages/react-native/test-native/check-ark-bindings.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Run against the released v0.2.1 AAR or XCFramework; fixtures exercise +# channel-capable bindings without a daemon, emulator, or wallet. +set -eu +cd "$(dirname "$0")/.." +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +case "${1:-}" in + android) + unzip -p "${2:-android/libs/Wavewalletdk.aar}" classes.jar > "$tmp/classes.jar" + kotlinc android/src/main/java/engineering/lightning/wavelength/reactnative/ArkChannelBindings.kt \ + test-native/ArkChannelBindingsCheck.kt -cp "$tmp/classes.jar" -include-runtime -d "$tmp/check.jar" + java -cp "$tmp/check.jar:$tmp/classes.jar" engineering.lightning.wavelength.reactnative.ArkChannelBindingsCheckKt + ;; + ios) + framework="${2:-ios/Wavewalletdk.xcframework}" + flags=(-std=c++20 -fobjc-arc -fmodules -fcxx-modules "-fmodules-cache-path=$tmp/modules") + for abi in 0 1 2; do + xcrun --sdk macosx clang++ "${flags[@]}" -DARK_ABI=$abi -F"$framework/ios-arm64" \ + test-native/ark-bindings.mm -framework Foundation -o "$tmp/check" + "$tmp/check" + done + for spec in 'iphoneos arm64-apple-ios15.1 ios-arm64' \ + 'iphonesimulator arm64-apple-ios15.1-simulator ios-arm64_x86_64-simulator'; do + read -r sdk target slice <<< "$spec" + xcrun --sdk "$sdk" clang++ "${flags[@]}" -target "$target" -DARK_ABI=0 -DLINK_RELEASED_RUNTIME \ + -F"$framework/$slice" test-native/ark-bindings.mm -framework Foundation \ + -framework Wavewalletdk -framework Security -lresolv -o "$tmp/ios-check" + done + ;; + *) echo "usage: $0 android|ios [released artifact path]" >&2; exit 2 ;; +esac diff --git a/packages/web/README.md b/packages/web/README.md index 3e9dac8..7f244d8 100644 --- a/packages/web/README.md +++ b/packages/web/README.md @@ -44,6 +44,26 @@ await client.ready(); await client.start(defaultConfig("signet")); ``` +## Explicit Ark channels + +With a channel-capable Wavelength runtime and SwapDK hub, a funded, unlocked +`lwwallet` can promote wallet VTXOs and pay over the resulting channel. Enable +channels at startup with `{ ...config, arkChannelsEnabled: true }`. The same +three client methods are available in the React Native SDK. + +```ts +// Persist one key per promotion. Reuse it if the reply is lost. +const channel = await client.promoteVTXO({ amountSat: 100_000, idempotencyKey }); +await client.payOnActiveChannel({ invoice, maxFeeSat: 10 }); +const incoming = await client.receiveOnActiveChannel({ amountSat: 5_000 }); +``` + +The receive call requests an invoice against existing inbound liquidity. It +does not open another channel or fall back to a swap. Use `client.receive()` +for the separate vHTLC flow. Use WASM assets or a native library built from +the matching channel branch; the previously released binaries do not expose +these operations. Do not log the payment preimage returned by a successful pay. + ## Performance diagnostics `onPerformance` opts a client or engine into structured timing samples. The diff --git a/packages/web/src/debug-redaction.test.ts b/packages/web/src/debug-redaction.test.ts index 6f8967b..f65d2ce 100644 --- a/packages/web/src/debug-redaction.test.ts +++ b/packages/web/src/debug-redaction.test.ts @@ -12,6 +12,8 @@ const ENCIPHERED_SEED = 'AGVuY2lwaGVyZWQgc2VlZA=='; const PRF_OUTPUT = 'ab'.repeat(32); const SEED_ENTROPY = 'AAECAwQFBgcICQoLDA0ODw=='; +const PREIMAGE = 'de'.repeat(32); + type Case = { method: string; params: unknown; @@ -55,6 +57,13 @@ const CASES: Case[] = [ RecoveredVTXOs: 2, }, }, + { + method: 'payOnActiveChannel', + params: { Invoice: 'invoice', MaxFeeSat: 2 }, + result: { Preimage: PREIMAGE, payment: { preimage: PREIMAGE, FeeSat: 1 } }, + redactedParams: { Invoice: 'invoice', MaxFeeSat: 2 }, + redactedResult: { Preimage: R, payment: { preimage: R, FeeSat: 1 } }, + }, { method: 'unlockWallet', params: { WalletPassword: PASSWORD_B64 }, @@ -101,6 +110,7 @@ const SECRETS = [ ENCIPHERED_SEED, PRF_OUTPUT, SEED_ENTROPY, + PREIMAGE, ...MNEMONIC, ]; diff --git a/packages/web/src/index.ts b/packages/web/src/index.ts index b6cbc74..23a5e2c 100644 --- a/packages/web/src/index.ts +++ b/packages/web/src/index.ts @@ -2,6 +2,7 @@ import { createWalletEngine, type DistributiveOmit, type ExternalSeedWalletClient, + type ArkChannelClient, type PasskeyCeremony, type WavelengthPerformanceListener, type WalletEngine, @@ -104,7 +105,7 @@ export type WebClientOptions = { */ export function createWebClient( options: WebClientOptions = {}, -): ExternalSeedWalletClient { +): ExternalSeedWalletClient & ArkChannelClient { return options.runtimeThread === 'main' ? new MainThreadWavelengthClient(options) : new WorkerWavelengthClient(options); diff --git a/packages/web/src/util.ts b/packages/web/src/util.ts index e1caa4b..506193b 100644 --- a/packages/web/src/util.ts +++ b/packages/web/src/util.ts @@ -39,6 +39,7 @@ export function debugTs(): string { // shapes all match. wavewalletdk-worker.js cannot import this module and // carries an identical copy; keep the two in sync. const SECRET_FIELDS: ReadonlySet = new Set([ + 'preimage', 'walletpassword', 'seedpassphrase', 'mnemonic', diff --git a/packages/web/src/wavewalletdk-worker.js b/packages/web/src/wavewalletdk-worker.js index 97e8494..43abaef 100644 --- a/packages/web/src/wavewalletdk-worker.js +++ b/packages/web/src/wavewalletdk-worker.js @@ -38,6 +38,7 @@ function debugTs() { // Mirrors SECRET_FIELDS and facadeDebugPayload in packages/web/src/util.ts, // hand-copied because this worker cannot import it; keep the two identical. const SECRET_FIELDS = new Set([ + "preimage", "walletpassword", "seedpassphrase", "mnemonic",