diff --git a/db/oor_session_registry_store.go b/db/oor_session_registry_store.go index dcdf601cf..bcef7821c 100644 --- a/db/oor_session_registry_store.go +++ b/db/oor_session_registry_store.go @@ -311,6 +311,49 @@ func (s *OORSessionRegistryStoreDB) GetSession(ctx context.Context, return record, nil } +// GetUnfailedSessionByIdempotencyKey loads a durable outgoing identity before +// an immutable dispatch attempt exists. Failed rows deliberately release the +// key; pending and completed rows retain it. +func (s *OORSessionRegistryStoreDB) GetUnfailedSessionByIdempotencyKey( + ctx context.Context, key string) (*OORSessionRegistryRecord, error) { + + if key == "" { + return nil, ErrOORSessionNotFound + } + + var record *OORSessionRegistryRecord + readFn := func(q *sqlc.Queries) error { + row, err := q.GetUnfailedOORSessionRegistryByIdempotencyKey( + ctx, sql.NullString{ + String: key, + Valid: true, + }, + ) + if err != nil { + return err + } + + converted, err := oorSessionRecordFromRow(row) + if err != nil { + return err + } + + record = &converted + + return nil + } + + err := s.ExecTx(ctx, ReadTxOption(), readFn) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrOORSessionNotFound + } + if err != nil { + return nil, err + } + + return record, nil +} + // GetDispatchAttemptByIdempotencyKey loads the immutable outgoing dispatch // bound to key. Unlike the mutable session lookup, it remains valid across // terminal and incoming lifecycle updates. diff --git a/db/oor_session_registry_store_test.go b/db/oor_session_registry_store_test.go index 03f0a11cf..50ea1577b 100644 --- a/db/oor_session_registry_store_test.go +++ b/db/oor_session_registry_store_test.go @@ -97,6 +97,51 @@ func TestOORSessionRegistryGetNotFound(t *testing.T) { require.ErrorIs(t, err, ErrOORSessionNotFound) } +// TestOORSessionRegistryLookupPreparedIdentity verifies that the caller key is +// queryable before the first dispatch attempt is persisted. This is the +// durable identity boundary for prepare-only OOR sessions across restarts. +func TestOORSessionRegistryLookupPreparedIdentity(t *testing.T) { + t.Parallel() + + ctx := t.Context() + store := newOORSessionRegistryStoreForTest(t) + sid := sessionHash(0x03) + record := OORSessionRegistryRecord{ + SessionID: sid, + ActorID: "actor-" + sid.String(), + Direction: OORSessionDirectionOutgoing, + Phase: "prepared", + IdempotencyKey: "prepared-key", + Status: OORSessionStatusPending, + SnapshotData: []byte{ + 0x01, + }, + SnapshotVersion: 1, + } + require.NoError(t, store.UpsertSession(ctx, record)) + + got, err := store.GetUnfailedSessionByIdempotencyKey( + ctx, record.IdempotencyKey, + ) + require.NoError(t, err) + require.Equal(t, sid, got.SessionID) + require.Equal(t, "prepared", got.Phase) + + _, err = store.GetDispatchAttemptByIdempotencyKey( + ctx, record.IdempotencyKey, + ) + require.ErrorIs(t, err, ErrOORDispatchAttemptNotFound) + + record.Status = OORSessionStatusFailed + record.Phase = "failed" + require.NoError(t, store.UpsertSession(ctx, record)) + + _, err = store.GetUnfailedSessionByIdempotencyKey( + ctx, record.IdempotencyKey, + ) + require.ErrorIs(t, err, ErrOORSessionNotFound) +} + // TestOORSessionRegistryUpsertUpdates verifies a second upsert advances the // mutable fields while preserving the original created_at. func TestOORSessionRegistryUpsertUpdates(t *testing.T) { diff --git a/db/oor_unroll_resolver.go b/db/oor_unroll_resolver.go index b2884fe39..c489fc93f 100644 --- a/db/oor_unroll_resolver.go +++ b/db/oor_unroll_resolver.go @@ -56,15 +56,72 @@ type unrollPackageNode struct { func (s *OORArtifactPersistenceStore) ResolveUnrollPackages(ctx context.Context, outpoint wire.OutPoint) (*OORUnrollPackages, error) { + return s.resolveUnrollPackages( + ctx, outpoint, + func(ctx context.Context, q OORArtifactStore) ( + *OORPackageBundle, error) { + + return loadPackageBundleByOutpoint(ctx, q, outpoint) + }, + ) +} + +// ResolveUnrollPackagesBySessionID resolves a package chain before the local +// endpoint has installed an outpoint binding. OOR senders use this while +// promoting a recipient output into shared channel recovery state. +func (s *OORArtifactPersistenceStore) ResolveUnrollPackagesBySessionID( + ctx context.Context, outpoint wire.OutPoint, sessionID chainhash.Hash) ( + *OORUnrollPackages, error) { + + if sessionID != outpoint.Hash { + return nil, fmt.Errorf("target outpoint %s does not match OOR "+ + "session %s", outpoint, sessionID) + } + + return s.resolveUnrollPackages( + ctx, outpoint, + func(ctx context.Context, q OORArtifactStore) ( + *OORPackageBundle, error) { + + pkg, err := loadPackageBundleBySessionID( + ctx, q, sessionID, + ) + if err != nil { + return nil, err + } + if !packageProducesAncestorOutput( + pkg, outpoint.Hash, outpoint.Index, + ) { + return nil, fmt.Errorf("OOR session %s does "+ + "not create target outpoint %s", + sessionID, outpoint) + } + + return pkg, nil + }, + ) +} + +// resolveUnrollPackages traverses one package chain from a caller-selected +// target loader. The target outpoint remains part of the result even when the +// first package is known only by session ID. +func (s *OORArtifactPersistenceStore) resolveUnrollPackages(ctx context.Context, + outpoint wire.OutPoint, + loadTarget func(context.Context, OORArtifactStore) (*OORPackageBundle, + error)) (*OORUnrollPackages, error) { + if s == nil || s.db == nil { return nil, fmt.Errorf("store must be provided") } + if loadTarget == nil { + return nil, fmt.Errorf("target package loader must be provided") + } readTx := ReadTxOption() var result *OORUnrollPackages err := s.db.ExecTx(ctx, readTx, func(q OORArtifactStore) error { - targetPkg, err := loadPackageBundleByOutpoint(ctx, q, outpoint) + targetPkg, err := loadTarget(ctx, q) if err != nil { return err } diff --git a/db/oor_unroll_resolver_test.go b/db/oor_unroll_resolver_test.go index 2ff5345c4..178109f5b 100644 --- a/db/oor_unroll_resolver_test.go +++ b/db/oor_unroll_resolver_test.go @@ -33,6 +33,43 @@ func TestResolveUnrollPackagesUnknownOutpoint(t *testing.T) { require.True(t, errors.Is(err, sql.ErrNoRows)) } +// TestResolveUnrollPackagesBySessionID verifies an OOR sender can resolve the +// recipient output before shared channel recovery state creates a local VTXO +// row and output binding. +func TestResolveUnrollPackagesBySessionID(t *testing.T) { + t.Parallel() + + ctx := t.Context() + store, _ := newOORArtifactStoreForTest(t) + sessionID, arkPSBT, checkpoints, outpoint, _, _, unresolvedInput := + buildTestOORPackage(t, 0x31) + + err := store.UpsertPackage( + ctx, OORPackageDirectionOutgoing, sessionID, arkPSBT, + checkpoints, + ) + require.NoError(t, err) + + resolved, err := store.ResolveUnrollPackagesBySessionID( + ctx, outpoint, sessionID, + ) + require.NoError(t, err) + require.Equal(t, outpoint, resolved.TargetOutpoint) + require.Len(t, resolved.Packages, 1) + require.Equal(t, sessionID, resolved.Packages[0].SessionID) + require.Equal( + t, []wire.OutPoint{unresolvedInput}, + resolved.UnresolvedCheckpointInputs, + ) + + wrongSession := sessionID + wrongSession[0] ^= 1 + _, err = store.ResolveUnrollPackagesBySessionID( + ctx, outpoint, wrongSession, + ) + require.ErrorContains(t, err, "does not match OOR session") +} + // TestResolveUnrollPackagesWithKnownAncestor verifies that resolver traversal // returns a deterministic ancestor-first package chain and surfaces unresolved // outermost checkpoint inputs. diff --git a/db/round_store.go b/db/round_store.go index 9188a381a..ea1a151a2 100644 --- a/db/round_store.go +++ b/db/round_store.go @@ -197,6 +197,9 @@ type RoundStore interface { ctx context.Context, arg sqlc.UpdateVTXOStatusParams, ) error + SetRecoveryOnlyVTXORelativeExpiry(ctx context.Context, + arg sqlc.SetRecoveryOnlyVTXORelativeExpiryParams) (int64, error) + // DeleteSpendingReservation removes a spending-reservation row so the // VTXO store can atomically update a VTXO's status and drop its // reservation in the same transaction when it leaves SpendingState. diff --git a/db/sqlc/migrations/000004_vtxos.up.sql b/db/sqlc/migrations/000004_vtxos.up.sql index c413691a9..1fcc96f2d 100644 --- a/db/sqlc/migrations/000004_vtxos.up.sql +++ b/db/sqlc/migrations/000004_vtxos.up.sql @@ -76,6 +76,8 @@ CREATE TABLE IF NOT EXISTS vtxos ( -- 5 = UnilateralExit -- 6 = Failed -- 7 = Spending + -- 8 = Expired + -- 9 = RecoveryOnly status INTEGER NOT NULL DEFAULT 0, -- forfeit_round_id is the round in which this VTXO is being forfeited. diff --git a/db/sqlc/oor_session_registry.sql.go b/db/sqlc/oor_session_registry.sql.go index 840d4e453..9abf4873b 100644 --- a/db/sqlc/oor_session_registry.sql.go +++ b/db/sqlc/oor_session_registry.sql.go @@ -69,6 +69,33 @@ func (q *Queries) GetOORSessionRegistry(ctx context.Context, sessionID []byte) ( return i, err } +const GetUnfailedOORSessionRegistryByIdempotencyKey = `-- name: GetUnfailedOORSessionRegistryByIdempotencyKey :one +SELECT session_id, actor_id, direction, phase, idempotency_key, status, last_error, snapshot_data, snapshot_version, flow_version, created_at, updated_at FROM oor_session_registry +WHERE idempotency_key = $1 AND status != 2 +ORDER BY created_at ASC +LIMIT 1 +` + +func (q *Queries) GetUnfailedOORSessionRegistryByIdempotencyKey(ctx context.Context, idempotencyKey sql.NullString) (OorSessionRegistry, error) { + row := q.db.QueryRowContext(ctx, GetUnfailedOORSessionRegistryByIdempotencyKey, idempotencyKey) + var i OorSessionRegistry + err := row.Scan( + &i.SessionID, + &i.ActorID, + &i.Direction, + &i.Phase, + &i.IdempotencyKey, + &i.Status, + &i.LastError, + &i.SnapshotData, + &i.SnapshotVersion, + &i.FlowVersion, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + const InsertOORDispatchAttempt = `-- name: InsertOORDispatchAttempt :exec INSERT INTO oor_dispatch_attempts ( idempotency_key, session_id, request_data, created_at diff --git a/db/sqlc/querier.go b/db/sqlc/querier.go index 673559dcc..35bb3f0b7 100644 --- a/db/sqlc/querier.go +++ b/db/sqlc/querier.go @@ -174,6 +174,7 @@ type Querier interface { // Returns cumulative Ark protocol fees paid to the operator (fees_paid // account only). Does not include L1 chain/miner fees (onchain_fees). GetTotalOperatorFeesPaid(ctx context.Context) (int64, error) + GetUnfailedOORSessionRegistryByIdempotencyKey(ctx context.Context, idempotencyKey sql.NullString) (OorSessionRegistry, error) GetUnilateralExitJob(ctx context.Context, arg GetUnilateralExitJobParams) (UnilateralExitJob, error) GetVHTLCRecoveryJob(ctx context.Context, id string) (VhtlcRecoveryJob, error) GetVHTLCRecoveryJobByRequestID(ctx context.Context, requestID string) (VhtlcRecoveryJob, error) @@ -595,6 +596,9 @@ type Querier interface { // SetAssetDepositError records the latest failure of a deposit that has not // confirmed. SetAssetDepositError(ctx context.Context, arg SetAssetDepositErrorParams) error + // Selects the exact final-spend delay for an application-owned recovery row. + // Ordinary wallet VTXOs can never be modified through this query. + SetRecoveryOnlyVTXORelativeExpiry(ctx context.Context, arg SetRecoveryOnlyVTXORelativeExpiryParams) (int64, error) SumBoardingIntentAmountsByStatus(ctx context.Context, status string) (interface{}, error) // SumLedgerWalletLegs totals the ledger legs that move value in and out of // wallet_balance, split by event type and by whether wallet_balance is the diff --git a/db/sqlc/queries/oor_session_registry.sql b/db/sqlc/queries/oor_session_registry.sql index 5eba76aeb..a1cf070ef 100644 --- a/db/sqlc/queries/oor_session_registry.sql +++ b/db/sqlc/queries/oor_session_registry.sql @@ -25,6 +25,13 @@ SELECT * FROM oor_session_registry WHERE session_id = $1 ; +-- name: GetUnfailedOORSessionRegistryByIdempotencyKey :one +SELECT * FROM oor_session_registry +WHERE idempotency_key = $1 AND status != 2 +ORDER BY created_at ASC +LIMIT 1 +; + -- name: ListNonTerminalOORSessionRegistry :many -- Status 1 = Completed, 2 = Failed (anchored to Go iota in -- db/oor_session_registry_store.go OORSessionStatus). diff --git a/db/sqlc/queries/vtxo.sql b/db/sqlc/queries/vtxo.sql index c1911b4bc..4ea5b7459 100644 --- a/db/sqlc/queries/vtxo.sql +++ b/db/sqlc/queries/vtxo.sql @@ -110,6 +110,14 @@ WHERE outpoint_hash = $1 AND outpoint_index = $2 AND batch_expiry = $4 AND (created_height = $5 OR created_height = $3); +-- name: SetRecoveryOnlyVTXORelativeExpiry :execrows +-- Selects the exact final-spend delay for an application-owned recovery row. +-- Ordinary wallet VTXOs can never be modified through this query. +UPDATE vtxos +SET expiry = $3, + last_update_time = $4 +WHERE outpoint_hash = $1 AND outpoint_index = $2 AND status = 9; + -- name: MarkVTXOForfeiting :exec -- MarkVTXOForfeiting transitions a VTXO to Forfeiting status and persists -- the forfeit round ID and transaction for crash recovery. Called when diff --git a/db/sqlc/schemas/generated_schema.sql b/db/sqlc/schemas/generated_schema.sql index 0e1e9a7ec..6719b5a81 100644 --- a/db/sqlc/schemas/generated_schema.sql +++ b/db/sqlc/schemas/generated_schema.sql @@ -1950,6 +1950,8 @@ CREATE TABLE vtxos ( -- 5 = UnilateralExit -- 6 = Failed -- 7 = Spending + -- 8 = Expired + -- 9 = RecoveryOnly status INTEGER NOT NULL DEFAULT 0, -- forfeit_round_id is the round in which this VTXO is being forfeited. diff --git a/db/sqlc/vtxo.sql.go b/db/sqlc/vtxo.sql.go index f397a0df8..be510c728 100644 --- a/db/sqlc/vtxo.sql.go +++ b/db/sqlc/vtxo.sql.go @@ -561,6 +561,35 @@ func (q *Queries) RepairVTXOCreatedHeight(ctx context.Context, arg RepairVTXOCre return result.RowsAffected() } +const SetRecoveryOnlyVTXORelativeExpiry = `-- name: SetRecoveryOnlyVTXORelativeExpiry :execrows +UPDATE vtxos +SET expiry = $3, + last_update_time = $4 +WHERE outpoint_hash = $1 AND outpoint_index = $2 AND status = 9 +` + +type SetRecoveryOnlyVTXORelativeExpiryParams struct { + OutpointHash []byte + OutpointIndex int32 + Expiry int32 + LastUpdateTime int64 +} + +// Selects the exact final-spend delay for an application-owned recovery row. +// Ordinary wallet VTXOs can never be modified through this query. +func (q *Queries) SetRecoveryOnlyVTXORelativeExpiry(ctx context.Context, arg SetRecoveryOnlyVTXORelativeExpiryParams) (int64, error) { + result, err := q.db.ExecContext(ctx, SetRecoveryOnlyVTXORelativeExpiry, + arg.OutpointHash, + arg.OutpointIndex, + arg.Expiry, + arg.LastUpdateTime, + ) + if err != nil { + return 0, err + } + return result.RowsAffected() +} + const SumVTXOAmountsByStatus = `-- name: SumVTXOAmountsByStatus :many SELECT status, CAST(COUNT(*) AS BIGINT) AS vtxo_count, diff --git a/db/vtxo_store.go b/db/vtxo_store.go index 4b000e32e..b1f70bc71 100644 --- a/db/vtxo_store.go +++ b/db/vtxo_store.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "log/slog" + "math" "slices" "github.com/btcsuite/btcd/btcec/v2" @@ -121,6 +122,125 @@ func (s *VTXOPersistenceStore) SaveVTXO( }) } +// SaveRecoveryOnlyVTXO atomically persists an application-owned descriptor in +// the recovery-only state. Unlike SaveVTXO, this method never exposes the row +// as live between insertion and the status transition, so concurrent wallet +// selection cannot mistake a channel or contract output for wallet liquidity. +// Replays are accepted only when the existing immutable descriptor matches. +func (s *VTXOPersistenceStore) SaveRecoveryOnlyVTXO(ctx context.Context, + desc *vtxo.Descriptor) error { + + if desc == nil { + return fmt.Errorf("descriptor must be provided") + } + if desc.Status != vtxo.VTXOStatusRecoveryOnly { + return fmt.Errorf("recovery-only descriptor has status %s", + desc.Status) + } + + return s.db.ExecTx(ctx, WriteTxOption(), func(q RoundStore) error { + key := sqlc.GetVTXOParams{ + OutpointHash: desc.Outpoint.Hash[:], + OutpointIndex: int32(desc.Outpoint.Index), + } + existing, err := q.GetVTXO(ctx, key) + switch { + case err == nil: + if err := validateRecoveryOnlyVTXORow( + existing, desc, + ); err != nil { + return err + } + + return upsertAncestryPaths( + ctx, q, desc.Outpoint.Hash[:], + int32(desc.Outpoint.Index), desc.Ancestry, + ) + + case !errors.Is(err, sql.ErrNoRows): + return fmt.Errorf("load recovery-only VTXO: %w", err) + } + + if err := s.ensureRoundExists(ctx, q, desc); err != nil { + return fmt.Errorf("ensure round: %w", err) + } + params, err := s.descriptorToInsertParams(ctx, q, desc) + if err != nil { + return fmt.Errorf("convert descriptor: %w", err) + } + if err := q.InsertVTXO(ctx, params); err != nil { + return fmt.Errorf("insert recovery-only VTXO: %w", err) + } + if err := q.UpdateVTXOStatus(ctx, sqlc.UpdateVTXOStatusParams{ + OutpointHash: desc.Outpoint.Hash[:], + OutpointIndex: int32(desc.Outpoint.Index), + Status: int32(desc.Status), + LastUpdateTime: s.clock.Now().Unix(), + }); err != nil { + return fmt.Errorf("mark VTXO recovery-only: %w", err) + } + + return upsertAncestryPaths( + ctx, q, desc.Outpoint.Hash[:], + int32(desc.Outpoint.Index), desc.Ancestry, + ) + }) +} + +// SetRecoveryOnlyVTXORelativeExpiry selects the delay used by the exact Ark +// channel final-spend policy without making the descriptor wallet-owned. +func (s *VTXOPersistenceStore) SetRecoveryOnlyVTXORelativeExpiry( + ctx context.Context, outpoint wire.OutPoint, delay uint32) error { + + if delay > math.MaxInt32 { + return fmt.Errorf("recovery-only VTXO delay %d exceeds "+ + "storage range", delay) + } + + return s.db.ExecTx(ctx, WriteTxOption(), func(q RoundStore) error { + rows, err := q.SetRecoveryOnlyVTXORelativeExpiry( + ctx, sqlc.SetRecoveryOnlyVTXORelativeExpiryParams{ + OutpointHash: outpoint.Hash[:], + OutpointIndex: int32(outpoint.Index), + Expiry: int32(delay), + LastUpdateTime: s.clock.Now().Unix(), + }, + ) + if err != nil { + return err + } + if rows != 1 { + return fmt.Errorf("recovery-only VTXO %s not found", + outpoint) + } + + return nil + }) +} + +// validateRecoveryOnlyVTXORow rejects an outpoint collision or a replay after +// another subsystem has taken ownership of the same VTXO. Relative expiry is +// excluded because channel recovery selects it after registration. +func validateRecoveryOnlyVTXORow(row VTXORow, desc *vtxo.Descriptor) error { + status := vtxo.VTXOStatus(row.Status) + if status != vtxo.VTXOStatusRecoveryOnly && + status != vtxo.VTXOStatusSpent { + return fmt.Errorf("recovery-only VTXO already has status %s", + status) + } + if row.RoundID != desc.RoundID || row.Amount != int64(desc.Amount) || + !bytes.Equal(row.PkScript, desc.PkScript) || + !bytes.Equal(row.PolicyTemplate, desc.PolicyTemplate) || + row.BatchExpiry != desc.BatchExpiry || + row.ChainDepth != int32(desc.ChainDepth) || + row.CreatedHeight != desc.CreatedHeight || + !bytes.Equal(row.CommitmentTxid, desc.CommitmentTxID[:]) { + return fmt.Errorf("recovery-only VTXO descriptor mismatch") + } + + return nil +} + // ensureRoundExists inserts a minimal confirmed round row when a VTXO refers // to a remote round that this client has not otherwise persisted locally. // If the round already exists (e.g. from the normal round flow), the existing diff --git a/db/vtxo_store_test.go b/db/vtxo_store_test.go index fcb8a3c9b..d680990d6 100644 --- a/db/vtxo_store_test.go +++ b/db/vtxo_store_test.go @@ -2673,3 +2673,98 @@ func TestVTXOPersistenceStoreListVTXOsByStatusesLight(t *testing.T) { outpoints(live), ) } + +// TestVTXOStoreRecoveryOnlyExcludedFromWalletSets verifies that a descriptor +// prepared for channel materialization remains available to the unroller but +// cannot become wallet liquidity or spawn an ordinary VTXO actor. +func TestVTXOStoreRecoveryOnlyExcludedFromWalletSets(t *testing.T) { + t.Parallel() + + vtxoStore, _, _ := newVTXOStoreForTest(t) + ctx := t.Context() + desc := createTestVTXODescriptor( + t, testRoundIDDB("test-round-recovery-only"), 21, + ) + desc.Status = vtxo.VTXOStatusRecoveryOnly + + require.NoError(t, vtxoStore.SaveRecoveryOnlyVTXO(ctx, desc)) + + stored, err := vtxoStore.GetVTXO(ctx, desc.Outpoint) + require.NoError(t, err) + require.Equal(t, vtxo.VTXOStatusRecoveryOnly, stored.Status) + require.Len(t, stored.Ancestry, len(desc.Ancestry)) + require.Equal( + t, desc.Ancestry[0].CommitmentTxID, + stored.Ancestry[0].CommitmentTxID, + ) + require.Equal( + t, desc.Ancestry[0].TreeDepth, stored.Ancestry[0].TreeDepth, + ) + + live, err := vtxoStore.ListLiveVTXOs(ctx) + require.NoError(t, err) + require.Empty(t, live) + + recoverable, err := vtxoStore.ListRecoverableVTXOs(ctx) + require.NoError(t, err) + require.Empty(t, recoverable) + require.ErrorContains( + t, vtxoStore.SetRecoveryOnlyVTXORelativeExpiry( + ctx, desc.Outpoint, ^uint32(0), + ), + "exceeds storage range", + ) + + // Channel registration sets the materialization delay after the row is + // first saved. Replaying source preparation must preserve that selected + // value instead of mistaking it for an outpoint collision. + selectedExpiry := desc.RelativeExpiry + 10 + require.NoError( + t, vtxoStore.SetRecoveryOnlyVTXORelativeExpiry( + ctx, desc.Outpoint, selectedExpiry, + ), + ) + require.NoError(t, vtxoStore.SaveRecoveryOnlyVTXO(ctx, desc)) + storedRow, err := vtxoStore.db.GetVTXO(ctx, sqlc.GetVTXOParams{ + OutpointHash: desc.Outpoint.Hash[:], + OutpointIndex: int32(desc.Outpoint.Index), + }) + require.NoError(t, err) + require.Equal(t, int32(selectedExpiry), storedRow.Expiry) + + candidates, err := vtxoStore.ListSelectionCandidatesByStatus( + ctx, vtxo.VTXOStatusLive, + ) + require.NoError(t, err) + require.Empty(t, candidates) + + // Durable close actions may replay source preparation after the row has + // already been committed. Identical terms are idempotent, while an + // outpoint collision with different immutable terms must fail. + require.NoError(t, vtxoStore.SaveRecoveryOnlyVTXO(ctx, desc)) + mismatch := *desc + mismatch.Amount++ + require.ErrorContains( + t, vtxoStore.SaveRecoveryOnlyVTXO(ctx, &mismatch), + "descriptor mismatch", + ) + + // The setter must not repurpose an ordinary wallet VTXO as channel + // recovery state. + liveDescriptor := createTestVTXODescriptor( + t, testRoundIDDB("test-round-live-expiry-guard"), 22, + ) + require.NoError(t, vtxoStore.SaveVTXO(ctx, liveDescriptor)) + require.ErrorContains( + t, vtxoStore.SetRecoveryOnlyVTXORelativeExpiry( + ctx, liveDescriptor.Outpoint, + liveDescriptor.RelativeExpiry+10, + ), + "not found", + ) + storedLive, err := vtxoStore.GetVTXO(ctx, liveDescriptor.Outpoint) + require.NoError(t, err) + require.Equal( + t, liveDescriptor.RelativeExpiry, storedLive.RelativeExpiry, + ) +} diff --git a/docs/index.md b/docs/index.md index 04a27939e..b81293675 100644 --- a/docs/index.md +++ b/docs/index.md @@ -38,6 +38,7 @@ into specific topics below. | [mailbox_ingress_safety.md](mailbox_ingress_safety.md) | Durable ingress handoff, quarantine, replay retention, and recovery | | [mailbox_durable_actor_layer.md](mailbox_durable_actor_layer.md) | The durable mailbox and durable actor: leases, dedup, transactional outbox, DurableAsk, and the classic vs. Read/Commit (`TxBehavior`/`Exec[S]`) execution paths | | [mailbox_transport_serverconn_clientconn.md](mailbox_transport_serverconn_clientconn.md) | The RPC-over-mailbox transport relating this client's `serverconn` to the operator's `clientconn`: envelope, edge API, shared `mailbox/conn` primitives, ack watermark, identity/auth/liveness, and the wire contract | +| [mailbox_ingress_safety.md](mailbox_ingress_safety.md) | Ingress evidence contracts: occurrence IDs scoped to the reply mailbox, 30-day delivery receipts consumed at durable inbox insertion, and bounded poison quarantine with per-lane reservations | | [RPC_MAILBOX_CONTRACT.md](RPC_MAILBOX_CONTRACT.md) | Envelope semantics, at-least-once delivery, ack watermarks | | [credit_durable_actor_design.md](credit_durable_actor_design.md) | Credit subsystem durable-actor design: supervisor + per-operation actors driving fault-tolerant sub-floor pay, credit-receive, and redeem flows against the authoritative server ledger | | [wavewalletdk_mobile.md](wavewalletdk_mobile.md) | gomobile-safe `sdk/wavewalletdk/mobile` facade: drives an embedded in-process `waved` wallet from Android/iOS over the private bufconn transport (bytes-out API, no daemon binary) | diff --git a/internal/actortest/e2e_test.go b/internal/actortest/e2e_test.go index 52a46fd5b..ac04c70fd 100644 --- a/internal/actortest/e2e_test.go +++ b/internal/actortest/e2e_test.go @@ -444,7 +444,7 @@ func TestDurableCounter_ForwardWritesToOutbox(t *testing.T) { h := newTestHarness(t) actorID := uniqueID("counter") - counterActor, _ := h.newDurableCounter(actorID) + counterActor, behavior := h.newDurableCounter(actorID) counterActor.Start() defer counterActor.Stop() @@ -473,8 +473,9 @@ func TestDurableCounter_ForwardWritesToOutbox(t *testing.T) { ) require.NoError(t, err) - return len(batch) > 0 + return len(batch) == 1 }) + require.Equal(t, int64(1), behavior.ForwardCount()) require.Len(t, batch, 1) require.Equal(t, actorID, batch[0].SourceActorID) require.Equal(t, "target-counter", batch[0].TargetActorID) diff --git a/lib/actormsg/vtxo_admission.go b/lib/actormsg/vtxo_admission.go index b10df1cc7..ff9ca6ab9 100644 --- a/lib/actormsg/vtxo_admission.go +++ b/lib/actormsg/vtxo_admission.go @@ -420,13 +420,18 @@ const ( // vhtlcrecovery.ExitPolicyKindRefundWithoutReceiver. ExitPolicyVHTLCRefundWithoutReceiver ExitPolicyKind = "vhtlc_" + "refund_without_receiver" + + // ExitPolicyArkChannelBacking identifies a pre-signed channel + // materialization spend from a recovery-only channel-policy VTXO. + ExitPolicyArkChannelBacking ExitPolicyKind = "ark_channel_backing" ) // Valid reports whether the exit policy kind is one of the known non-standard // policies that can ride the ForceUnroll path. func (k ExitPolicyKind) Valid() bool { switch k { - case ExitPolicyVHTLCClaim, ExitPolicyVHTLCRefundWithoutReceiver: + case ExitPolicyVHTLCClaim, ExitPolicyVHTLCRefundWithoutReceiver, + ExitPolicyArkChannelBacking: return true default: diff --git a/lib/actormsg/vtxo_admission_test.go b/lib/actormsg/vtxo_admission_test.go new file mode 100644 index 000000000..928514589 --- /dev/null +++ b/lib/actormsg/vtxo_admission_test.go @@ -0,0 +1,24 @@ +package actormsg + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// TestExitPolicyKindValid verifies every durable non-standard exit policy can +// pass the VTXO manager's recovery-only admission guard. +func TestExitPolicyKindValid(t *testing.T) { + t.Parallel() + + valid := []ExitPolicyKind{ + ExitPolicyVHTLCClaim, + ExitPolicyVHTLCRefundWithoutReceiver, + ExitPolicyArkChannelBacking, + } + for _, kind := range valid { + require.True(t, kind.Valid(), kind) + } + + require.False(t, ExitPolicyKind("unknown").Valid()) +} diff --git a/lib/arkscript/channel_vtxo.go b/lib/arkscript/channel_vtxo.go new file mode 100644 index 000000000..97b99bff1 --- /dev/null +++ b/lib/arkscript/channel_vtxo.go @@ -0,0 +1,446 @@ +package arkscript + +import ( + "bytes" + "fmt" + "math" + + "github.com/btcsuite/btcd/blockchain" + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "github.com/btcsuite/btcd/wire/v2" +) + +const ( + // DefaultChannelReactionWindow separates channel-funding eligibility + // from funder-refund eligibility by 432 blocks: about three days at + // 144 blocks per day, not a wall-clock guarantee. + DefaultChannelReactionWindow uint32 = 432 +) + +// ChannelVTXOParams defines the key roles and relative delays of a VTXO that +// backs an unpublished Lightning channel point. +type ChannelVTXOParams struct { + // ClientArkKey authorizes the client's part of an in-Ark spend. + ClientArkKey *btcec.PublicKey + + // HubArkKey authorizes the hub's part of an in-Ark spend. + HubArkKey *btcec.PublicKey + + // ArkOperatorKey completes the immediate three-party in-Ark spend. + ArkOperatorKey *btcec.PublicKey + + // ClientChannelKey signs the delayed channel-funding transaction. + ClientChannelKey *btcec.PublicKey + + // HubChannelKey cosigns the delayed channel-funding transaction. + HubChannelKey *btcec.PublicKey + + // FunderKey can refund the original contribution after FunderDelay. + FunderKey *btcec.PublicKey + + // ChannelDelay gates the two-party channel-funding path in blocks. + // It preserves time for the Ark operator's checkpoint or forfeit + // recovery after the VTXO confirms, and must be at least MinExitDelay. + ChannelDelay uint32 + + // FunderDelay gates the refund path in blocks from the same VTXO + // confirmation. It must be at least ChannelDelay + ReactionWindow, + // giving the non-funder time to materialize before refund is possible. + FunderDelay uint32 + + // MinExitDelay is the admitting Ark operator's minimum exit delay. + MinExitDelay uint32 + + // ReactionWindow is the minimum block gap between the two delayed + // paths. Zero selects DefaultChannelReactionWindow. Neither delay + // extends the source round's absolute batch expiry. + ReactionWindow uint32 +} + +// ChannelVTXOPolicy is the compiled three-path policy for an Ark-backed +// Lightning channel. +type ChannelVTXOPolicy struct { + // Template retains the semantic policy for encoding and validation. + Template *PolicyTemplate + + // CompiledPolicy provides the canonical tapscripts and spend paths. + *CompiledPolicy + + // CooperativeClosure is the client-hub-operator 3-of-3 path, with no + // CSV delay, used for an in-Ark transfer or cooperative refresh. + CooperativeClosure Node + + // ChannelClosure is the delayed client-hub 2-of-2 path that funds the + // Lightning channel point when the VTXO is materialized on chain. + ChannelClosure Node + + // FunderClosure is the longer-delayed unilateral funder refund path. + FunderClosure Node + + // ChannelDelay is the channel-funding CSV delay from VTXO confirmation. + ChannelDelay uint32 + + // FunderDelay is the refund CSV delay from that same confirmation. + FunderDelay uint32 +} + +// NewChannelVTXOPolicy constructs the cooperative, materialization, and +// funder-refund paths while enforcing their relative timing. +func NewChannelVTXOPolicy(params ChannelVTXOParams) (*ChannelVTXOPolicy, + error) { + + if err := params.validate(); err != nil { + return nil, err + } + + cooperativeClosure := &Multisig{ + Keys: []*btcec.PublicKey{ + params.ClientArkKey, + params.HubArkKey, + params.ArkOperatorKey, + }, + } + channelClosure := &CSV{ + Lock: blockchain.LockTimeToSequence( + false, params.ChannelDelay, + ), + Inner: &Multisig{ + Keys: []*btcec.PublicKey{ + params.ClientChannelKey, + params.HubChannelKey, + }, + }, + } + funderClosure := &CSV{ + Lock: blockchain.LockTimeToSequence( + false, params.FunderDelay, + ), + Inner: &Multisig{ + Keys: []*btcec.PublicKey{ + params.FunderKey, + }, + }, + } + + template := &PolicyTemplate{ + Leaves: []LeafTemplate{ + { + Node: cooperativeClosure, + }, + { + Node: channelClosure, + }, + { + Node: funderClosure, + }, + }, + } + if err := template.ValidateArkPolicy(PolicyValidationOpts{ + OperatorKey: params.ArkOperatorKey, + MinExitDelay: params.MinExitDelay, + }); err != nil { + return nil, fmt.Errorf("validate channel VTXO policy: %w", err) + } + + compiled, err := template.Compile() + if err != nil { + return nil, fmt.Errorf("compile channel VTXO policy: %w", err) + } + + return &ChannelVTXOPolicy{ + Template: template, + CompiledPolicy: compiled, + CooperativeClosure: cooperativeClosure, + ChannelClosure: channelClosure, + FunderClosure: funderClosure, + ChannelDelay: params.ChannelDelay, + FunderDelay: params.FunderDelay, + }, nil +} + +// CooperativeSpendPath returns the immediate client-hub-Ark-operator path. +func (p *ChannelVTXOPolicy) CooperativeSpendPath() (*SpendPath, error) { + return p.SpendPathForNode(p.CooperativeClosure, nil) +} + +// ChannelSpendPath returns the delayed two-party materialization path. +func (p *ChannelVTXOPolicy) ChannelSpendPath() (*SpendPath, error) { + return p.SpendPathForNode(p.ChannelClosure, nil) +} + +// FunderSpendPath returns the later unilateral refund path. +func (p *ChannelVTXOPolicy) FunderSpendPath() (*SpendPath, error) { + return p.SpendPathForNode(p.FunderClosure, nil) +} + +// EncodeChannelVTXOArtifacts returns the semantic policy and its canonical +// P2TR output script. +func EncodeChannelVTXOArtifacts(params ChannelVTXOParams) ([]byte, []byte, + error) { + + policy, err := NewChannelVTXOPolicy(params) + if err != nil { + return nil, nil, err + } + + template, err := policy.Template.Encode() + if err != nil { + return nil, nil, err + } + pkScript, err := policy.Template.PkScript() + if err != nil { + return nil, nil, err + } + + return template, pkScript, nil +} + +// ValidateChannelVTXOPolicy recognizes the canonical three-leaf channel VTXO +// policy using the admitting operator's key and minimum exit delay. It does +// not assign client and hub labels to the two symmetric endpoint key pairs. +func ValidateChannelVTXOPolicy(template *PolicyTemplate, + operatorKey *btcec.PublicKey, minExitDelay uint32) error { + + if template == nil { + return fmt.Errorf("channel VTXO template is required") + } + if operatorKey == nil { + return fmt.Errorf("channel VTXO operator key is required") + } + if minExitDelay == 0 { + return fmt.Errorf("channel VTXO minimum exit delay is required") + } + if len(template.Leaves) != 3 { + return fmt.Errorf("channel VTXO policy must contain exactly " + + "3 leaves") + } + + var ( + cooperativeKeys []*btcec.PublicKey + channelKeys []*btcec.PublicKey + funderKey *btcec.PublicKey + channelDelay uint32 + funderDelay uint32 + ) + for i := range template.Leaves { + switch node := template.Leaves[i].Node.(type) { + case *Multisig: + if len(node.Keys) != 3 || cooperativeKeys != nil { + return fmt.Errorf("channel VTXO leaf %d is "+ + "not the unique 3-of-3 "+ + "cooperative path", i) + } + + cooperativeKeys = node.Keys + + case *CSV: + if err := validateCSVLock(node.Lock); err != nil { + return fmt.Errorf("channel VTXO leaf %d has "+ + "invalid CSV: %w", i, err) + } + + multisig, ok := node.Inner.(*Multisig) + if !ok { + return fmt.Errorf("channel VTXO leaf %d is "+ + "not CSV-gated multisig", i) + } + + delay := node.Lock & uint32(wire.SequenceLockTimeMask) + switch len(multisig.Keys) { + case 2: + if channelKeys != nil { + return fmt.Errorf("channel VTXO has " + + "multiple 2-of-2 " + + "materialization paths") + } + + channelKeys = multisig.Keys + channelDelay = delay + + case 1: + if funderKey != nil { + return fmt.Errorf("channel VTXO has " + + "multiple funder refund paths") + } + + funderKey = multisig.Keys[0] + funderDelay = delay + + default: + return fmt.Errorf("channel VTXO leaf %d has "+ + "%d signing keys", i, len( + multisig.Keys, + )) + } + + default: + return fmt.Errorf("channel VTXO leaf %d has an "+ + "unsupported shape", i) + } + } + + if cooperativeKeys == nil || channelKeys == nil || funderKey == nil { + return fmt.Errorf("channel VTXO policy is missing a required " + + "path") + } + + params := ChannelVTXOParams{ + ClientArkKey: cooperativeKeys[0], + HubArkKey: cooperativeKeys[1], + ArkOperatorKey: operatorKey, + ClientChannelKey: channelKeys[0], + HubChannelKey: channelKeys[1], + FunderKey: funderKey, + ChannelDelay: channelDelay, + FunderDelay: funderDelay, + MinExitDelay: minExitDelay, + } + + return ValidateChannelVTXOTemplate(template, params) +} + +// ValidateChannelVTXOTemplate verifies that an untrusted template has the +// exact key roles and delays expected by a channel intent. +func ValidateChannelVTXOTemplate(template *PolicyTemplate, + params ChannelVTXOParams) error { + + if template == nil { + return fmt.Errorf("channel VTXO template is required") + } + + expected, err := NewChannelVTXOPolicy(params) + if err != nil { + return err + } + if len(template.Leaves) != len(expected.Template.Leaves) { + return fmt.Errorf("channel VTXO policy must contain exactly " + + "3 leaves") + } + + actualScripts := make(map[string]struct{}, len(template.Leaves)) + for i := range template.Leaves { + script, err := template.Leaves[i].Script() + if err != nil { + return fmt.Errorf("compile channel VTXO leaf %d: %w", i, + err) + } + + actualScripts[string(script)] = struct{}{} + } + + for i := range expected.Template.Leaves { + script, err := expected.Template.Leaves[i].Script() + if err != nil { + return err + } + if _, ok := actualScripts[string(script)]; !ok { + return fmt.Errorf("channel VTXO policy does not " + + "match expected key roles and delays") + } + } + + actualPkScript, err := template.PkScript() + if err != nil { + return fmt.Errorf("compile channel VTXO output: %w", err) + } + expectedPkScript, err := expected.Template.PkScript() + if err != nil { + return fmt.Errorf("compile expected channel VTXO output: %w", + err) + } + if !bytes.Equal(actualPkScript, expectedPkScript) { + return fmt.Errorf("channel VTXO output does not match " + + "expected key roles and delays") + } + + return nil +} + +// validate enforces key separation and the funder reaction window. +func (p ChannelVTXOParams) validate() error { + keys := []struct { + name string + key *btcec.PublicKey + }{ + { + name: "client Ark", + key: p.ClientArkKey, + }, + { + name: "hub Ark", + key: p.HubArkKey, + }, + { + name: "Ark operator", + key: p.ArkOperatorKey, + }, + { + name: "client channel", + key: p.ClientChannelKey, + }, + { + name: "hub channel", + key: p.HubChannelKey, + }, + { + name: "funder", + key: p.FunderKey, + }, + } + for _, key := range keys { + if key.key == nil { + return fmt.Errorf("channel VTXO %s key is nil", + key.name) + } + } + + if channelKeysEqual(p.ClientArkKey, p.HubArkKey) || + channelKeysEqual(p.ClientArkKey, p.ArkOperatorKey) || + channelKeysEqual(p.HubArkKey, p.ArkOperatorKey) { + return fmt.Errorf("channel VTXO cooperative keys must be " + + "controlled by three distinct parties") + } + if channelKeysEqual(p.ClientChannelKey, p.HubChannelKey) { + return fmt.Errorf("channel VTXO materialization keys must be " + + "distinct") + } + + if p.MinExitDelay == 0 { + return fmt.Errorf("channel VTXO minimum exit delay must be " + + "non-zero") + } + if p.ChannelDelay < p.MinExitDelay { + return fmt.Errorf("channel delay %d is below Ark minimum %d", + p.ChannelDelay, p.MinExitDelay) + } + if p.ChannelDelay > wire.SequenceLockTimeMask || + p.FunderDelay > wire.SequenceLockTimeMask { + return fmt.Errorf("channel VTXO delays must fit BIP-68 block " + + "mode") + } + + reactionWindow := p.ReactionWindow + if reactionWindow == 0 { + reactionWindow = DefaultChannelReactionWindow + } + if reactionWindow > wire.SequenceLockTimeMask || + p.ChannelDelay > math.MaxUint32-reactionWindow { + return fmt.Errorf("channel VTXO reaction window overflows") + } + minimumFunderDelay := p.ChannelDelay + reactionWindow + if p.FunderDelay < minimumFunderDelay { + return fmt.Errorf("funder delay %d must be at least %d to "+ + "preserve the reaction window", p.FunderDelay, + minimumFunderDelay) + } + + return nil +} + +// channelKeysEqual compares public keys by their x-only tapscript encoding. +func channelKeysEqual(a, b *btcec.PublicKey) bool { + return bytes.Equal( + schnorr.SerializePubKey(a), schnorr.SerializePubKey(b), + ) +} diff --git a/lib/arkscript/channel_vtxo_test.go b/lib/arkscript/channel_vtxo_test.go new file mode 100644 index 000000000..f3c296127 --- /dev/null +++ b/lib/arkscript/channel_vtxo_test.go @@ -0,0 +1,158 @@ +package arkscript + +import ( + "testing" + + "github.com/btcsuite/btcd/blockchain" + "github.com/btcsuite/btcd/btcec/v2" + "github.com/stretchr/testify/require" +) + +// TestChannelVTXOPolicyPaths verifies each spend path has the intended signer +// set and relative delay. +func TestChannelVTXOPolicyPaths(t *testing.T) { + t.Parallel() + + params := testChannelVTXOParams(t) + policy, err := NewChannelVTXOPolicy(params) + require.NoError(t, err) + + cooperative, err := policy.CooperativeSpendPath() + require.NoError(t, err) + require.Equal(t, ^uint32(0), cooperative.RequiredSequence) + cooperativeNode, ok := policy.CooperativeClosure.(*Multisig) + require.True(t, ok) + require.Len(t, cooperativeNode.Keys, 3) + + channel, err := policy.ChannelSpendPath() + require.NoError(t, err) + require.Equal( + t, blockchain.LockTimeToSequence( + false, params.ChannelDelay, + ), + channel.RequiredSequence, + ) + channelCSV, ok := policy.ChannelClosure.(*CSV) + require.True(t, ok) + channelNode, ok := channelCSV.Inner.(*Multisig) + require.True(t, ok) + require.Len(t, channelNode.Keys, 2) + + funder, err := policy.FunderSpendPath() + require.NoError(t, err) + require.Equal( + t, blockchain.LockTimeToSequence( + false, params.FunderDelay, + ), + funder.RequiredSequence, + ) + funderCSV, ok := policy.FunderClosure.(*CSV) + require.True(t, ok) + funderNode, ok := funderCSV.Inner.(*Multisig) + require.True(t, ok) + require.Len(t, funderNode.Keys, 1) +} + +// TestChannelVTXOPolicyReactionWindow rejects a refund path that can overtake +// the channel endpoints before they have time to materialize. +func TestChannelVTXOPolicyReactionWindow(t *testing.T) { + t.Parallel() + + params := testChannelVTXOParams(t) + params.FunderDelay = params.ChannelDelay + + DefaultChannelReactionWindow - 1 + + _, err := NewChannelVTXOPolicy(params) + require.ErrorContains(t, err, "preserve the reaction window") +} + +// TestChannelVTXOPolicyCustomReactionWindow verifies callers can increase the +// block budget without changing the channel-funding delay. +func TestChannelVTXOPolicyCustomReactionWindow(t *testing.T) { + t.Parallel() + + params := testChannelVTXOParams(t) + params.ReactionWindow = 2 * DefaultChannelReactionWindow + _, err := NewChannelVTXOPolicy(params) + require.ErrorContains(t, err, "preserve the reaction window") + + params.FunderDelay = params.ChannelDelay + params.ReactionWindow + policy, err := NewChannelVTXOPolicy(params) + require.NoError(t, err) + require.Equal(t, params.ChannelDelay, policy.ChannelDelay) + require.Equal(t, params.FunderDelay, policy.FunderDelay) +} + +// TestValidateChannelVTXOTemplate detects any change to the persisted channel +// contract while accepting a canonical encode/decode round trip. +func TestValidateChannelVTXOTemplate(t *testing.T) { + t.Parallel() + + params := testChannelVTXOParams(t) + raw, pkScript, err := EncodeChannelVTXOArtifacts(params) + require.NoError(t, err) + require.NotEmpty(t, pkScript) + + template, err := DecodePolicyTemplate(raw) + require.NoError(t, err) + derivedPkScript, err := template.PkScript() + require.NoError(t, err) + require.Equal(t, pkScript, derivedPkScript) + require.NoError(t, ValidateChannelVTXOTemplate(template, params)) + + otherKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + params.HubChannelKey = otherKey.PubKey() + require.Error(t, ValidateChannelVTXOTemplate(template, params)) +} + +// TestValidateChannelVTXOPolicy verifies admission can recognize the +// canonical policy without trusting caller-supplied channel terms. +func TestValidateChannelVTXOPolicy(t *testing.T) { + t.Parallel() + + params := testChannelVTXOParams(t) + raw, _, err := EncodeChannelVTXOArtifacts(params) + require.NoError(t, err) + template, err := DecodePolicyTemplate(raw) + require.NoError(t, err) + + // Leaf order does not affect the Taproot policy or its classification. + template.Leaves[0], template.Leaves[2] = + template.Leaves[2], template.Leaves[0] + err = ValidateChannelVTXOPolicy( + template, params.ArkOperatorKey, params.MinExitDelay, + ) + require.NoError(t, err) + + otherOperator, err := btcec.NewPrivateKey() + require.NoError(t, err) + err = ValidateChannelVTXOPolicy( + template, otherOperator.PubKey(), params.MinExitDelay, + ) + require.ErrorContains(t, err, "does not match expected key roles") +} + +// testChannelVTXOParams returns independent keys and valid channel delays. +func testChannelVTXOParams(t *testing.T) ChannelVTXOParams { + t.Helper() + + keys := make([]*btcec.PrivateKey, 6) + for i := range keys { + key, err := btcec.NewPrivateKey() + require.NoError(t, err) + keys[i] = key + } + + return ChannelVTXOParams{ + ClientArkKey: keys[0].PubKey(), + HubArkKey: keys[1].PubKey(), + ArkOperatorKey: keys[2].PubKey(), + ClientChannelKey: keys[3].PubKey(), + HubChannelKey: keys[4].PubKey(), + FunderKey: keys[5].PubKey(), + ChannelDelay: 144, + FunderDelay: 144 + DefaultChannelReactionWindow, + MinExitDelay: 144, + } +} diff --git a/lwwallet/chain_backend.go b/lwwallet/chain_backend.go index aa7adeb1f..61dee2e7d 100644 --- a/lwwallet/chain_backend.go +++ b/lwwallet/chain_backend.go @@ -713,12 +713,16 @@ func (b *ChainBackend) RegisterSpend(ctx context.Context, b.cancelSpendReg(id, reg) } - // Per-registration one-shot to handle outpoints that are - // already spent at registration time. See RegisterConf for the - // O(N²)-vs-O(1) rationale and the b.wg lifecycle note. + // Complete the initial spend check before returning. Lnd's transaction + // publisher performs a non-blocking read immediately after registering + // to distinguish a confirmed transaction from an RBF candidate. An + // asynchronous initial check can therefore make lnd replace an already + // confirmed sweep and terminally fail it with missing inputs. + // + // The check remains scoped to this registration, so registration is + // still O(1) rather than re-scanning all pending registrations. b.wg.Add(1) - //nolint:contextcheck // registration cancel/Stop own one-shot lifetime - go b.runSpendOneShot(id, reg) + b.runSpendOneShot(ctx, id, reg) return &chainsource.SpendRegistration{ Spend: spendChan, @@ -752,7 +756,9 @@ func (b *ChainBackend) cancelSpendReg(id uint64, reg *spendRegistration) { // triggered at RegisterSpend time. The registration is NOT deleted // after delivery: a reorg may later reset it to stateWatching and // the next re-check must fire Spend again on the new chain. -func (b *ChainBackend) runSpendOneShot(id uint64, reg *spendRegistration) { +func (b *ChainBackend) runSpendOneShot(ctx context.Context, id uint64, + reg *spendRegistration) { + defer b.wg.Done() select { @@ -769,14 +775,16 @@ func (b *ChainBackend) runSpendOneShot(id uint64, reg *spendRegistration) { return } - b.deliverSpendIfNew(id, reg) + b.deliverSpendIfNew(ctx, id, reg) } // deliverSpendIfNew runs a spend re-check and fires the Spend // channel iff the registration is in stateWatching and a spend is // now available. Mirror of deliverConfIfNew; see that function's // comment for the regMu / channel-send ordering rationale. -func (b *ChainBackend) deliverSpendIfNew(id uint64, reg *spendRegistration) { +func (b *ChainBackend) deliverSpendIfNew(ctx context.Context, id uint64, + reg *spendRegistration) { + reg.regMu.Lock() if reg.state == statePositive { reg.regMu.Unlock() @@ -791,11 +799,9 @@ func (b *ChainBackend) deliverSpendIfNew(id uint64, reg *spendRegistration) { // did not parse and reorgSpendReg will fall back to a // conservative re-check rather than try to match against // ReorgEvent.Disconnected. - detail, spendingBlockHash, err := b.checkSingleSpend(reg) + detail, spendingBlockHash, err := b.checkSingleSpend(ctx, reg) if err != nil { - b.log.DebugS( - context.Background(), - "Spend status temporarily unavailable", + b.log.DebugS(ctx, "Spend status temporarily unavailable", slog.Uint64("reg_id", id), btclog.Fmt("err", "%v", err), ) @@ -828,7 +834,7 @@ func (b *ChainBackend) deliverSpendIfNew(id uint64, reg *spendRegistration) { return } - b.log.DebugS(context.Background(), + b.log.DebugS(ctx, "Spend registration fulfilled", slog.Uint64("reg_id", id), slog.String("outpoint", reg.outpoint.String()), @@ -1069,7 +1075,9 @@ func (b *ChainBackend) reorgSpendReg(id uint64, reg *spendRegistration, // was unparseable at delivery time. If the outpoint is // still spent by the same spender in the same block, // no reorg for this registration. - current, currentBlock, err := b.checkSingleSpend(reg) + current, currentBlock, err := b.checkSingleSpend( + context.Background(), reg, + ) if err != nil { b.log.DebugS( context.Background(), @@ -1120,7 +1128,7 @@ func (b *ChainBackend) reorgSpendReg(id uint64, reg *spendRegistration, slog.Uint64("reg_id", id), ) - b.deliverSpendIfNew(id, reg) + b.deliverSpendIfNew(context.Background(), id, reg) } // handleChainEvents drains the unified chain stream and dispatches @@ -1500,7 +1508,7 @@ func (b *ChainBackend) checkSpends() { continue } - b.deliverSpendIfNew(id, reg) + b.deliverSpendIfNew(context.Background(), id, reg) } } @@ -1511,15 +1519,16 @@ func (b *ChainBackend) checkSpends() { // interpreted as a reorg. The second return value is the block hash containing // the spending tx; a zero hash means only that the hash was unparseable while // the spend itself was valid. -func (b *ChainBackend) checkSingleSpend(reg *spendRegistration) ( - *chainsource.SpendDetail, chainhash.Hash, error) { +func (b *ChainBackend) checkSingleSpend(ctx context.Context, + reg *spendRegistration) (*chainsource.SpendDetail, chainhash.Hash, + error) { if reg.outpoint == nil { return nil, chainhash.Hash{}, nil } outspend, err := b.esplora.GetOutspend( - context.Background(), reg.outpoint.Hash, reg.outpoint.Index, + ctx, reg.outpoint.Hash, reg.outpoint.Index, ) if err != nil { return nil, chainhash.Hash{}, err @@ -1534,9 +1543,7 @@ func (b *ChainBackend) checkSingleSpend(reg *spendRegistration) ( return nil, chainhash.Hash{}, err } - spendingTx, err := b.esplora.GetRawTx( - context.Background(), *spenderHash, - ) + spendingTx, err := b.esplora.GetRawTx(ctx, *spenderHash) if err != nil { return nil, chainhash.Hash{}, err } diff --git a/lwwallet/chain_backend_test.go b/lwwallet/chain_backend_test.go index cfaa75fba..d92e52192 100644 --- a/lwwallet/chain_backend_test.go +++ b/lwwallet/chain_backend_test.go @@ -416,8 +416,8 @@ func TestChainBackendConfRegistration(t *testing.T) { } } -// TestChainBackendSpendRegistration verifies that spend -// registrations fire when an output is spent. +// TestChainBackendSpendRegistration verifies that historical spends are +// buffered before registration returns. func TestChainBackendSpendRegistration(t *testing.T) { t.Parallel() @@ -499,8 +499,8 @@ func TestChainBackendSpendRegistration(t *testing.T) { require.Equal(t, uint32(1), spend.SpenderInputIndex) require.Equal(t, int32(99), spend.SpendingHeight) - case <-time.After(2 * time.Second): - t.Fatal("timed out waiting for spend notification") + default: + t.Fatal("historical spend was not available on return") } } diff --git a/lwwallet/esplora_chain.go b/lwwallet/esplora_chain.go index 605a71622..0111dd338 100644 --- a/lwwallet/esplora_chain.go +++ b/lwwallet/esplora_chain.go @@ -5,6 +5,7 @@ import ( "fmt" "log/slog" "sort" + "strings" "sync" "time" @@ -832,6 +833,10 @@ func (s *EsploraChainService) Rescan(startHash *chainhash.Hash, if err != nil { return fmt.Errorf("get tip height for rescan: %w", err) } + if startHeight > tipHeight { + return fmt.Errorf("rescan start height %d exceeds tip %d", + startHeight, tipHeight) + } s.log.InfoS(ctx, "Starting chain rescan", slog.Int("start_height", int(startHeight)), @@ -842,7 +847,11 @@ func (s *EsploraChainService) Rescan(startHash *chainhash.Hash, // Collect all notifications first, then flush them // asynchronously. See method doc for deadlock rationale. - var pending []interface{} + var ( + pending []interface{} + finalHash chainhash.Hash + finalTime time.Time + ) // Ask the address index which transactions in this range are // relevant, instead of downloading every block and scanning it. @@ -891,6 +900,8 @@ func (s *EsploraChainService) Rescan(startHash *chainhash.Hash, }, Time: time.Unix(blockHeader.Timestamp, 0), } + finalHash = blockHash + finalTime = blockMeta.Time // Build records for whatever the index attributed to this // canonical block. An inconsistent index answer falls back to @@ -962,6 +973,15 @@ func (s *EsploraChainService) Rescan(startHash *chainhash.Hash, ) } + // btcwallet only marks its chain view synchronized after this terminal + // notification. Advancing SyncedTo without it leaves channel funding + // disabled even though every block has been processed. + pending = append(pending, &chain.RescanFinished{ + Hash: &finalHash, + Height: tipHeight, + Time: finalTime, + }) + s.log.InfoS(ctx, "Chain rescan complete", slog.Int("tip_height", int(tipHeight)), slog.Int("pending_notifications", len(pending)), @@ -1219,10 +1239,34 @@ func (s *EsploraChainService) TestMempoolAccept(txns []*wire.MsgTx, return results, nil } -// MapRPCErr passes through errors unchanged since the Esplora backend -// does not use RPC error codes. -func (s *EsploraChainService) MapRPCErr(err error) error { - return err +// MapRPCErr maps Bitcoin Core reject reasons returned by Esplora to the +// sentinel errors expected by btcwallet and lnd. +func (s *EsploraChainService) MapRPCErr(rpcErr error) error { + for code := chain.ErrMissingInputsOrSpent; code <= + chain.ErrBadWitnessNonStandard; code++ { + + if chainErrorMatches(rpcErr, code.Error()) { + return code + } + } + + for message, mappedErr := range chain.Bitcoind28ErrMap { + if chainErrorMatches(rpcErr, message) { + return mappedErr + } + } + + return fmt.Errorf("%w: %w", chain.ErrUndefined, rpcErr) +} + +// chainErrorMatches normalizes Core's dashed reject reasons before matching. +func chainErrorMatches(err error, pattern string) bool { + errText := strings.ReplaceAll(err.Error(), "-", " ") + pattern = strings.ReplaceAll(pattern, "-", " ") + + return strings.Contains( + strings.ToLower(errText), strings.ToLower(pattern), + ) } // handleChainEvents drains the unified chain stream and translates diff --git a/lwwallet/esplora_chain_test.go b/lwwallet/esplora_chain_test.go index 10737b818..6fbb10d1c 100644 --- a/lwwallet/esplora_chain_test.go +++ b/lwwallet/esplora_chain_test.go @@ -5,6 +5,7 @@ import ( "context" "encoding/hex" "encoding/json" + "errors" "fmt" "net/http" "net/http/httptest" @@ -21,6 +22,35 @@ import ( "github.com/stretchr/testify/require" ) +// TestEsploraChainServiceMapRPCErr verifies that Esplora's textual Core +// reject reasons retain the error identities consumed by lnd's sweeper. +func TestEsploraChainServiceMapRPCErr(t *testing.T) { + t.Parallel() + + service := &EsploraChainService{} + require.ErrorIs( + t, + service.MapRPCErr( + errors.New("missing-inputs"), + ), + chain.ErrMissingInputs, + ) + require.ErrorIs( + t, + service.MapRPCErr( + errors.New("mempool script verify flag failed"), + ), + chain.ErrNonMandatoryScriptVerifyFlag, + ) + require.ErrorIs( + t, + service.MapRPCErr( + errors.New("unknown rejection"), + ), + chain.ErrUndefined, + ) +} + // TestEsploraChainServiceStopCancelsRequestContext verifies that Stop cancels // the context used by chain.Interface methods. Btcwallet waits for its recovery // goroutine before it stops the chain client, so lwwallet must be able to diff --git a/lwwallet/esplora_filterblocks_test.go b/lwwallet/esplora_filterblocks_test.go index e7c018540..a140c4808 100644 --- a/lwwallet/esplora_filterblocks_test.go +++ b/lwwallet/esplora_filterblocks_test.go @@ -957,6 +957,12 @@ func TestRescanUsesIndexAndOrdersDependencies(t *testing.T) { t, svc.notifications, ) require.Equal(t, meta.Hash, wtxmgr.BlockMeta(connected).Hash) + + finished := requireNotification[*chain.RescanFinished]( + t, svc.notifications, + ) + require.Equal(t, meta.Hash, *finished.Hash) + require.Equal(t, meta.Height, finished.Height) require.Zero(t, idx.rawBlockFetches) } diff --git a/lwwallet/esplora_rescan_watch_test.go b/lwwallet/esplora_rescan_watch_test.go index 120454c9c..34cb88930 100644 --- a/lwwallet/esplora_rescan_watch_test.go +++ b/lwwallet/esplora_rescan_watch_test.go @@ -43,14 +43,16 @@ func TestRescanRetainsLiveChangeWatch(t *testing.T) { start := stub.hashFor(100) require.NoError(t, service.Rescan(&start, addresses, nil)) - // Drain the historical scan before driving the next live block. - for range 2 { - select { - case <-service.Notifications(): - case <-time.After(time.Second): - t.Fatal("missing historical rescan notification") - } - } + // Rescan flushes asynchronously. Validate the historical block pair + // and terminal event before driving the next live block. + historical := readSpendWatchBlock(t, service) + finished := requireNotification[*chain.RescanFinished]( + t, service.Notifications(), + ) + require.Equal(t, historical.Block.Height, finished.Height) + require.Equal(t, historical.Block.Hash, *finished.Hash) + require.Equal(t, historical.Block.Time, finished.Time) + script, err := txscript.PayToAddrScript(addresses[1]) require.NoError(t, err) funding := wire.OutPoint{Hash: chainhash.Hash{1}, Index: 0} @@ -75,19 +77,12 @@ func TestRescanRetainsLiveChangeWatch(t *testing.T) { stub.tipHeight = 101 stub.mu.Unlock() service.processTipEvent(t.Context(), tipEventFor(stub, 101)) - select { - case notification := <-service.Notifications(): - filtered, ok := notification.(chain.FilteredBlockConnected) - require.True(t, ok) - require.EqualValues(t, 101, filtered.Block.Height) - require.Len(t, filtered.RelevantTxs, 1) - require.Equal(t, spend.TxHash(), filtered.RelevantTxs[0].Hash) - require.Equal( - t, funding, - filtered.RelevantTxs[0].MsgTx.TxIn[0].PreviousOutPoint, - ) - - case <-time.After(time.Second): - t.Fatal("rescan change address missing from live notifications") - } + filtered := readSpendWatchBlock(t, service) + require.EqualValues(t, 101, filtered.Block.Height) + require.Len(t, filtered.RelevantTxs, 1) + require.Equal(t, spend.TxHash(), filtered.RelevantTxs[0].Hash) + require.Equal( + t, funding, + filtered.RelevantTxs[0].MsgTx.TxIn[0].PreviousOutPoint, + ) } diff --git a/lwwallet/esplora_spend_watch_test.go b/lwwallet/esplora_spend_watch_test.go index 83083ede5..c808c0d18 100644 --- a/lwwallet/esplora_spend_watch_test.go +++ b/lwwallet/esplora_spend_watch_test.go @@ -50,10 +50,14 @@ func readSpendWatchBlock(t *testing.T, if i == 0 { var ok bool filtered, ok = n.(chain.FilteredBlockConnected) - require.True(t, ok) + require.True( + t, ok, "unexpected notification %T", n, + ) } else { _, ok := n.(chain.BlockConnected) - require.True(t, ok) + require.True( + t, ok, "unexpected notification %T", n, + ) } case <-time.After(time.Second): @@ -114,7 +118,20 @@ func TestLiveWatchesIncludeInputOnlySpends(t *testing.T) { require.NoError( t, service.Rescan(&start, addresses, coins), ) - readSpendWatchBlock(t, service) + historical := readSpendWatchBlock(t, service) + + // Rescan flushes asynchronously. Observe its terminal + // event before delivering a live block to the same + // notification queue. + finished := requireNotification[*chain.RescanFinished]( + t, service.Notifications(), + ) + require.Equal( + t, historical.Block.Height, finished.Height, + ) + require.Equal(t, historical.Block.Hash, *finished.Hash) + require.Equal(t, historical.Block.Time, finished.Time) + height := int32(101) if mode == "live output" { installSpendWatchBlock(stub, height, funding) diff --git a/mailbox/rpc/retry.go b/mailbox/rpc/retry.go index f8672c0ec..e742065cf 100644 --- a/mailbox/rpc/retry.go +++ b/mailbox/rpc/retry.go @@ -143,14 +143,11 @@ func Retry(ctx context.Context, policy RetryPolicy, // idempotency key, for example because the key is derived from a durable // record so it survives a restart. Passing an empty key mints one. // -// The key must not already be in flight elsewhere when this is called. Both -// the operator's deduplication and the transport's habit of defaulting the -// correlation ID to the key assume one live request per key, so two callers -// retrying concurrently under the same key would land two waiters on one -// correlation ID and let either one collect the other's answer. Nothing here -// enforces that, because every caller today re-issues sequentially from a -// single goroutine; a caller that wants concurrent attempts of the same -// logical request needs its own key per attempt-set. +// The key must not already be in flight elsewhere when this is called. The +// operator's deduplication assumes one active attempt per logical operation; +// concurrent requests under one key can observe an in-doubt execution rather +// than its eventual result. Nothing here enforces serialization, because every +// caller today re-issues sequentially from a single goroutine. func RetryWithKey(ctx context.Context, policy RetryPolicy, key string, call func(context.Context, RPCOptions) error) error { diff --git a/oor/AGENTS.md b/oor/AGENTS.md index cb4898f95..676ae19e6 100644 --- a/oor/AGENTS.md +++ b/oor/AGENTS.md @@ -114,13 +114,15 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/oor. 1 { + return startTransferPayload{}, fmt.Errorf("prepare-only flag " + + "must be 0 or 1") + } inputs, err := decodeTransferInputSnapshotsWithLimits( inputsRaw, limits, @@ -298,6 +321,7 @@ func decodeStartTransferPayloadWithLimits(raw []byte, IdempotencyKey: string(idKey), DispatchRequestData: dispatchRequestData, AdmissionDeadlineUnixNanos: int64(deadline), + PrepareOnly: prepareOnly != 0, }, nil } @@ -1289,6 +1313,20 @@ func encodeTransferInputSnapshot(input *TransferInputSnapshot) ([]byte, error) { transferInputReserveEpochRecordType, &reserveEpoch, ), ) + if len(input.ExternalArkSignatures) > 0 { + blob, err := encodeExternalSignatures( + input.ExternalArkSignatures, + ) + if err != nil { + return nil, err + } + records = append( + records, tlv.MakePrimitiveRecord( + transferInputExternalArkSignaturesRecordType, + &blob, + ), + ) + } return tlvutil.EncodeRecordsToBytes(records...) } @@ -1310,6 +1348,7 @@ func decodeTransferInputSnapshot(raw []byte) (*TransferInputSnapshot, error) { controlBlock []byte condBlob []byte externalSigBlob []byte + externalArkSigBlob []byte requiredSequence uint32 requiredLockTime uint32 reserveEpoch uint64 @@ -1376,6 +1415,10 @@ func decodeTransferInputSnapshot(raw []byte) (*TransferInputSnapshot, error) { tlv.MakePrimitiveRecord( transferInputReserveEpochRecordType, &reserveEpoch, ), + tlv.MakePrimitiveRecord( + transferInputExternalArkSignaturesRecordType, + &externalArkSigBlob, + ), } if _, err := decodeBoundedRecords( @@ -1437,6 +1480,13 @@ func decodeTransferInputSnapshot(raw []byte) (*TransferInputSnapshot, error) { snap.ExternalSignatures = sigs } + if len(externalArkSigBlob) > 0 { + sigs, err := decodeExternalSignatures(externalArkSigBlob) + if err != nil { + return nil, err + } + snap.ExternalArkSignatures = sigs + } return snap, nil } @@ -2038,6 +2088,13 @@ func encodeEventPayload(event Event) ([]byte, error) { ) switch evt := event.(type) { + case *CommitPreparedEvent: + eventKind = eventKindCommitPrepared + + case *AbortPreparedEvent: + eventKind = eventKindAbortPrepared + reason = []byte(evt.Reason) + case *ArkSignedEvent: eventKind = eventKindArkSigned if evt.ArkPSBT == nil { @@ -2227,8 +2284,6 @@ func encodeEventPayload(event Event) ([]byte, error) { // decodeEventPayloadWithLimits decodes an event payload and applies receive // limits to nested list-shaped event fields. -// -//nolint:funlen // One TLV switch owns the complete event wire format. func decodeEventPayloadWithLimits(raw []byte, limits ReceiveLimits) (Event, error) { @@ -2290,6 +2345,12 @@ func decodeEventPayloadWithLimits(raw []byte, } switch eventKind { + case eventKindCommitPrepared: + return &CommitPreparedEvent{}, nil + + case eventKindAbortPrepared: + return &AbortPreparedEvent{Reason: string(reason)}, nil + case eventKindArkSigned: ark, err := psbtutil.Parse(arkPSBT) if err != nil { @@ -2350,43 +2411,10 @@ func decodeEventPayloadWithLimits(raw []byte, return &FailEvent{Reason: string(reason)}, nil case eventKindIncomingTransfer: - if len(arkPSBT) == 0 { - return nil, fmt.Errorf("incoming transfer event ark " + - "psbt must be provided") - } - - ark, err := psbtutil.Parse(arkPSBT) - if err != nil { - return nil, err - } - - checkpoints, err := decodeCheckpointPSBTsWithLimits( - checkpointPSBT, limits, - ) - if err != nil { - return nil, err - } - - ancestors, err := decodePackageArtifactsWithLimits( - ancestorPayload, limits, - ) - if err != nil { - return nil, err - } - - recipients, err := decodeIncomingRecipientsWithLimits( + return decodeIncomingTransferEvent( + arkPSBT, checkpointPSBT, ancestorPayload, recipientPayload, limits, ) - if err != nil { - return nil, err - } - - return &IncomingTransferEvent{ - ArkPSBT: ark, - FinalCheckpointPSBTs: checkpoints, - AncestorPackages: ancestors, - Recipients: recipients, - }, nil case eventKindIncomingHandled: outpoints, err := decodeOutPointListWithLimits( @@ -2436,6 +2464,47 @@ func decodeEventPayloadWithLimits(raw []byte, } } +// decodeIncomingTransferEvent decodes the list-shaped fields carried by an +// incoming transfer event under the configured receive limits. +func decodeIncomingTransferEvent(arkPSBT, checkpointPSBT, ancestorPayload, + recipientPayload []byte, limits ReceiveLimits) (Event, error) { + + if len(arkPSBT) == 0 { + return nil, fmt.Errorf("incoming transfer event ark psbt " + + "must be provided") + } + + ark, err := psbtutil.Parse(arkPSBT) + if err != nil { + return nil, err + } + checkpoints, err := decodeCheckpointPSBTsWithLimits( + checkpointPSBT, limits, + ) + if err != nil { + return nil, err + } + ancestors, err := decodePackageArtifactsWithLimits( + ancestorPayload, limits, + ) + if err != nil { + return nil, err + } + recipients, err := decodeIncomingRecipientsWithLimits( + recipientPayload, limits, + ) + if err != nil { + return nil, err + } + + return &IncomingTransferEvent{ + ArkPSBT: ark, + FinalCheckpointPSBTs: checkpoints, + AncestorPackages: ancestors, + Recipients: recipients, + }, nil +} + // decodeCheckpointPSBTsWithLimits decodes checkpoint PSBT lists using receive // limits for the outer blob list. func decodeCheckpointPSBTsWithLimits(raw []byte, diff --git a/oor/actor_durable_message_test.go b/oor/actor_durable_message_test.go index d7b1ec41a..a90e232ad 100644 --- a/oor/actor_durable_message_test.go +++ b/oor/actor_durable_message_test.go @@ -71,6 +71,7 @@ func TestStartTransferPayloadTLVRoundTrip(t *testing.T) { 3, }, AdmissionDeadlineUnixNanos: 1_700_000_000_123_456_789, + PrepareOnly: true, } raw, err := encodeStartTransferPayload(payload) @@ -92,10 +93,73 @@ func TestStartTransferPayloadTLVRoundTrip(t *testing.T) { t, payload.AdmissionDeadlineUnixNanos, decoded.AdmissionDeadlineUnixNanos, ) + require.Equal(t, payload.PrepareOnly, decoded.PrepareOnly) require.Len(t, decoded.Inputs, 1) require.Equal(t, payload.Inputs[0], decoded.Inputs[0]) } +// TestStartTransferPayloadRejectsNonCanonicalBool verifies durable messages do +// not silently reinterpret malformed boolean values across implementations. +func TestStartTransferPayloadRejectsNonCanonicalBool(t *testing.T) { + t.Parallel() + + raw, err := encodeStartTransferPayload(startTransferPayload{ + PrepareOnly: true, + }) + require.NoError(t, err) + require.NotEmpty(t, raw) + + // PrepareOnly is the final, one-byte TLV record in this payload. + raw[len(raw)-1] = 2 + _, err = decodeStartTransferPayload(raw) + require.ErrorContains(t, err, "prepare-only flag must be 0 or 1") +} + +// TestDriveEventRequestRoundTripPreparedEvents verifies the two-phase OOR +// control events survive the durable mailbox codec. +func TestDriveEventRequestRoundTripPreparedEvents(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + event Event + }{ + { + name: "commit", + event: &CommitPreparedEvent{}, + }, + { + name: "abort", + event: &AbortPreparedEvent{ + Reason: "channel negotiation failed", + }, + }, + } + + for _, test := range tests { + test := test + t.Run(test.name, func(t *testing.T) { + t.Parallel() + + msg := &DriveEventRequest{ + SessionID: SessionID{ + 1, + 2, + 3, + }, + Event: test.event, + } + var buf bytes.Buffer + require.NoError(t, msg.Encode(&buf)) + + var decoded DriveEventRequest + require.NoError(t, decoded.Decode(&buf)) + require.Equal(t, msg.SessionID, decoded.SessionID) + require.Equal(t, test.event, decoded.Event) + }) + } +} + // TestLookupTransferRequestRoundTrip verifies a read-only keyed reconciliation // request survives the durable registry mailbox codec. func TestLookupTransferRequestRoundTrip(t *testing.T) { diff --git a/oor/actor_messages.go b/oor/actor_messages.go index b0f4280ea..667e745be 100644 --- a/oor/actor_messages.go +++ b/oor/actor_messages.go @@ -120,6 +120,11 @@ type StartTransferRequest struct { // new transfer may be admitted. Existing keyed winners remain readable // after this deadline. Zero leaves admission unbounded. AdmissionDeadlineUnixNanos int64 + + // PrepareOnly persists the deterministic package and input reservations + // without signing or submitting it. A later CommitPreparedEvent + // releases the ordinary OOR flow. + PrepareOnly bool } // MessageType returns the type of this message. @@ -142,6 +147,7 @@ func (m *StartTransferRequest) Encode(w io.Writer) error { IdempotencyKey: m.IdempotencyKey, DispatchRequestData: m.DispatchRequestData, AdmissionDeadlineUnixNanos: m.AdmissionDeadlineUnixNanos, + PrepareOnly: m.PrepareOnly, Recipients: make( []recipientPayload, 0, len(m.Recipients), ), @@ -211,6 +217,7 @@ func (m *StartTransferRequest) Decode(r io.Reader) error { m.IdempotencyKey = payload.IdempotencyKey m.DispatchRequestData = payload.DispatchRequestData m.AdmissionDeadlineUnixNanos = payload.AdmissionDeadlineUnixNanos + m.PrepareOnly = payload.PrepareOnly m.Inputs = make([]TransferInput, 0, len(payload.Inputs)) for i := range payload.Inputs { diff --git a/oor/ark_sign.go b/oor/ark_sign.go index aeb534b69..a91b63414 100644 --- a/oor/ark_sign.go +++ b/oor/ark_sign.go @@ -4,6 +4,7 @@ import ( "bytes" "fmt" + "github.com/btcsuite/btcd/btcec/v2/schnorr" "github.com/btcsuite/btcd/chainhash/v2" "github.com/btcsuite/btcd/psbt/v2" "github.com/btcsuite/btcd/txscript/v2" @@ -189,6 +190,57 @@ func signArkPSBTInput(signer input.Signer, arkPSBT *psbt.Packet, inputIndex int, return err } + // Extra owners authorize the final allocation independently of their + // checkpoint authorization, even when both spend scripts are identical. + ownerLeaf, err := arkscript.DecodeLeafTemplate(in.OwnerLeafPolicy) + if err != nil { + return err + } + for _, external := range in.ExternalArkSignatures { + matchesLeaf := bytes.Equal( + external.WitnessScript, collabLeaf.Script, + ) + if external.PubKey == nil || + external.SigHash != txscript.SigHashDefault || + !matchesLeaf { + return fmt.Errorf("external Ark signature does not " + + "bind owner leaf") + } + participant := false + for _, key := range ownerLeaf.ParticipantKeys() { + if bytes.Equal( + schnorr.SerializePubKey(key), + schnorr.SerializePubKey(external.PubKey), + ) { + + participant = true + break + } + } + if !participant { + return fmt.Errorf("external Ark signer is not an owner") + } + if err := psbtutil.AddTaprootScriptSpendSig( + pInput, external.PubKey, collabLeaf.Script, + external.Signature, external.SigHash, + ); err != nil { + return err + } + sig, err := findTaprootScriptSpendSig( + pInput, external.PubKey, collabLeaf.Script, + ) + if err != nil { + return err + } + if err := verifyTaprootScriptSpendSig( + arkPSBT.UnsignedTx, inputIndex, prevFetcher, + collabLeaf.Script, sig, + ); err != nil { + return fmt.Errorf("verify external Ark signature: %w", + err) + } + } + // Preserve condition witness items for custom spends so later submit // validation can reconstruct the full tapscript witness after the // operator attaches its signature. diff --git a/oor/checkpoint_sign.go b/oor/checkpoint_sign.go index a9f23795b..c996602d1 100644 --- a/oor/checkpoint_sign.go +++ b/oor/checkpoint_sign.go @@ -338,6 +338,40 @@ func verifyTaprootScriptSpendSig(tx *wire.MsgTx, inputIndex int, return nil } +// VerifySingleInputAuthorization verifies a full-payout Schnorr signature on +// a locally reconstructed single-input packet, not peer-supplied prevouts. +func VerifySingleInputAuthorization(pkt *psbt.Packet, owner *btcec.PublicKey, + script []byte, sig ExternalTaprootScriptSignature) error { + + if pkt == nil || pkt.UnsignedTx == nil || + len(pkt.UnsignedTx.TxIn) != 1 || len(pkt.Inputs) != 1 || + pkt.Inputs[0].WitnessUtxo == nil { + return fmt.Errorf("expected one funded input") + } + if owner == nil || sig.PubKey == nil || + !bytes.Equal( + schnorr.SerializePubKey(owner), + schnorr.SerializePubKey(sig.PubKey), + ) || + !bytes.Equal(script, sig.WitnessScript) || + sig.SigHash != txscript.SigHashDefault || + len(sig.Signature) != schnorr.SignatureSize { + return fmt.Errorf("signature does not bind expected owner " + + "and leaf") + } + prev := pkt.Inputs[0].WitnessUtxo + + return verifyTaprootScriptSpendSig( + pkt.UnsignedTx, 0, txscript.NewCannedPrevOutputFetcher( + prev.PkScript, prev.Value, + ), + script, &psbt.TaprootScriptSpendSig{ + XOnlyPubKey: schnorr.SerializePubKey(owner), + Signature: sig.Signature, SigHash: sig.SigHash, + }, + ) +} + // signCheckpointPSBT signs checkpoint input 0 with the client key for the // collaborative VTXO leaf path. func signCheckpointPSBT(signer input.Signer, in *TransferInput, diff --git a/oor/events.go b/oor/events.go index 9a52d44f1..ef9053a87 100644 --- a/oor/events.go +++ b/oor/events.go @@ -44,11 +44,32 @@ type StartTransferEvent struct { // DispatchRequestData is the normalized caller-recipient proof that // must become durable before submit transport is enqueued. DispatchRequestData []byte + + // PrepareOnly stops after deterministically constructing and persisting + // the unsigned package. No signature or operator message is released + // until CommitPreparedEvent arrives. + PrepareOnly bool } // eventSealed marks this as implementing the sealed Event interface. func (e *StartTransferEvent) eventSealed() {} +// CommitPreparedEvent releases a previously prepared transfer into the +// ordinary OOR signing and submission flow. +type CommitPreparedEvent struct{} + +// eventSealed marks this as implementing the sealed Event interface. +func (*CommitPreparedEvent) eventSealed() {} + +// AbortPreparedEvent abandons a prepared transfer before any signature was +// released and returns its reserved inputs to the wallet. +type AbortPreparedEvent struct { + Reason string +} + +// eventSealed marks this as implementing the sealed Event interface. +func (*AbortPreparedEvent) eventSealed() {} + // ArkSignedEvent is emitted after the client signs the Ark PSBT. type ArkSignedEvent struct { // ArkPSBT is the signed Ark PSBT. diff --git a/oor/outgoing_ponr_test.go b/oor/outgoing_ponr_test.go index 2c94a86e1..55921fb6a 100644 --- a/oor/outgoing_ponr_test.go +++ b/oor/outgoing_ponr_test.go @@ -145,10 +145,13 @@ func TestOutgoingFailedBeforePONRFromRecord(t *testing.T) { require.NoError(t, err) require.False(t, got) - // A snapshot from before the record existed ends without the trailing - // record: type, length, and one value byte. + // A pre-v6 failed snapshot carries no failure-proof record. Build that + // format directly rather than assuming which TLV is last today. legacy := record(&Failed{Reason: "old", PrePONR: true}) - legacy.SnapshotData = legacy.SnapshotData[:len(legacy.SnapshotData)-3] + legacy.SnapshotData, err = encodeSnapshotRawForDecodeTest( + 5, 0, OutgoingPhaseFailed, + ) + require.NoError(t, err) decoded, err := decodeOutgoingSnapshot(legacy.SnapshotData) require.NoError(t, err) require.False(t, decoded.FailedPrePONR) diff --git a/oor/outgoing_snapshot.go b/oor/outgoing_snapshot.go index 7526b5fca..ae04af63f 100644 --- a/oor/outgoing_snapshot.go +++ b/oor/outgoing_snapshot.go @@ -1,15 +1,19 @@ package oor import ( + "bytes" "context" "fmt" "time" "github.com/btcsuite/btcd/psbt/v2" "github.com/lightninglabs/wavelength/baselib/protofsm" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" "github.com/lightninglabs/wavelength/lib/tx/psbtutil" ) +const outgoingSnapshotVersion uint8 = 8 + // OutgoingPhase identifies the coarse stage of an outgoing client transfer. // // This is intentionally more stable than Go state type names to keep snapshot @@ -17,6 +21,10 @@ import ( type OutgoingPhase string const ( + // OutgoingPhasePrepared indicates the deterministic package and input + // reservations are durable, but no signature has been released. + OutgoingPhasePrepared OutgoingPhase = "prepared" + // OutgoingPhaseArkSignRequested indicates the submit package has been // built and the client must attach Ark signatures before submit can be // sent. @@ -110,6 +118,52 @@ type OutgoingSnapshot struct { // (which lacks the record) restores to, preserving a fresh retry // window. FirstRejectUnixNanos int64 + + // RecipientOutputs preserves semantic policy metadata needed when a + // prepared or pre-submit transfer resumes after restart. + RecipientOutputs []oortx.RecipientOutput +} + +// OutgoingSnapshotRecipients extracts the canonical Ark recipients from one +// durable outgoing snapshot. Callers use this to recover response metadata for +// an idempotent replay without rebuilding the transfer or selecting new wallet +// inputs. +func OutgoingSnapshotRecipients(raw []byte) ([]ArkRecipientOutput, error) { + snapshot, err := decodeOutgoingSnapshot(raw) + if err != nil { + return nil, fmt.Errorf("decode outgoing snapshot: %w", err) + } + + ark, err := psbtutil.Parse(snapshot.ArkPSBT) + if err != nil { + return nil, fmt.Errorf("parse outgoing Ark PSBT: %w", err) + } + + recipients, err := ExtractArkRecipients(ark) + if err != nil { + return nil, fmt.Errorf("extract outgoing recipients: %w", err) + } + + for i := range recipients { + for j := range snapshot.RecipientOutputs { + output := snapshot.RecipientOutputs[j] + if output.Value != recipients[i].Value || + !bytes.Equal( + output.PkScript, recipients[i].PkScript, + ) { + + continue + } + + recipients[i].VTXOPolicyTemplate = append( + []byte(nil), output.VTXOPolicyTemplate..., + ) + + break + } + } + + return recipients, nil } // NewOutgoingSnapshot exports an outgoing transfer FSM state into a snapshot. @@ -125,17 +179,30 @@ func NewOutgoingSnapshot(sessionID SessionID, } snap := &OutgoingSnapshot{ - // Version 5 adds the FirstRejectUnixNanos record (bounded - // transient submit-reject retry window). Restore stays - // backward-compatible: a pre-v5 snapshot lacks the record and - // decodes FirstRejectUnixNanos to 0 (a fresh window). Version 6 - // adds the FailedPrePONR record, which a pre-v6 snapshot lacks - // and decodes to false (not proven pre-PONR). - Version: 6, + // Version 8 keeps upstream's failure marker at record 27 and + // moves prepared recipients to record 31. Version 7 used record + // 27 for recipients and record 29 for the failure marker. + Version: outgoingSnapshotVersion, SessionID: sessionID, } switch s := state.(type) { + case *Prepared: + snap.Phase = OutgoingPhasePrepared + snap.IdempotencyKey = s.IdempotencyKey + snap.RecipientOutputs = cloneRecipientOutputs( + s.RecipientOutputs, + ) + snap.DispatchRequestData = append( + []byte(nil), s.DispatchRequestData..., + ) + + if err := assignPSBTArtifacts( + snap, s.ArkPSBT, s.CheckpointPSBTs, s.TransferInputs, + ); err != nil { + return nil, err + } + case *AwaitingArkSignatures: // Snapshot deterministic submit artifacts before submit. // This lets resume re-drive Ark signing without rebuilding. @@ -144,6 +211,9 @@ func NewOutgoingSnapshot(sessionID SessionID, snap.DispatchRequestData = append( []byte(nil), s.DispatchRequestData..., ) + snap.RecipientOutputs = cloneRecipientOutputs( + s.RecipientOutputs, + ) ark, err := psbtutil.Serialize(s.ArkPSBT) if err != nil { @@ -179,6 +249,9 @@ func NewOutgoingSnapshot(sessionID SessionID, snap.RetryAfter = s.RetryAfter snap.FailReason = s.RetryReason snap.FirstRejectUnixNanos = s.FirstRejectUnixNanos + snap.RecipientOutputs = cloneRecipientOutputs( + s.RecipientOutputs, + ) if err := assignPSBTArtifacts( snap, s.ArkPSBT, s.CheckpointPSBTs, s.TransferInputs, @@ -295,8 +368,42 @@ func OutgoingStateFromSnapshot(snapshot *OutgoingSnapshot) (State, error) { if snapshot.Version == 0 { return nil, fmt.Errorf("snapshot version must be provided") } + if snapshot.Version > outgoingSnapshotVersion { + return nil, fmt.Errorf("unknown outgoing snapshot version %d", + snapshot.Version) + } switch snapshot.Phase { + case OutgoingPhasePrepared: + ark, cps, err := parseOutgoingPSBTs( + snapshot.ArkPSBT, snapshot.CheckpointPSBTs, + ) + if err != nil { + return nil, err + } + if err := requireSessionIDMatchesArk( + snapshot.SessionID, ark, + ); err != nil { + return nil, err + } + inputs, err := restoreTransferInputs(snapshot) + if err != nil { + return nil, err + } + + return &Prepared{ + ArkPSBT: ark, + CheckpointPSBTs: cps, + TransferInputs: inputs, + RecipientOutputs: cloneRecipientOutputs( + snapshot.RecipientOutputs, + ), + IdempotencyKey: snapshot.IdempotencyKey, + DispatchRequestData: append( + []byte(nil), snapshot.DispatchRequestData..., + ), + }, nil + case OutgoingPhaseArkSignRequested: ark, cps, err := parseOutgoingPSBTs( snapshot.ArkPSBT, snapshot.CheckpointPSBTs, @@ -323,6 +430,9 @@ func OutgoingStateFromSnapshot(snapshot *OutgoingSnapshot) (State, error) { DispatchRequestData: append( []byte(nil), snapshot.DispatchRequestData..., ), + RecipientOutputs: cloneRecipientOutputs( + snapshot.RecipientOutputs, + ), }, nil case OutgoingPhaseSubmitSent: @@ -351,8 +461,11 @@ func OutgoingStateFromSnapshot(snapshot *OutgoingSnapshot) (State, error) { DispatchRequestData: append( []byte(nil), snapshot.DispatchRequestData..., ), - RetryAfter: snapshot.RetryAfter, - RetryReason: snapshot.FailReason, + RetryAfter: snapshot.RetryAfter, + RetryReason: snapshot.FailReason, + RecipientOutputs: cloneRecipientOutputs( + snapshot.RecipientOutputs, + ), FirstRejectUnixNanos: snapshot.FirstRejectUnixNanos, }, nil @@ -438,6 +551,28 @@ func OutgoingStateFromSnapshot(snapshot *OutgoingSnapshot) (State, error) { } } +// cloneRecipientOutputs returns an isolated copy of OOR recipient metadata. +func cloneRecipientOutputs( + outputs []oortx.RecipientOutput) []oortx.RecipientOutput { + + if len(outputs) == 0 { + return nil + } + + cloned := make([]oortx.RecipientOutput, len(outputs)) + for i := range outputs { + cloned[i] = oortx.RecipientOutput{ + PkScript: append([]byte(nil), outputs[i].PkScript...), + Value: outputs[i].Value, + VTXOPolicyTemplate: append( + []byte(nil), outputs[i].VTXOPolicyTemplate..., + ), + } + } + + return cloned +} + // snapshotTransferInputs converts transfer inputs into portable snapshots. func snapshotTransferInputs(inputs []TransferInput) ([]*TransferInputSnapshot, error) { diff --git a/oor/outgoing_snapshot_codec.go b/oor/outgoing_snapshot_codec.go index 595504372..785ffde4c 100644 --- a/oor/outgoing_snapshot_codec.go +++ b/oor/outgoing_snapshot_codec.go @@ -5,8 +5,10 @@ import ( "math" "time" + "github.com/btcsuite/btcd/btcutil/v2" "github.com/btcsuite/btcd/wire/v2" "github.com/lightninglabs/wavelength/baselib/tlvutil" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" "github.com/lightningnetwork/lnd/tlv" ) @@ -38,6 +40,13 @@ const ( // failed before the point of no return (snapshot version 6+). A // pre-v6 snapshot omits it, so it decodes to false. snapshotFailedPrePONRRecordType tlv.Type = 27 + + // snapshotRecipientsRecordType stores semantic recipient metadata for + // prepared and pre-submit sessions in version 8 and later. + snapshotRecipientsRecordType tlv.Type = 31 + + // snapshotPrePONRFailureRecordType is the version-7 failure marker. + snapshotPrePONRFailureRecordType tlv.Type = 29 ) // encodeOutgoingSnapshot serializes outgoing transfer state, including retry @@ -56,7 +65,6 @@ func encodeOutgoingSnapshot(snapshot *OutgoingSnapshot) ([]byte, error) { if err != nil { return nil, err } - inputSnapshots, err := encodeTransferInputSnapshots( snapshot.TransferInputSnapshots, ) @@ -74,7 +82,30 @@ func encodeOutgoingSnapshot(snapshot *OutgoingSnapshot) ([]byte, error) { failedPrePONR = 1 } + recipientPayloads := make( + []recipientPayload, 0, len(snapshot.RecipientOutputs), + ) + for i := range snapshot.RecipientOutputs { + output := snapshot.RecipientOutputs[i] + recipientPayloads = append(recipientPayloads, recipientPayload{ + PkScript: output.PkScript, + ValueSat: int64(output.Value), + VTXOPolicyTemplate: output.VTXOPolicyTemplate, + }) + } + recipients, err := encodeRecipientPayloads(recipientPayloads) + if err != nil { + return nil, err + } + version := uint64(snapshot.Version) + failedRecord := []byte{failedPrePONR} + var legacyFailure uint8 + if snapshot.Version == 7 { + failedRecord = recipients + legacyFailure = failedPrePONR + recipients = nil + } records := []tlv.Record{ tlv.MakePrimitiveRecord(snapshotVersionRecordType, &version), tlv.MakePrimitiveRecord( @@ -105,7 +136,13 @@ func encodeOutgoingSnapshot(snapshot *OutgoingSnapshot) ([]byte, error) { &dispatchRequestData, ), tlv.MakePrimitiveRecord( - snapshotFailedPrePONRRecordType, &failedPrePONR, + snapshotFailedPrePONRRecordType, &failedRecord, + ), + tlv.MakePrimitiveRecord( + snapshotPrePONRFailureRecordType, &legacyFailure, + ), + tlv.MakePrimitiveRecord( + snapshotRecipientsRecordType, &recipients, ), } @@ -133,7 +170,9 @@ func decodeOutgoingSnapshotWithLimits(raw []byte, idempotencyKeyRaw []byte firstRejectNanos uint64 dispatchRequestData []byte - failedPrePONR uint8 + failedRecord []byte + recipientsRaw []byte + prePONRFailure uint8 ) records := []tlv.Record{ @@ -166,7 +205,13 @@ func decodeOutgoingSnapshotWithLimits(raw []byte, &dispatchRequestData, ), tlv.MakePrimitiveRecord( - snapshotFailedPrePONRRecordType, &failedPrePONR, + snapshotFailedPrePONRRecordType, &failedRecord, + ), + tlv.MakePrimitiveRecord( + snapshotPrePONRFailureRecordType, &prePONRFailure, + ), + tlv.MakePrimitiveRecord( + snapshotRecipientsRecordType, &recipientsRaw, ), } @@ -212,6 +257,10 @@ func decodeOutgoingSnapshotWithLimits(raw []byte, if err != nil { return nil, err } + if decodedVersion > outgoingSnapshotVersion { + return nil, fmt.Errorf("unknown outgoing snapshot version %d", + decodedVersion) + } decodedRetryAfter, err := decodeUint64ToDuration( retryAfterNanos, "snapshot retry_after nanos", @@ -226,6 +275,58 @@ func decodeOutgoingSnapshotWithLimits(raw []byte, if err != nil { return nil, err } + if prePONRFailure > 1 { + return nil, fmt.Errorf("snapshot pre-PONR failure must be 0 " + + "or 1") + } + + // The unmerged version-7 format assigned recipient bytes to record + // 27. Select its meaning by version before interpreting failure proof. + failedPrePONR := false + if version == 7 { + if len(recipientsRaw) != 0 { + return nil, fmt.Errorf("version-7 snapshot has " + + "duplicate recipients") + } + recipientsRaw = failedRecord + failedPrePONR = prePONRFailure == 1 + } else if len(failedRecord) != 0 { + if len(failedRecord) != 1 || failedRecord[0] > 1 { + return nil, fmt.Errorf("invalid snapshot pre-PONR " + + "failure marker") + } + failedPrePONR = failedRecord[0] == 1 + } + + var recipientOutputs []oortx.RecipientOutput + if len(recipientsRaw) > 0 { + recipientPayloads, err := decodeRecipientPayloadsWithLimits( + recipientsRaw, limits, + ) + if err != nil { + return nil, err + } + if len(recipientPayloads) > 0 { + recipientOutputs = make( + []oortx.RecipientOutput, 0, + len(recipientPayloads), + ) + for i := range recipientPayloads { + payload := recipientPayloads[i] + recipientOutputs = append( + recipientOutputs, + oortx.RecipientOutput{ + PkScript: payload.PkScript, + Value: btcutil.Amount( + payload.ValueSat, + ), + VTXOPolicyTemplate: payload. + VTXOPolicyTemplate, + }, + ) + } + } + } return &OutgoingSnapshot{ Version: decodedVersion, @@ -239,7 +340,8 @@ func decodeOutgoingSnapshotWithLimits(raw []byte, IdempotencyKey: string(idempotencyKeyRaw), FirstRejectUnixNanos: decodedFirstReject, DispatchRequestData: dispatchRequestData, - FailedPrePONR: failedPrePONR == 1, + FailedPrePONR: failedPrePONR, + RecipientOutputs: recipientOutputs, }, nil } diff --git a/oor/outgoing_snapshot_codec_test.go b/oor/outgoing_snapshot_codec_test.go index a4ff9c3db..d8a36a009 100644 --- a/oor/outgoing_snapshot_codec_test.go +++ b/oor/outgoing_snapshot_codec_test.go @@ -2,12 +2,14 @@ package oor import ( "bytes" + "fmt" "math" "testing" "time" "github.com/btcsuite/btcd/chainhash/v2" "github.com/btcsuite/btcd/wire/v2" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" "github.com/lightningnetwork/lnd/tlv" "github.com/stretchr/testify/require" ) @@ -69,6 +71,17 @@ func TestOutgoingSnapshotTLVRoundTrip(t *testing.T) { DispatchRequestData: []byte{ 1, 2, 3, }, + RecipientOutputs: []oortx.RecipientOutput{{ + PkScript: []byte{ + 0x51, + 0x20, + }, + Value: 321, + VTXOPolicyTemplate: []byte{ + 0x01, 0x02, + }, + }}, + FailedPrePONR: true, } raw, err := encodeOutgoingSnapshot(snapshot) @@ -79,6 +92,65 @@ func TestOutgoingSnapshotTLVRoundTrip(t *testing.T) { require.Equal(t, snapshot, decoded) } +// TestOutgoingSnapshotFailureProofVersions preserves the two historical +// meanings of record 27 without confusing recipient bytes with abort proof. +func TestOutgoingSnapshotFailureProofVersions(t *testing.T) { + t.Parallel() + + recipients, err := encodeRecipientPayloads([]recipientPayload{{ + PkScript: []byte{0x51}, ValueSat: 123, + }}) + require.NoError(t, err) + + for _, version := range []uint64{6, 7, 8} { + t.Run(fmt.Sprintf("version-%d", version), func(t *testing.T) { + t.Parallel() + + session := sessionIDBytes(SessionID(chainhash.Hash{1})) + phase := []byte(OutgoingPhaseFailed) + marker := []byte{1} + var legacyFailure uint8 + var currentRecipients []byte + checkpoints, err := encodeLengthPrefixedBlobList(nil) + require.NoError(t, err) + inputs, err := encodeTransferInputSnapshots(nil) + require.NoError(t, err) + if version == 7 { + marker = recipients + legacyFailure = 1 + } else if version == 8 { + currentRecipients = recipients + } + stream, err := tlv.NewStream( + tlv.MakePrimitiveRecord(1, &version), + tlv.MakePrimitiveRecord(3, &session), + tlv.MakePrimitiveRecord(5, &phase), + tlv.MakePrimitiveRecord(9, &checkpoints), + tlv.MakePrimitiveRecord(11, &inputs), + tlv.MakePrimitiveRecord(27, &marker), + tlv.MakePrimitiveRecord(29, &legacyFailure), + tlv.MakePrimitiveRecord(31, ¤tRecipients), + ) + require.NoError(t, err) + var raw bytes.Buffer + require.NoError(t, stream.Encode(&raw)) + snapshot, err := decodeOutgoingSnapshot(raw.Bytes()) + require.NoError(t, err) + require.True(t, snapshot.FailedPrePONR) + if version >= 7 { + require.Len(t, snapshot.RecipientOutputs, 1) + amount := snapshot.RecipientOutputs[0].Value + require.EqualValues(t, 123, amount) + } + state, err := OutgoingStateFromSnapshot(snapshot) + require.NoError(t, err) + failed, ok := state.(*Failed) + require.True(t, ok) + require.True(t, failed.PrePONR) + }) + } +} + // TestOutgoingSnapshotFirstRejectRoundTrip asserts a version-5 submit-sent // snapshot carrying a non-zero FirstRejectUnixNanos serializes and restores it // so the bounded transient submit-reject retry window survives a restart. @@ -117,7 +189,7 @@ func TestOutgoingSnapshotFirstRejectRoundTrip(t *testing.T) { func TestOutgoingSnapshotV4RestoresZeroFirstReject(t *testing.T) { t.Parallel() - raw, err := encodeSnapshotRawForDecodeTest(4, 0) + raw, err := encodeSnapshotRawForDecodeTest(4, 0, OutgoingPhaseCompleted) require.NoError(t, err) decoded, err := decodeOutgoingSnapshot(raw) @@ -147,7 +219,7 @@ func TestDecodeOutgoingSnapshotRejectsVersionOverflow(t *testing.T) { t.Parallel() raw, err := encodeSnapshotRawForDecodeTest( - uint64(math.MaxUint8)+1, 0, + uint64(math.MaxUint8)+1, 0, OutgoingPhaseCompleted, ) require.NoError(t, err) @@ -155,11 +227,25 @@ func TestDecodeOutgoingSnapshotRejectsVersionOverflow(t *testing.T) { require.ErrorContains(t, err, "snapshot version overflows uint8") } +// TestDecodeOutgoingSnapshotRejectsFutureVersion verifies this binary fails +// closed instead of interpreting fields from an unknown snapshot schema. +func TestDecodeOutgoingSnapshotRejectsFutureVersion(t *testing.T) { + t.Parallel() + + raw, err := encodeSnapshotRawForDecodeTest( + uint64(outgoingSnapshotVersion)+1, 0, OutgoingPhaseCompleted, + ) + require.NoError(t, err) + + _, err = decodeOutgoingSnapshot(raw) + require.ErrorContains(t, err, "unknown outgoing snapshot version") +} + func TestDecodeOutgoingSnapshotRejectsRetryAfterOverflow(t *testing.T) { t.Parallel() raw, err := encodeSnapshotRawForDecodeTest( - 2, uint64(math.MaxInt64)+1, + 2, uint64(math.MaxInt64)+1, OutgoingPhaseCompleted, ) require.NoError(t, err) @@ -169,11 +255,11 @@ func TestDecodeOutgoingSnapshotRejectsRetryAfterOverflow(t *testing.T) { ) } -func encodeSnapshotRawForDecodeTest(version uint64, - retryAfterNanos uint64) ([]byte, error) { +func encodeSnapshotRawForDecodeTest(version uint64, retryAfterNanos uint64, + phase OutgoingPhase) ([]byte, error) { sessionBytes := sessionIDBytes(SessionID(chainhash.Hash{1})) - phaseBytes := []byte(OutgoingPhaseCompleted) + phaseBytes := []byte(phase) arkPSBT := []byte(nil) checkpointPSBTsRaw, err := encodeLengthPrefixedBlobList(nil) diff --git a/oor/prepared_abort_reservation_replay_test.go b/oor/prepared_abort_reservation_replay_test.go new file mode 100644 index 000000000..be16c7844 --- /dev/null +++ b/oor/prepared_abort_reservation_replay_test.go @@ -0,0 +1,337 @@ +package oor + +import ( + "context" + "database/sql" + "fmt" + "testing" + "time" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/btcsuite/btclog/v2" + "github.com/lightninglabs/wavelength/baselib/actor" + "github.com/lightninglabs/wavelength/chainsource" + clientdb "github.com/lightninglabs/wavelength/db" + "github.com/lightninglabs/wavelength/ledger" + "github.com/lightninglabs/wavelength/lib/actormsg" + "github.com/lightninglabs/wavelength/lib/arkscript" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" + "github.com/lightninglabs/wavelength/vtxo" + "github.com/lightninglabs/wavelength/wallet" + "github.com/lightningnetwork/lnd/clock" + fn "github.com/lightningnetwork/lnd/fn/v2" + "github.com/stretchr/testify/require" +) + +// preparedReplayChainSource keeps the real VTXO actors below their expiry +// threshold without introducing unrelated block notifications. +type preparedReplayChainSource struct{} + +// Receive supplies the subscription and initial tip used by recovered actors. +func (*preparedReplayChainSource) Receive(_ context.Context, + msg chainsource.ChainSourceMsg) fn.Result[chainsource.ChainSourceResp] { + + switch msg.(type) { + case *chainsource.SubscribeBlocksRequest: + return fn.Ok[chainsource.ChainSourceResp]( + &chainsource.SubscribeBlocksResponse{}, + ) + + case *chainsource.BestHeightRequest: + return fn.Ok[chainsource.ChainSourceResp]( + &chainsource.BestHeightResponse{ + Height: 100, + }, + ) + + default: + return fn.Err[chainsource.ChainSourceResp]( + fmt.Errorf("unexpected chain request %T", msg), + ) + } +} + +// TestPreparedReserveEpochs keeps legacy unknown epochs out of guarded +// releases while retaining every known reservation by its exact outpoint. +func TestPreparedReserveEpochs(t *testing.T) { + t.Parallel() + + first := wire.OutPoint{Hash: [32]byte{0x83}, Index: 1} + second := wire.OutPoint{Hash: first.Hash, Index: 2} + legacy := wire.OutPoint{Hash: first.Hash, Index: 3} + state := &Prepared{TransferInputs: []TransferInput{ + { + VTXO: &vtxo.Descriptor{ + Outpoint: first, + }, + ReserveEpoch: 41, + }, + { + VTXO: &vtxo.Descriptor{ + Outpoint: second, + }, + ReserveEpoch: 42, + }, + { + VTXO: &vtxo.Descriptor{ + Outpoint: legacy, + }, + }, + { + ReserveEpoch: 43, + }, + }} + require.Equal(t, map[wire.OutPoint]uint64{ + first: 41, second: 42, + }, prePONRReserveEpochs(state)) +} + +// TestPreparedAbortReplayPreservesNewReservation exercises an abort whose +// release succeeds but snapshot commit fails. Replaying the saved Prepared +// state must not release a newer owner's reservation of the same input. +func TestPreparedAbortReplayPreservesNewReservation(t *testing.T) { + t.Parallel() + + for name, event := range map[string]Event{ + "abort": &AbortPreparedEvent{ + Reason: "negotiation canceled", + }, + "fail": &FailEvent{ + Reason: "preparation failed", + }, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + assertPreparedAbortReplay(t, event) + }) + } +} + +// assertPreparedAbortReplay verifies reservation fencing across abort replay. +func assertPreparedAbortReplay(t *testing.T, event Event) { + t.Helper() + + ctx := t.Context() + operator, err := btcec.NewPrivateKey() + require.NoError(t, err) + client, err := btcec.NewPrivateKey() + require.NoError(t, err) + input := newTestTransferInput( + t, client, operator.PubKey(), wire.OutPoint{ + Hash: [32]byte{0x84}, + }, + btcutil.Amount(10_000), + ) + input.VTXO.Status = vtxo.VTXOStatusLive + input.VTXO.RoundID = "prepared-replay-round" + input.VTXO.CreatedHeight = 100 + input.VTXO.BatchExpiry = 10_000 + op := input.VTXO.Outpoint + + sqlDB := clientdb.NewTestDB(t) + roundDB := clientdb.NewTransactionExecutor( + sqlDB.BaseDB, + func(tx *sql.Tx) clientdb.RoundStore { + return sqlDB.WithTx(tx) + }, + btclog.Disabled, + ) + coins := clientdb.NewVTXOPersistenceStore( + roundDB, clock.NewDefaultClock(), + ) + require.NoError(t, coins.SaveVTXO(ctx, input.VTXO)) + system := actor.NewActorSystem() + t.Cleanup(func() { + stopCtx, cancel := context.WithTimeout( + context.Background(), 5*time.Second, + ) + defer cancel() + require.NoError(t, system.Shutdown(stopCtx)) + }) + chainKey := actor.NewServiceKey[ + chainsource.ChainSourceMsg, + chainsource.ChainSourceResp, + ]( + "prepared-replay-chain", + ) + chainRef := chainKey.Spawn( + system, "prepared-replay-chain", &preparedReplayChainSource{}, + ) + manager := vtxo.NewManager(&vtxo.ManagerConfig{ + Store: coins, ActorSystem: system, + ChainSource: chainRef, + Log: fn.Some[btclog.Logger]( + btclog.Disabled, + ), + }) + managerRef := actormsg.VTXOManagerServiceKey().Spawn( + system, actormsg.VTXOManagerServiceKeyName, manager, + ) + require.NoError(t, manager.Start(ctx, managerRef)) + w := wallet.NewArk( + nil, nil, nil, nil, system, fn.None[ledger.Sink](), + btclog.Disabled, + ) + reserve := func() uint64 { + response, err := w.Receive( + ctx, &wallet.SelectAndLockVTXOsRequest{ + TargetAmount: input.VTXO.Amount, + Outpoints: []wire.OutPoint{op}, + }, + ).Unpack() + require.NoError(t, err) + locked, ok := response.(*wallet.SelectAndLockVTXOsResponse) + require.True(t, ok) + require.Len(t, locked.SelectedVTXOs, 1) + + // Selection is detached from the durable + // Spending write. + require.Eventually(t, func() bool { + desc, err := coins.GetVTXO(ctx, op) + + return err == nil && + desc.Status == vtxo.VTXOStatusSpending + }, 5*time.Second, time.Millisecond) + + return locked.SelectedVTXOs[0].ReserveEpoch + } + epochA := reserve() + require.NotZero(t, epochA) + input.ReserveEpoch = epochA + session, _, err := NewPreparedSessionWithIdempotencyKey( + ctx, arkscript.CheckpointPolicy{ + OperatorKey: operator.PubKey(), CSVDelay: 10, + }, []TransferInput{input}, []oortx.RecipientOutput{{ + PkScript: input.VTXO.PkScript, + Value: input.VTXO.Amount, + }}, "", EnvConfig{}, + ) + require.NoError(t, err) + initial, err := session.FSM.CurrentState() + require.NoError(t, err) + prepared, ok := initial.(*Prepared) + require.True(t, ok) + record, err := outgoingRegistryRecord( + session.ID, prepared, + ) + require.NoError(t, err) + base := newFakeRegistryStore() + require.NoError(t, base.UpsertSession(ctx, record)) + store := &failFirstUpsertStore{ + fakeRegistryStore: base, failsLeft: 1, + } + var released []int + var releaseEpochs []uint64 + release := func(ctx context.Context, ops []wire.OutPoint, + epochs map[wire.OutPoint]uint64) error { + + response, err := managerRef.Ask( + ctx, &actormsg.ReleaseSpendRequest{ + Outpoints: ops, ReserveEpochs: epochs, + }, + ).Await(ctx).Unpack() + if err != nil { + return err + } + releasedResp, ok := response.(*actormsg.ReleaseSpendResponse) + require.True(t, ok) + released = append( + released, releasedResp.ReleasedCount, + ) + releaseEpochs = append( + releaseEpochs, epochs[op], + ) + + return nil + } + b := &sessionBehavior{ + cfg: SessionActorConfig{ + RegistryStore: store, + ServerConn: fakeServerConnRef{}, + VTXOStore: coins, + SpendReleaser: release, + }, + actorID: ActorIDForSession(session.ID), + log: btclog.Disabled, + sessionID: session.ID, + direction: clientdb.OORSessionDirectionOutgoing, + fsm: session.FSM, loaded: true, + } + t.Cleanup(b.stopFSM) + ax := fakeExec{tx: oorTx{ + store: &fakeDeliveryStore{}, actorID: b.actorID, + }} + drive := &DriveEventRequest{ + SessionID: session.ID, Event: event, + } + result := b.Receive(ctx, drive, ax) + require.ErrorIs(t, result.Err(), errFilterBroken) + require.True(t, b.commitFailed) + require.Equal(t, []int{1}, released) + desc, err := coins.GetVTXO(ctx, op) + require.NoError(t, err) + require.Equal(t, vtxo.VTXOStatusLive, desc.Status) + saved, err := base.GetSession( + ctx, chainHashOf(session.ID), + ) + require.NoError(t, err) + require.Equal( + t, record.SnapshotData, saved.SnapshotData, + ) + snapshot, err := decodeOutgoingSnapshot( + saved.SnapshotData, + ) + require.NoError(t, err) + restored, err := OutgoingStateFromSnapshot(snapshot) + require.NoError(t, err) + prepared, ok = restored.(*Prepared) + require.True(t, ok) + require.Equal( + t, epochA, + prepared.TransferInputs[0].ReserveEpoch, + ) + + epochB := reserve() + require.Greater(t, epochB, epochA) + result = b.Receive(ctx, drive, ax) + require.True(t, result.IsOk(), result.Err()) + require.False(t, b.commitFailed) + require.Equal( + t, []int{1, 0}, released, + "replayed abort must not release the newer reservation", + ) + require.Equal( + t, []uint64{epochA, epochA}, releaseEpochs, + ) + desc, err = coins.GetVTXO(ctx, op) + require.NoError(t, err) + require.Equal(t, vtxo.VTXOStatusSpending, desc.Status) + _, err = w.Receive(ctx, &wallet.SelectAndLockVTXOsRequest{ + TargetAmount: input.VTXO.Amount, + Outpoints: []wire.OutPoint{op}, + }).Unpack() + require.ErrorIs(t, err, vtxo.ErrVTXOLiquidityLocked) + saved, err = base.GetSession( + ctx, chainHashOf(session.ID), + ) + require.NoError(t, err) + require.Equal( + t, clientdb.OORSessionStatusFailed, + saved.Status, + ) + + // The newer owner's matching epoch must still release + // X. + require.NoError( + t, + release( + ctx, []wire.OutPoint{op}, map[wire.OutPoint]uint64{ + op: epochB, + }, + ), + ) + require.Equal(t, []int{1, 0, 1}, released) +} diff --git a/oor/registry.go b/oor/registry.go index bc1e620e5..ac26f70fe 100644 --- a/oor/registry.go +++ b/oor/registry.go @@ -14,6 +14,7 @@ import ( "github.com/lightninglabs/wavelength/build" clientdb "github.com/lightninglabs/wavelength/db" "github.com/lightninglabs/wavelength/ledger" + "github.com/lightninglabs/wavelength/rpc/oorpb" "github.com/lightninglabs/wavelength/serverconn" "github.com/lightninglabs/wavelength/timeout" "github.com/lightninglabs/wavelength/vtxo" @@ -751,6 +752,32 @@ func (r *oorRegistryBehavior) handleStartTransfer(ctx context.Context, return fn.Err[ActorResp](err) } + prepared, err := store.GetUnfailedSessionByIdempotencyKey( + ctx, req.IdempotencyKey, + ) + switch { + case err == nil: + if prepared.Direction != + clientdb.OORSessionDirectionOutgoing { + return fn.Err[ActorResp]( + fmt.Errorf("%w: key %q belongs to a "+ + "non-outgoing session", + ErrIdempotencyKeyConflict, + req.IdempotencyKey), + ) + } + + delete(r.pendingOutgoingKeys, req.IdempotencyKey) + + return fn.Ok[ActorResp](&StartTransferResponse{ + SessionID: SessionID(prepared.SessionID), + Existing: true, + }) + + case !errors.Is(err, clientdb.ErrOORSessionNotFound): + return fn.Err[ActorResp](err) + } + pendingID, pending := r.pendingOutgoingKeys[req.IdempotencyKey] if pending { if _, active := r.active[pendingID]; active { @@ -781,7 +808,7 @@ func (r *oorRegistryBehavior) handleStartTransfer(ctx context.Context, // daemon's lifetime (one leak per outgoing admission otherwise). session, _, err := newSessionWithDispatchRequest( ctx, req.Policy, req.Inputs, req.Recipients, req.IdempotencyKey, - req.DispatchRequestData, r.envConfig(), + req.DispatchRequestData, req.PrepareOnly, r.envConfig(), ) if err != nil { return fn.Err[ActorResp](err) @@ -926,10 +953,16 @@ func (r *oorRegistryBehavior) validateOutgoingDispatchIdentity( switch { case err == nil && record.Direction == clientdb.OORSessionDirectionOutgoing && - record.Status == clientdb.OORSessionStatusFailed: + record.Status == clientdb.OORSessionStatusFailed && + (record.IdempotencyKey == "" || record.IdempotencyKey == key): replaceFailed = true + case err == nil && record.Direction == + clientdb.OORSessionDirectionOutgoing && + record.IdempotencyKey == key: + return false, nil + case err == nil: return false, fmt.Errorf("%w: session %s", ErrIdempotencyKeyConflict, sessionID) @@ -984,6 +1017,32 @@ func (r *oorRegistryBehavior) handleLookupTransfer(ctx context.Context, return fn.Err[ActorResp](err) } + prepared, err := r.cfg.RegistryStore. + GetUnfailedSessionByIdempotencyKey( + ctx, req.IdempotencyKey, + ) + switch { + case err == nil: + if prepared.Direction != clientdb.OORSessionDirectionOutgoing { + return fn.Err[ActorResp]( + fmt.Errorf("%w: key %q belongs to a "+ + "non-outgoing session", + ErrIdempotencyKeyConflict, + req.IdempotencyKey), + ) + } + + delete(r.pendingOutgoingKeys, req.IdempotencyKey) + + return fn.Ok[ActorResp](&LookupTransferResponse{ + SessionID: SessionID(prepared.SessionID), + Found: true, + }) + + case !errors.Is(err, clientdb.ErrOORSessionNotFound): + return fn.Err[ActorResp](err) + } + sessionID, pending := r.pendingOutgoingKeys[req.IdempotencyKey] if !pending { return fn.Ok[ActorResp](&LookupTransferResponse{}) @@ -1715,6 +1774,18 @@ func (r *oorRegistryBehavior) routeAsk(ctx context.Context, sessionID SessionID, return fn.Err[ActorResp](err) } if child == nil { + if _, ok := msg.(*GetStateRequest); ok { + state, found, err := r.persistedState(ctx, sessionID) + if err != nil { + return fn.Err[ActorResp](err) + } + if found { + return fn.Ok[ActorResp](&GetStateResponse{ + State: state, + }) + } + } + return fn.Err[ActorResp]( fmt.Errorf("unknown session: %s", sessionID), ) @@ -1749,6 +1820,60 @@ func (r *oorRegistryBehavior) routeAsk(ctx context.Context, sessionID SessionID, return fn.Ok[ActorResp](&DriveEventResponse{}) } +// persistedState reconstructs a reaped session's state from its durable +// snapshot. Terminal actors are deliberately short-lived, but status readers +// must remain race-free after the child exits. +func (r *oorRegistryBehavior) persistedState(ctx context.Context, + sessionID SessionID) (SessionState, bool, error) { + + record, err := r.cfg.RegistryStore.GetSession( + ctx, chainHashOf(sessionID), + ) + switch { + case errors.Is(err, clientdb.ErrOORSessionNotFound): + return nil, false, nil + + case err != nil: + return nil, false, err + } + + if err := oorpb.ValidateFlowVersion(record.FlowVersion); err != nil { + return nil, false, err + } + if len(record.SnapshotData) == 0 { + return nil, false, fmt.Errorf("session %s has no snapshot", + sessionID) + } + + switch record.Direction { + case clientdb.OORSessionDirectionOutgoing: + snapshot, err := decodeOutgoingSnapshot(record.SnapshotData) + if err != nil { + return nil, false, err + } + + state, err := OutgoingStateFromSnapshot(snapshot) + + return state, true, err + + case clientdb.OORSessionDirectionIncoming: + snapshot, err := decodeIncomingSnapshotWithLimits( + record.SnapshotData, r.cfg.Limits, + ) + if err != nil { + return nil, false, err + } + + state, err := IncomingStateFromSnapshot(snapshot) + + return state, true, err + + default: + return nil, false, fmt.Errorf("unknown session direction: %d", + record.Direction) + } +} + // sessionIsTerminal reports whether the durable row for a session exists and // has reached a terminal status. A missing row reports (false, nil): it is // genuinely unknown, not terminal. Used by handleDriveEvent to distinguish a diff --git a/oor/registry_failed_key_test.go b/oor/registry_failed_key_test.go new file mode 100644 index 000000000..bca6b1063 --- /dev/null +++ b/oor/registry_failed_key_test.go @@ -0,0 +1,102 @@ +package oor + +import ( + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/wire/v2" + clientdb "github.com/lightninglabs/wavelength/db" + "github.com/lightninglabs/wavelength/lib/arkscript" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" + "github.com/stretchr/testify/require" +) + +// TestOORRegistryFailedSessionRetainsKey verifies an attemptless failed +// session can be rebuilt only by its original keyed caller. +func TestOORRegistryFailedSessionRetainsKey(t *testing.T) { + t.Parallel() + + operator, err := btcec.NewPrivateKey() + require.NoError(t, err) + client, err := btcec.NewPrivateKey() + require.NoError(t, err) + input := newTestTransferInput( + t, client, operator.PubKey(), wire.OutPoint{ + Hash: [32]byte{0x84}, + }, + btcutil.Amount(10_000), + ) + req := &StartTransferRequest{ + Policy: arkscript.CheckpointPolicy{ + OperatorKey: operator.PubKey(), CSVDelay: 10, + }, + Inputs: []TransferInput{ + input, + }, + Recipients: []oortx.RecipientOutput{{ + PkScript: newTestTaprootPkScript(t, client.PubKey()), + Value: input.VTXO.Amount, + }}, + IdempotencyKey: "original-caller", + } + session, _, err := NewSessionWithIdempotencyKey( + t.Context(), req.Policy, req.Inputs, req.Recipients, + req.IdempotencyKey, EnvConfig{}, + ) + require.NoError(t, err) + t.Cleanup(session.FSM.Stop) + outgoing := clientdb.OORSessionDirectionOutgoing + + for _, key := range []string{"different-caller", "original-caller"} { + t.Run(key, func(t *testing.T) { + store := newFakeRegistryStore() + record := clientdb.OORSessionRegistryRecord{ + SessionID: chainHashOf(session.ID), + ActorID: ActorIDForSession(session.ID), + Direction: outgoing, + Phase: "failed", + IdempotencyKey: "original-caller", + Status: clientdb.OORSessionStatusFailed, + } + require.NoError( + t, + store.UpsertSession( + t.Context(), record, + ), + ) + b, rec := newTestRegistryBehavior(store) + b.active[session.ID] = &OORSessionActor{stop: func() { + rec.mu.Lock() + defer rec.mu.Unlock() + + rec.stops++ + }} + request := *req + request.IdempotencyKey = key + result := b.handleStartTransfer(t.Context(), &request) + if key != req.IdempotencyKey { + require.ErrorIs( + t, result.Err(), + ErrIdempotencyKeyConflict, + ) + require.Zero(t, rec.stopCount()) + require.Zero(t, rec.spawns) + require.Empty(t, rec.recorded()) + + return + } + + require.True(t, result.IsOk(), result.Err()) + value := result.UnwrapOr(nil) + response, ok := value.(*StartTransferResponse) + require.True(t, ok) + require.False(t, response.Existing) + require.Equal(t, session.ID, response.SessionID) + require.Equal(t, 1, rec.stopCount()) + require.Equal(t, 1, rec.spawns) + require.Len(t, rec.recorded(), 1) + require.Equal(t, session.ID, b.pendingOutgoingKeys[key]) + }) + } +} diff --git a/oor/registry_test.go b/oor/registry_test.go index 989269b4a..815f319b9 100644 --- a/oor/registry_test.go +++ b/oor/registry_test.go @@ -229,6 +229,34 @@ func upsertRegistryRowContext(ctx context.Context, t *testing.T, require.NoError(t, store.UpsertSession(ctx, rec)) } +// TestOORRegistryGetStateReadsReapedSnapshot verifies status probes remain +// valid after a terminal child has been removed from the active set. +func TestOORRegistryGetStateReadsReapedSnapshot(t *testing.T) { + t.Parallel() + + ctx := t.Context() + store := newFakeRegistryStore() + id := oorSessionID(0x7a) + record, err := outgoingRegistryRecord(id, &Completed{ + IdempotencyKey: "ark-channel:test", + }) + require.NoError(t, err) + require.NoError(t, store.UpsertSession(ctx, record)) + + registry, recorder := newTestRegistryBehavior(store) + result := registry.routeAsk(ctx, id, &GetStateRequest{ + SessionID: id, + }) + require.True(t, result.IsOk(), result.Err()) + require.Zero(t, recorder.spawns) + + response, ok := result.UnwrapOr(nil).(*GetStateResponse) + require.True(t, ok) + completed, ok := response.State.(*Completed) + require.True(t, ok) + require.Equal(t, "ark-channel:test", completed.IdempotencyKey) +} + // TestOORRegistryRestoreNonTerminal verifies restore spawns one child per // non-terminal row and skips terminal ones. func TestOORRegistryRestoreNonTerminal(t *testing.T) { @@ -305,6 +333,52 @@ func TestOORRegistryStartTransferDedup(t *testing.T) { require.Equal(t, 0, rec.spawns) } +// TestOORRegistryPreparedTransferDedupAfterRestart verifies that a prepared +// session remains the keyed winner even though it has not emitted transport +// work and therefore has no immutable dispatch-attempt row yet. +func TestOORRegistryPreparedTransferDedupAfterRestart(t *testing.T) { + t.Parallel() + + ctx := t.Context() + store := newFakeRegistryStore() + existing := oorSessionID(0x11) + record := clientdb.OORSessionRegistryRecord{ + SessionID: chainHashOf(existing), + ActorID: ActorIDForSession(existing), + Direction: clientdb.OORSessionDirectionOutgoing, + Phase: "prepared", + IdempotencyKey: "prepared-key", + Status: clientdb.OORSessionStatusPending, + SnapshotData: []byte{ + 0x01, + }, + } + require.NoError(t, store.UpsertSession(ctx, record)) + + // A fresh behavior has no process-local pending key map. Both the retry + // and explicit lookup must still find the durable prepared winner. + b, rec := newTestRegistryBehavior(store) + started := b.handleStartTransfer(ctx, &StartTransferRequest{ + IdempotencyKey: record.IdempotencyKey, + }) + require.True(t, started.IsOk(), started.Err()) + startResp, ok := started.UnwrapOr(nil).(*StartTransferResponse) + require.True(t, ok) + require.True(t, startResp.Existing) + require.Equal(t, existing, startResp.SessionID) + require.Zero(t, rec.spawns) + + lookedUp := b.handleLookupTransfer(ctx, &LookupTransferRequest{ + IdempotencyKey: record.IdempotencyKey, + }) + require.True(t, lookedUp.IsOk(), lookedUp.Err()) + lookupResp, ok := lookedUp.UnwrapOr(nil).(*LookupTransferResponse) + require.True(t, ok) + require.True(t, lookupResp.Found) + require.False(t, lookupResp.Pending) + require.Equal(t, existing, lookupResp.SessionID) +} + // TestOORRegistryAdmissionDeadline verifies a new transfer cannot cross its // caller-owned admission deadline, while an existing key winner remains // readable after the same cutoff. diff --git a/oor/resume.go b/oor/resume.go index ab23a9bfc..b70c42ff9 100644 --- a/oor/resume.go +++ b/oor/resume.go @@ -132,6 +132,11 @@ func OutboxForState(state State) ([]OutboxEvent, error) { } switch s := state.(type) { + case *Prepared: + // Preparation deliberately has no implied side effect. Only an + // explicit CommitPreparedEvent may release signatures. + return nil, nil + case *AwaitingArkSignatures: return []OutboxEvent{ &RequestArkSignatures{ diff --git a/oor/session.go b/oor/session.go index 9a2966ba0..d70df6fff 100644 --- a/oor/session.go +++ b/oor/session.go @@ -50,6 +50,31 @@ func NewSessionWithIdempotencyKey(ctx context.Context, outputs []oortx.RecipientOutput, idempotencyKey string, envCfg EnvConfig) (*Session, []OutboxEvent, error) { + return newSessionWithIdempotencyKey( + ctx, policy, inputs, outputs, idempotencyKey, false, envCfg, + ) +} + +// NewPreparedSessionWithIdempotencyKey creates a durable OOR session whose +// deterministic package is built but whose signatures and transport remain +// gated on CommitPreparedEvent. +func NewPreparedSessionWithIdempotencyKey(ctx context.Context, + policy arkscript.CheckpointPolicy, inputs []TransferInput, + outputs []oortx.RecipientOutput, idempotencyKey string, + envCfg EnvConfig) (*Session, []OutboxEvent, error) { + + return newSessionWithIdempotencyKey( + ctx, policy, inputs, outputs, idempotencyKey, true, envCfg, + ) +} + +// newSessionWithIdempotencyKey constructs either an immediately committed or +// explicitly prepared outgoing OOR session. +func newSessionWithIdempotencyKey(ctx context.Context, + policy arkscript.CheckpointPolicy, inputs []TransferInput, + outputs []oortx.RecipientOutput, idempotencyKey string, + prepareOnly bool, envCfg EnvConfig) (*Session, []OutboxEvent, error) { + var dispatchRequestData []byte if idempotencyKey != "" { var err error @@ -61,15 +86,15 @@ func NewSessionWithIdempotencyKey(ctx context.Context, return newSessionWithDispatchRequest( ctx, policy, inputs, outputs, idempotencyKey, - dispatchRequestData, envCfg, + dispatchRequestData, prepareOnly, envCfg, ) } func newSessionWithDispatchRequest(ctx context.Context, policy arkscript.CheckpointPolicy, inputs []TransferInput, outputs []oortx.RecipientOutput, idempotencyKey string, - dispatchRequestData []byte, envCfg EnvConfig) (*Session, []OutboxEvent, - error) { + dispatchRequestData []byte, prepareOnly bool, envCfg EnvConfig) ( + *Session, []OutboxEvent, error) { logger(ctx).DebugS(ctx, "Creating new OOR session", slog.Int("num_inputs", len(inputs)), @@ -101,6 +126,7 @@ func newSessionWithDispatchRequest(ctx context.Context, DispatchRequestData: append( []byte(nil), dispatchRequestData..., ), + PrepareOnly: prepareOnly, }) result := fut.Await(ctx) if result.IsErr() { @@ -114,6 +140,9 @@ func newSessionWithDispatchRequest(ctx context.Context, var arkPSBT *psbt.Packet switch s := currentState.(type) { + case *Prepared: + arkPSBT = s.ArkPSBT + case *AwaitingArkSignatures: arkPSBT = s.ArkPSBT diff --git a/oor/session_actor.go b/oor/session_actor.go index cdb401791..18d9ce807 100644 --- a/oor/session_actor.go +++ b/oor/session_actor.go @@ -372,7 +372,7 @@ type sessionBehavior struct { // commitFailed reports that the previous turn advanced b.fsm in memory // but its Commit rolled back (a non-lease-loss error), leaving the // in-memory FSM observably ahead of the last durably-committed - // snapshot. When set, the next driving turn re-runs restore() before + // snapshot. When set, the next turn re-runs restore() before // dispatch so the redelivered event re-applies against the // last-committed state instead of being discarded as already-applied // against an uncommitted advance. A lease-loss commit failure does not @@ -402,26 +402,20 @@ func (b *sessionBehavior) logger(ctx context.Context) btclog.Logger { func (b *sessionBehavior) Receive(ctx context.Context, msg OORDurableMsg, ax actor.Exec[oorTx]) fn.Result[ActorResp] { - switch msg.(type) { - case *actor.RestartMessage: + if _, ok := msg.(*actor.RestartMessage); ok { + // Restore already ran at construction; the restart message // carries no state to persist, so the framework consumes it via // the non-transactional ack path. return fn.Ok[ActorResp](&DriveEventResponse{}) - - case *GetStateRequest: - return b.handleGetState() } // If the previous turn's Commit rolled back after advancing b.fsm in // memory, the in-memory FSM is ahead of the last durably-committed - // snapshot. Rebuild it from the registry row before dispatch so the - // redelivered driving event re-applies the full transition (re-staging - // materialization and transport) against the last-committed state, - // rather than being no-op'd by an FSM that already advanced on an - // uncommitted turn. restore() rebuilds b.fsm from the durable row; on - // success the flag is cleared and the redelivered event drives the - // rebuilt FSM. + // snapshot. Rebuild it from the registry row before querying or driving + // the FSM so a read cannot authorize cleanup from an uncommitted abort. + // A redelivered event then re-applies the transition and its effects + // against the last committed state instead of skipping them. if b.commitFailed { b. logger(ctx). @@ -467,6 +461,10 @@ func (b *sessionBehavior) Receive(ctx context.Context, msg OORDurableMsg, b.commitFailed = false } + if _, ok := msg.(*GetStateRequest); ok { + return b.handleGetState() + } + // Reset the per-turn accumulators and drain the FSM. dispatch performs // every inline side effect, collects cross-actor messages, and stages // extra commit work, but never commits. @@ -1150,7 +1148,6 @@ func (b *sessionBehavior) commitAck(ctx context.Context, if err := b.cfg.RegistryStore.UpsertSession( txCtx, record, ); err != nil { - // On Postgres the resolveKeyDedup SELECT above can miss // a concurrent same-key winner (the racing children do // not serialize on oor_session_registry the way diff --git a/oor/session_actor_handlers.go b/oor/session_actor_handlers.go index 20234e724..bb8784195 100644 --- a/oor/session_actor_handlers.go +++ b/oor/session_actor_handlers.go @@ -90,7 +90,7 @@ func (b *sessionBehavior) handleStartTransfer(ctx context.Context, session, outbox, err := newSessionWithDispatchRequest( ctx, req.Policy, req.Inputs, req.Recipients, req.IdempotencyKey, - req.DispatchRequestData, b.envConfig(), + req.DispatchRequestData, req.PrepareOnly, b.envConfig(), ) if err != nil { return fn.Err[ActorResp](err) diff --git a/oor/session_actor_prepared_query_test.go b/oor/session_actor_prepared_query_test.go new file mode 100644 index 000000000..ff9503e00 --- /dev/null +++ b/oor/session_actor_prepared_query_test.go @@ -0,0 +1,102 @@ +package oor + +import ( + "context" + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/btcsuite/btclog/v2" + clientdb "github.com/lightninglabs/wavelength/db" + "github.com/lightninglabs/wavelength/lib/arkscript" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" + "github.com/stretchr/testify/require" +) + +// TestPreparedAbortQueryReloadsCommittedState prevents an uncommitted abort +// from authorizing channel cleanup before the durable OOR gate is closed. +func TestPreparedAbortQueryReloadsCommittedState(t *testing.T) { + t.Parallel() + + ctx := t.Context() + operator, err := btcec.NewPrivateKey() + require.NoError(t, err) + client, err := btcec.NewPrivateKey() + require.NoError(t, err) + input := newTestTransferInput( + t, client, operator.PubKey(), wire.OutPoint{ + Hash: [32]byte{0x83}, + }, + btcutil.Amount(10_000), + ) + session, _, err := NewPreparedSessionWithIdempotencyKey( + ctx, arkscript.CheckpointPolicy{ + OperatorKey: operator.PubKey(), CSVDelay: 10, + }, []TransferInput{input}, []oortx.RecipientOutput{{ + PkScript: newTestTaprootPkScript(t, client.PubKey()), + Value: input.VTXO.Amount, + }}, "", EnvConfig{}, + ) + require.NoError(t, err) + initial, err := session.FSM.CurrentState() + require.NoError(t, err) + prepared, ok := initial.(*Prepared) + require.True(t, ok) + record, err := outgoingRegistryRecord(session.ID, prepared) + require.NoError(t, err) + base := newFakeRegistryStore() + require.NoError(t, base.UpsertSession(ctx, record)) + store := &failFirstUpsertStore{ + fakeRegistryStore: base, failsLeft: 1, + } + releases := 0 + b := &sessionBehavior{ + cfg: SessionActorConfig{ + RegistryStore: store, ServerConn: fakeServerConnRef{}, + SpendReleaser: func(context.Context, []wire.OutPoint, + map[wire.OutPoint]uint64) error { + + releases++ + + return nil + }, + }, + actorID: ActorIDForSession(session.ID), log: btclog.Disabled, + sessionID: session.ID, direction: clientdb.OORSessionDirectionOutgoing, + fsm: session.FSM, loaded: true, + } + t.Cleanup(b.stopFSM) + ax := fakeExec{tx: oorTx{ + store: &fakeDeliveryStore{}, actorID: b.actorID, + }} + result := b.Receive(ctx, &DriveEventRequest{ + SessionID: session.ID, + Event: &AbortPreparedEvent{Reason: "negotiation canceled"}, + }, ax) + require.True(t, result.IsErr()) + require.ErrorIs(t, result.Err(), errFilterBroken) + require.Equal(t, 1, releases) + require.True(t, b.commitFailed) + uncommitted, err := b.fsm.CurrentState() + require.NoError(t, err) + require.IsType(t, &Failed{}, uncommitted) + saved, err := base.GetSession(ctx, chainHashOf(session.ID)) + require.NoError(t, err) + require.Equal(t, record.Phase, saved.Phase) + require.False(t, saved.Status.IsTerminal()) + + result = b.Receive(ctx, &GetStateRequest{SessionID: session.ID}, ax) + require.True(t, result.IsOk(), result.Err()) + response, ok := result.UnwrapOr(nil).(*GetStateResponse) + require.True(t, ok) + require.IsType( + t, &Prepared{}, response.State, "status must describe the "+ + "committed gate, not the rolled-back abort", + ) + require.False(t, b.commitFailed) + require.Equal(t, 1, releases, "a read must not replay side effects") + saved, err = base.GetSession(ctx, chainHashOf(session.ID)) + require.NoError(t, err) + require.Equal(t, record.Phase, saved.Phase) +} diff --git a/oor/session_actor_test.go b/oor/session_actor_test.go index a3b76e29a..eb155f5b6 100644 --- a/oor/session_actor_test.go +++ b/oor/session_actor_test.go @@ -105,6 +105,26 @@ func (s *fakeRegistryStore) GetSession(_ context.Context, return &record, nil } +func (s *fakeRegistryStore) GetUnfailedSessionByIdempotencyKey( + _ context.Context, key string) (*clientdb.OORSessionRegistryRecord, + error) { + + s.mu.Lock() + defer s.mu.Unlock() + + for _, record := range s.rows { + if record.IdempotencyKey == key && + record.Status != clientdb.OORSessionStatusFailed { + + recordCopy := record + + return &recordCopy, nil + } + } + + return nil, clientdb.ErrOORSessionNotFound +} + func (s *fakeRegistryStore) GetDispatchAttemptByIdempotencyKey( _ context.Context, key string) (*clientdb.OORDispatchAttemptRecord, error) { diff --git a/oor/session_registry_bridge.go b/oor/session_registry_bridge.go index 22e03b3ce..096e99b1f 100644 --- a/oor/session_registry_bridge.go +++ b/oor/session_registry_bridge.go @@ -29,6 +29,11 @@ type SessionRegistryStore interface { error, ) + // GetUnfailedSessionByIdempotencyKey loads an outgoing session before + // its immutable dispatch-attempt row exists. Failed rows release keys. + GetUnfailedSessionByIdempotencyKey(ctx context.Context, + key string) (*clientdb.OORSessionRegistryRecord, error) + // GetDispatchAttemptByIdempotencyKey loads the immutable outgoing // dispatch carrying the given caller key. GetDispatchAttemptByIdempotencyKey(ctx context.Context, diff --git a/oor/session_test.go b/oor/session_test.go index 0a4753a3e..e35f2b5ab 100644 --- a/oor/session_test.go +++ b/oor/session_test.go @@ -170,6 +170,100 @@ func TestSessionHappyPath(t *testing.T) { require.True(t, ok) } +// TestPreparedSessionCommitAndAbort verifies a prepared transfer has no +// signing side effects until commit and releases its inputs when aborted. +func TestPreparedSessionCommitAndAbort(t *testing.T) { + t.Parallel() + + operatorKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + clientKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + + policy := arkscript.CheckpointPolicy{ + OperatorKey: operatorKey.PubKey(), + CSVDelay: 10, + } + input := newTestTransferInput( + t, clientKey, operatorKey.PubKey(), wire.OutPoint{ + Hash: [32]byte{0x02}, + Index: 1, + }, btcutil.Amount(10_000), + ) + outputs := []oortx.RecipientOutput{{ + PkScript: newTestTaprootPkScript(t, clientKey.PubKey()), + Value: btcutil.Amount(10_000), + }} + + prepared, outbox, err := NewPreparedSessionWithIdempotencyKey( + t.Context(), policy, []TransferInput{input}, outputs, + "channel-intent", EnvConfig{}, + ) + require.NoError(t, err) + require.Empty(t, outbox) + require.NotEqual(t, SessionID{}, prepared.ID) + + state, err := prepared.FSM.CurrentState() + require.NoError(t, err) + require.IsType(t, &Prepared{}, state) + outgoingState, ok := state.(State) + require.True(t, ok) + resumeOutbox, err := OutboxForState(outgoingState) + require.NoError(t, err) + require.Empty(t, resumeOutbox) + + result := prepared.FSM.AskEvent( + t.Context(), &CommitPreparedEvent{}, + ).Await(t.Context()) + require.False(t, result.IsErr()) + require.Len(t, result.UnwrapOr(nil), 1) + require.IsType(t, &RequestArkSignatures{}, result.UnwrapOr(nil)[0]) + + committedState, err := prepared.FSM.CurrentState() + require.NoError(t, err) + require.IsType(t, &AwaitingArkSignatures{}, committedState) + + aborted, _, err := NewPreparedSessionWithIdempotencyKey( + t.Context(), policy, []TransferInput{input}, outputs, + "aborted-channel-intent", EnvConfig{}, + ) + require.NoError(t, err) + + result = aborted.FSM.AskEvent(t.Context(), &AbortPreparedEvent{ + Reason: "channel negotiation failed", + }).Await(t.Context()) + require.False(t, result.IsErr()) + require.Len(t, result.UnwrapOr(nil), 1) + release, ok := result.UnwrapOr(nil)[0].(*ReleaseInputsRequest) + require.True(t, ok) + require.Equal( + t, []wire.OutPoint{input.VTXO.Outpoint}, release.Outpoints, + ) + + abortedState, err := aborted.FSM.CurrentState() + require.NoError(t, err) + failure, ok := abortedState.(*Failed) + require.True(t, ok) + require.Equal(t, "channel negotiation failed", failure.Reason) + require.True(t, failure.PrePONR) +} + +// TestFailedStateDerivesPrePONRFromPhase verifies malformed input metadata +// cannot turn a pre-signature failure into post-PONR evidence. +func TestFailedStateDerivesPrePONRFromPhase(t *testing.T) { + t.Parallel() + + failure := failedState("missing input", &Prepared{ + TransferInputs: []TransferInput{{}}, + }) + require.True(t, failure.PrePONR) + + failure = failedState( + "operator co-signed", &AwaitingCheckpointSignatures{}, + ) + require.False(t, failure.PrePONR) +} + // TestSessionMultiInputHappyPath verifies the outgoing transfer FSM with // multiple VTXO inputs. This exercises the multi-input Ark signing path // where BIP-341 sighash commits to ALL prevouts, requiring a diff --git a/oor/states.go b/oor/states.go index 52f1d74b7..e055d0b2a 100644 --- a/oor/states.go +++ b/oor/states.go @@ -36,6 +36,47 @@ func (s *Idle) IsTerminal() bool { // stateSealed marks Idle as implementing the sealed State interface. func (s *Idle) stateSealed() {} +// Prepared holds a deterministic OOR package without releasing signatures or +// transport. A channel coordinator can safely use its output outpoint while +// negotiating the lnd channel, then explicitly commit or abort the transfer. +type Prepared struct { + // ArkPSBT is the unsigned canonical Ark transaction whose txid is the + // stable session identifier. + ArkPSBT *psbt.Packet + + // CheckpointPSBTs are the unsigned checkpoint transactions for the + // selected source VTXOs. + CheckpointPSBTs []*psbt.Packet + + // TransferInputs carry the signing context retained until commit or + // abort. + TransferInputs []TransferInput + + // RecipientOutputs preserve semantic output metadata for submit. + RecipientOutputs []oortx.RecipientOutput + + // IdempotencyKey identifies the caller intent that prepared the + // transfer. + IdempotencyKey string + + // DispatchRequestData is the normalized caller-recipient proof retained + // until the prepared transfer is committed. + DispatchRequestData []byte +} + +// String returns the state name. +func (*Prepared) String() string { + return "Prepared" +} + +// IsTerminal reports that a prepared transfer remains resumable. +func (*Prepared) IsTerminal() bool { + return false +} + +// stateSealed marks Prepared as implementing State. +func (*Prepared) stateSealed() {} + // AwaitingArkSignatures indicates the submit package has been built and the // client must attach Ark signatures before submit can be sent. type AwaitingArkSignatures struct { diff --git a/oor/transfer_input_snapshot.go b/oor/transfer_input_snapshot.go index e242a4d8d..675182330 100644 --- a/oor/transfer_input_snapshot.go +++ b/oor/transfer_input_snapshot.go @@ -83,7 +83,8 @@ type TransferInputSnapshot struct { // ExternalSignatures are pre-collected tapscript signatures needed to // resume custom OOR spends after restart. - ExternalSignatures []ExternalTaprootScriptSignature + ExternalSignatures []ExternalTaprootScriptSignature + ExternalArkSignatures []ExternalTaprootScriptSignature } // ToSnapshot converts the transfer input into a portable snapshot. @@ -136,6 +137,9 @@ func (i *TransferInput) ToSnapshot() (*TransferInputSnapshot, error) { snap.RequiredLockTime = i.CustomSpend.RequiredLockTime } snap.ExternalSignatures = cloneExternalSignatures(i.ExternalSignatures) + snap.ExternalArkSignatures = cloneExternalSignatures( + i.ExternalArkSignatures, + ) return snap, nil } @@ -242,6 +246,9 @@ func TransferInputFromSnapshot(snap *TransferInputSnapshot) (TransferInput, result.ExternalSignatures = cloneExternalSignatures( snap.ExternalSignatures, ) + result.ExternalArkSignatures = cloneExternalSignatures( + snap.ExternalArkSignatures, + ) // For custom spend paths, use the stored PkScript instead of // deriving from keys. diff --git a/oor/transfer_input_snapshot_test.go b/oor/transfer_input_snapshot_test.go index 9be4acb05..c3d87d415 100644 --- a/oor/transfer_input_snapshot_test.go +++ b/oor/transfer_input_snapshot_test.go @@ -120,10 +120,20 @@ func TestTransferInputSnapshotRoundTrip(t *testing.T) { SigHash: txscript.SigHashDefault, }, } + in.ExternalArkSignatures = cloneExternalSignatures( + in.ExternalSignatures, + ) snap, err := in.ToSnapshot() require.NoError(t, err) require.NotNil(t, snap) + raw, err := encodeTransferInputSnapshot(snap) + require.NoError(t, err) + snap, err = decodeTransferInputSnapshot(raw) + require.NoError(t, err) + requireExternalSignatureEqual( + t, in.ExternalArkSignatures[0], snap.ExternalArkSignatures[0], + ) require.Equal(t, in.VTXO.Outpoint, snap.Outpoint) require.Equal(t, int64(in.VTXO.Amount), snap.AmountSat) require.Equal( @@ -191,6 +201,10 @@ func TestTransferInputSnapshotRoundTrip(t *testing.T) { requireExternalSignatureEqual( t, in.ExternalSignatures[0], rebuilt.ExternalSignatures[0], ) + requireExternalSignatureEqual( + t, in.ExternalArkSignatures[0], + rebuilt.ExternalArkSignatures[0], + ) } // TestCloneExternalSignaturesDeepCopiesMutableBytes verifies persisted custom diff --git a/oor/transfer_inputs.go b/oor/transfer_inputs.go index 85952f31f..9cd8aa799 100644 --- a/oor/transfer_inputs.go +++ b/oor/transfer_inputs.go @@ -64,6 +64,10 @@ type TransferInput struct { // ExternalSignatures are tapscript signatures produced by additional // custom-spend participants before the local daemon adds its signature. ExternalSignatures []ExternalTaprootScriptSignature + + // ExternalArkSignatures authorize the final allocation, not the + // checkpoint. They must remain distinct even if both leaves match. + ExternalArkSignatures []ExternalTaprootScriptSignature } // ExternalTaprootScriptSignature carries one externally produced tapscript diff --git a/oor/transitions.go b/oor/transitions.go index 4c79664b5..acfe11fcc 100644 --- a/oor/transitions.go +++ b/oor/transitions.go @@ -84,7 +84,7 @@ func failedState(reason string, current State) *Failed { // reported as safe. func failsBeforePONR(state State) bool { switch state.(type) { - case *Idle, *AwaitingArkSignatures, *AwaitingSubmitAccepted: + case *Idle, *Prepared, *AwaitingArkSignatures, *AwaitingSubmitAccepted: return true default: @@ -94,6 +94,9 @@ func failsBeforePONR(state State) bool { func stateIdempotencyKey(state State) string { switch s := state.(type) { + case *Prepared: + return s.IdempotencyKey + case *AwaitingArkSignatures: return s.IdempotencyKey @@ -201,10 +204,21 @@ func (s *Idle) ProcessEvent(ctx context.Context, event Event, } } - signReq := &RequestArkSignatures{ - ArkPSBT: ark, - CheckpointPSBTs: checkpoints, - TransferInputs: evt.VTXOInputs, + if evt.PrepareOnly { + return &StateTransition{ + NextState: &Prepared{ + ArkPSBT: ark, + CheckpointPSBTs: checkpoints, + TransferInputs: evt.VTXOInputs, + RecipientOutputs: canonicalRecipients, + IdempotencyKey: evt.IdempotencyKey, + DispatchRequestData: append( + []byte(nil), + dispatchRequestData..., + ), + }, + NewEvents: fn.None[EmittedEvent](), + }, nil } return &StateTransition{ @@ -220,7 +234,11 @@ func (s *Idle) ProcessEvent(ctx context.Context, event Event, }, NewEvents: fn.Some(EmittedEvent{ Outbox: []OutboxEvent{ - signReq, + &RequestArkSignatures{ + ArkPSBT: ark, + CheckpointPSBTs: checkpoints, + TransferInputs: evt.VTXOInputs, + }, }, }), }, nil @@ -236,6 +254,69 @@ func (s *Idle) ProcessEvent(ctx context.Context, event Event, } } +// ProcessEvent handles events for Prepared. +func (s *Prepared) ProcessEvent(_ context.Context, event Event, + _ *Environment) (*StateTransition, error) { + + switch event := event.(type) { + case *CommitPreparedEvent: + request := &RequestArkSignatures{ + ArkPSBT: s.ArkPSBT, + CheckpointPSBTs: s.CheckpointPSBTs, + TransferInputs: s.TransferInputs, + } + + return &StateTransition{ + NextState: &AwaitingArkSignatures{ + ArkPSBT: s.ArkPSBT, + CheckpointPSBTs: s.CheckpointPSBTs, + TransferInputs: s.TransferInputs, + RecipientOutputs: s.RecipientOutputs, + IdempotencyKey: s.IdempotencyKey, + DispatchRequestData: append( + []byte(nil), s.DispatchRequestData..., + ), + }, + NewEvents: fn.Some(EmittedEvent{ + Outbox: []OutboxEvent{request}, + }), + }, nil + + case *AbortPreparedEvent: + return abortPreparedTransition(s, event.Reason), nil + + case *FailEvent: + return abortPreparedTransition(s, event.Reason), nil + + default: + return unexpectedEvent(s), nil + } +} + +// abortPreparedTransition releases every input because preparation has not +// exposed signatures or crossed the operator co-sign boundary. +func abortPreparedTransition(state *Prepared, reason string) *StateTransition { + if reason == "" { + reason = "prepared transfer aborted" + } + + return &StateTransition{ + NextState: failedState(reason, state), + NewEvents: fn.Some(EmittedEvent{ + Outbox: []OutboxEvent{ + &ReleaseInputsRequest{ + Outpoints: InputOutpoints( + state.TransferInputs, + ), + ReserveEpochs: prePONRReserveEpochs( + state, + ), + }, + }, + }), + } +} + // ProcessEvent handles events for AwaitingArkSignatures. func (s *AwaitingArkSignatures) ProcessEvent(ctx context.Context, event Event, env *Environment) (*StateTransition, error) { @@ -573,6 +654,9 @@ func (s *Failed) ProcessEvent(ctx context.Context, event Event, func prePONRInputOutpoints(state State) []wire.OutPoint { var inputs []TransferInput switch s := state.(type) { + case *Prepared: + inputs = s.TransferInputs + case *AwaitingArkSignatures: inputs = s.TransferInputs @@ -603,6 +687,9 @@ func prePONRInputOutpoints(state State) []wire.OutPoint { func prePONRReserveEpochs(state State) map[wire.OutPoint]uint64 { var inputs []TransferInput switch s := state.(type) { + case *Prepared: + inputs = s.TransferInputs + case *AwaitingArkSignatures: inputs = s.TransferInputs diff --git a/sdk/ark/client.go b/sdk/ark/client.go index 11ba77b78..e5f0502b1 100644 --- a/sdk/ark/client.go +++ b/sdk/ark/client.go @@ -331,6 +331,12 @@ type CustomOORInput struct { // ExternalSignatures are tapscript signatures produced by additional // parties required by the selected spend path. ExternalSignatures []TaprootScriptSignature + + // PreserveSourceOwners retains the exact cooperative source leaf. + PreserveSourceOwners bool + + // PayoutSignatures authorize the final Ark payout, not the checkpoint. + PayoutSignatures []TaprootScriptSignature } // TaprootScriptSignature carries one externally produced tapscript signature @@ -1440,12 +1446,7 @@ func (c *Client) SignOORCustomInput(ctx context.Context, input CustomOORInput, "signature") } - return &TaprootScriptSignature{ - PubKey: append([]byte(nil), sig.GetPubkey()...), - WitnessScript: append([]byte(nil), sig.GetWitnessScript()...), - Signature: append([]byte(nil), sig.GetSignature()...), - SigHash: sig.GetSighash(), - }, nil + return signatureFromRPC(sig), nil } // customOORInputsToRPC converts SDK custom input structs to RPC messages. @@ -1460,35 +1461,17 @@ func customOORInputsToRPC(inputs []CustomOORInput) []*waverpc.CustomOORInput { // customOORInputToRPC converts one SDK custom input struct to an RPC message. func customOORInputToRPC(input CustomOORInput) *waverpc.CustomOORInput { - externalSigs := make( - []*waverpc.TaprootScriptSignature, 0, - len(input.ExternalSignatures), - ) - for j := range input.ExternalSignatures { - sig := input.ExternalSignatures[j] - externalSigs = append( - externalSigs, &waverpc.TaprootScriptSignature{ - Pubkey: append([]byte(nil), sig.PubKey...), - WitnessScript: append( - []byte(nil), sig.WitnessScript..., - ), - Signature: append( - []byte(nil), sig.Signature..., - ), - Sighash: sig.SigHash, - }, - ) - } - return &waverpc.CustomOORInput{ Outpoint: input.Outpoint, VtxoPolicyTemplate: append( []byte(nil), input.VTXOPolicyTemplate..., ), - SpendPath: append([]byte(nil), input.SpendPath...), - AmountSat: input.AmountSat, - PkScript: append([]byte(nil), input.PkScript...), - ExternalSignatures: externalSigs, + SpendPath: append([]byte(nil), input.SpendPath...), + AmountSat: input.AmountSat, + PkScript: append([]byte(nil), input.PkScript...), + ExternalSignatures: signaturesToRPC(input.ExternalSignatures), + PreserveSourceOwners: input.PreserveSourceOwners, + PayoutSignatures: signaturesToRPC(input.PayoutSignatures), } } @@ -1802,3 +1785,29 @@ func parseSessionTxID(sessionTxID string) ([]byte, error) { return append([]byte(nil), hash[:]...), nil } + +// signaturesToRPC isolates the wire signatures from caller-owned buffers. +func signaturesToRPC( + signatures []TaprootScriptSignature) []*waverpc.TaprootScriptSignature { + + externalSigs := make( + []*waverpc.TaprootScriptSignature, 0, len(signatures), + ) + for j := range signatures { + sig := signatures[j] + externalSigs = append( + externalSigs, &waverpc.TaprootScriptSignature{ + Pubkey: append([]byte(nil), sig.PubKey...), + WitnessScript: append( + []byte(nil), sig.WitnessScript..., + ), + Signature: append( + []byte(nil), sig.Signature..., + ), + Sighash: sig.SigHash, + }, + ) + } + + return externalSigs +} diff --git a/sdk/ark/cooperative_oor.go b/sdk/ark/cooperative_oor.go new file mode 100644 index 000000000..a457e4052 --- /dev/null +++ b/sdk/ark/cooperative_oor.go @@ -0,0 +1,68 @@ +package ark + +import ( + "bytes" + "context" + "fmt" + + "github.com/lightninglabs/wavelength/waverpc" +) + +// SignOORCooperativePackage asks the local wallet to independently rebuild the +// authorized transfer before signing both packets. The caller authenticates +// the recipient against its own swap state, not the signer's proposed PSBTs. +// Returns the checkpoint-input signature followed by the final Ark signature. +func (c *Client) SignOORCooperativePackage(ctx context.Context, + input CustomOORInput, recipientPubKey []byte, amountSat int64, + prepared *PreparedOOR) (*TaprootScriptSignature, + *TaprootScriptSignature, error) { + + if !input.PreserveSourceOwners || prepared == nil || + len(prepared.ArkPSBT) == 0 || + len(prepared.CheckpointPSBTs) != 1 || + len(prepared.CheckpointPSBTs[0]) == 0 { + return nil, nil, fmt.Errorf("unsigned cooperative package " + + "required") + } + pkg := &waverpc.CooperativeOORPackage{ + CustomInput: customOORInputToRPC(input), + Recipient: &waverpc.Output{ + Destination: &waverpc.Output_Pubkey{ + Pubkey: bytes.Clone(recipientPubKey), + }, + AmountSat: amountSat, + }, + CheckpointPsbt: bytes.Clone(prepared.CheckpointPSBTs[0]), + ArkPsbt: bytes.Clone(prepared.ArkPSBT), + } + // Leave both legacy fields empty so an older daemon refuses the request + // rather than silently signing just the checkpoint. + resp, err := c.daemon.SignOORCustomInput( + ctx, &waverpc.SignOORCustomInputRequest{ + CooperativePackage: pkg, + }, + ) + if err != nil { + return nil, nil, err + } + if resp.GetSignature() == nil || resp.GetPayoutSignature() == nil { + return nil, nil, fmt.Errorf("wallet did not return both " + + "signatures") + } + + return signatureFromRPC(resp.Signature), signatureFromRPC( + resp.PayoutSignature, + ), nil +} + +// signatureFromRPC returns an SDK-owned copy of a wallet signature. +func signatureFromRPC( + sig *waverpc.TaprootScriptSignature) *TaprootScriptSignature { + + return &TaprootScriptSignature{ + PubKey: bytes.Clone(sig.Pubkey), + WitnessScript: bytes.Clone(sig.WitnessScript), + Signature: bytes.Clone(sig.Signature), + SigHash: sig.Sighash, + } +} diff --git a/sdk/ark/cooperative_oor_test.go b/sdk/ark/cooperative_oor_test.go new file mode 100644 index 000000000..6ebe581ce --- /dev/null +++ b/sdk/ark/cooperative_oor_test.go @@ -0,0 +1,77 @@ +package ark + +import ( + "context" + "testing" + + "github.com/lightninglabs/wavelength/waverpc" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" +) + +type cooperativeTestSigner struct { + waverpc.DaemonServiceClient + + request *waverpc.SignOORCustomInputRequest + response *waverpc.SignOORCustomInputResponse +} + +// SignOORCustomInput records the RPC variant used by the SDK. +func (s *cooperativeTestSigner) SignOORCustomInput(_ context.Context, + req *waverpc.SignOORCustomInputRequest, _ ...grpc.CallOption) ( + *waverpc.SignOORCustomInputResponse, error) { + + s.request = req + + return s.response, nil +} + +// TestSignOORCooperativePackage locks the remote signer API and prevents a +// partial legacy response from escaping as a valid cooperative authorization. +func TestSignOORCooperativePackage(t *testing.T) { + t.Parallel() + + signer := &cooperativeTestSigner{} + signer.response = &waverpc.SignOORCustomInputResponse{ + Signature: &waverpc.TaprootScriptSignature{ + Signature: []byte{ + 1, + }, + }, + } + client := &Client{daemon: signer} + in := CustomOORInput{PreserveSourceOwners: true, AmountSat: 5000} + pkg := &PreparedOOR{ArkPSBT: []byte{1}, CheckpointPSBTs: [][]byte{{2}}} + + cp, payout, err := client.SignOORCooperativePackage( + t.Context(), in, []byte{3}, 5000, pkg, + ) + require.Error(t, err) + require.Nil(t, cp) + require.Nil(t, payout) + require.Nil(t, signer.request.CustomInput) + require.Empty(t, signer.request.CheckpointPsbt) + wire := signer.request.CooperativePackage + require.True(t, wire.CustomInput.PreserveSourceOwners) + require.Equal(t, pkg.ArkPSBT, wire.ArkPsbt) + require.Equal(t, pkg.CheckpointPSBTs[0], wire.CheckpointPsbt) + require.EqualValues(t, 5000, wire.Recipient.AmountSat) + require.Equal(t, []byte{3}, wire.Recipient.GetPubkey()) + + signer.response.PayoutSignature = &waverpc.TaprootScriptSignature{ + Signature: []byte{ + 2, + }, + } + cp, payout, err = client.SignOORCooperativePackage( + t.Context(), in, []byte{3}, 5000, pkg, + ) + require.NoError(t, err) + in.ExternalSignatures = []TaprootScriptSignature{*cp} + in.PayoutSignatures = []TaprootScriptSignature{*payout} + send := customOORInputToRPC(in) + signer.response.Signature.Signature[0]++ + signer.response.PayoutSignature.Signature[0]++ + require.Equal(t, []byte{1}, send.ExternalSignatures[0].Signature) + require.Equal(t, []byte{2}, send.PayoutSignatures[0].Signature) +} diff --git a/sdk/swaps/client.go b/sdk/swaps/client.go index 628b00569..97daba6dd 100644 --- a/sdk/swaps/client.go +++ b/sdk/swaps/client.go @@ -920,11 +920,24 @@ type InSwapRefundAuthorization struct { // refund checkpoint input. Signature TaprootScriptSignature + // PayoutSignature signs the final Ark payout, not the source VTXO. + PayoutSignature *TaprootScriptSignature + // FailureReason describes why the swap server considers the Lightning // payment terminal and therefore safe to refund immediately. FailureReason string } +// refundPayoutAuthorizer is an explicitly selected peer capability. The +// existence of a new RPC client method does not indicate peer support. +type refundPayoutAuthorizer interface { + SupportsRefundPayout() bool + + AuthorizeInSwapRefundPackage(context.Context, + *swaprpc.AuthorizeInSwapRefundRequest) ( + *InSwapRefundAuthorization, error) +} + // SwapClient is the high-level client API for Lightning<->Ark // swaps. type SwapClient struct { diff --git a/sdk/swaps/grpc_conn.go b/sdk/swaps/grpc_conn.go index d595b711f..746b5a916 100644 --- a/sdk/swaps/grpc_conn.go +++ b/sdk/swaps/grpc_conn.go @@ -541,7 +541,7 @@ func (g *GRPCSwapServerConn) AuthorizeInSwapRefund(ctx context.Context, return nil, fmt.Errorf("vHTLC amount must be positive") } - resp, err := g.client.AuthorizeInSwapRefund( + return g.authorizeRefund( ctx, &swaprpc.AuthorizeInSwapRefundRequest{ PaymentHash: append([]byte(nil), paymentHash[:]...), VhtlcOutpoint: vhtlcOutpoint, @@ -555,6 +555,40 @@ func (g *GRPCSwapServerConn) AuthorizeInSwapRefund(ctx context.Context, CheckpointPsbt: append([]byte(nil), checkpointPSBT...), }, ) +} + +// AuthorizeInSwapRefundPackage requests both signatures for an exact refund. +// A legacy peer may ignore the new fields; the SDK must not publish a +// checkpoint-only response as a cooperative refund. +func (g *GRPCSwapServerConn) AuthorizeInSwapRefundPackage(ctx context.Context, + req *swaprpc.AuthorizeInSwapRefundRequest) (*InSwapRefundAuthorization, + error) { + + if len(req.GetArkPsbt()) == 0 || len(req.GetCheckpointPsbt()) == 0 || + len(req.GetRefundPubkey()) == 0 || req.GetOwnerProof() == nil { + return nil, fmt.Errorf("incomplete refund payout package") + } + auth, err := g.authorizeRefund(ctx, req) + if err != nil { + return nil, err + } + if auth.PayoutSignature == nil { + return nil, status.Error( + codes.FailedPrecondition, + "peer did not authorize the full refund payout", + ) + } + + return auth, nil +} + +// authorizeRefund preserves the shared wire method and both distinct +// signatures without inferring peer capabilities from the transport type. +func (g *GRPCSwapServerConn) authorizeRefund(ctx context.Context, + req *swaprpc.AuthorizeInSwapRefundRequest) (*InSwapRefundAuthorization, + error) { + + resp, err := g.client.AuthorizeInSwapRefund(ctx, req) if err != nil { return nil, err } @@ -565,17 +599,29 @@ func (g *GRPCSwapServerConn) AuthorizeInSwapRefund(ctx context.Context, "empty signature") } - return &InSwapRefundAuthorization{ - Signature: TaprootScriptSignature{ - PubKey: append([]byte(nil), sig.GetPubkey()...), - WitnessScript: append( - []byte(nil), sig.GetWitnessScript()..., - ), - Signature: append([]byte(nil), sig.GetSignature()...), - SigHash: sig.GetSighash(), - }, + result := &InSwapRefundAuthorization{ + Signature: refundSignatureFromProto(sig), FailureReason: resp.GetFailureReason(), - }, nil + } + if payout := resp.GetPayoutSignature(); payout != nil { + sig := refundSignatureFromProto(payout) + result.PayoutSignature = &sig + } + + return result, nil +} + +// refundSignatureFromProto separates the two signing targets from the +// transport response before they are attached to the wallet's package. +func refundSignatureFromProto( + sig *swaprpc.TaprootScriptSignature) TaprootScriptSignature { + + return TaprootScriptSignature{ + PubKey: append([]byte(nil), sig.GetPubkey()...), + WitnessScript: append([]byte(nil), sig.GetWitnessScript()...), + Signature: append([]byte(nil), sig.GetSignature()...), + SigHash: sig.GetSighash(), + } } // SignInSwapForfeit asks the swap server to sign its participant share for one diff --git a/sdk/swaps/grpc_conn_test.go b/sdk/swaps/grpc_conn_test.go index 8cee29068..398915b87 100644 --- a/sdk/swaps/grpc_conn_test.go +++ b/sdk/swaps/grpc_conn_test.go @@ -21,6 +21,7 @@ type testSwapServiceClient struct { swaprpc.SwapServiceClient authorizeErr error + authorizeReply *swaprpc.AuthorizeInSwapRefundResponse ackErr error signForfeitResp *swaprpc.SignInSwapForfeitResponse signForfeitErr error @@ -35,7 +36,7 @@ func (c *testSwapServiceClient) AuthorizeInSwapRefund(context.Context, *swaprpc.AuthorizeInSwapRefundRequest, ...grpc.CallOption) ( *swaprpc.AuthorizeInSwapRefundResponse, error) { - return nil, c.authorizeErr + return c.authorizeReply, c.authorizeErr } func (c *testSwapServiceClient) AcknowledgeOutSwapHtlc(_ context.Context, @@ -289,6 +290,50 @@ func TestAuthorizeInSwapRefundPreservesStatusCode(t *testing.T) { require.Equal(t, codes.FailedPrecondition, status.Code(err)) } +// TestRefundPackageSeparatesSignatures pins the wire distinction between the +// receiver's checkpoint signature and its optional final-payout signature. +func TestRefundPackageSeparatesSignatures(t *testing.T) { + t.Parallel() + reply := &swaprpc.AuthorizeInSwapRefundResponse{ + Signature: &swaprpc.TaprootScriptSignature{ + Signature: []byte{ + 1, + }, + }, + } + conn := GRPCSwapServerConn{client: &testSwapServiceClient{ + authorizeReply: reply, + }} + req := &swaprpc.AuthorizeInSwapRefundRequest{ + ArkPsbt: []byte{ + 3, + }, CheckpointPsbt: []byte{ + 4, + }, + RefundPubkey: []byte{ + 5, + }, OwnerProof: &swaprpc.SwapOwnerProof{}, + } + _, err := conn.AuthorizeInSwapRefundPackage(t.Context(), req) + require.Equal(t, codes.FailedPrecondition, status.Code(err)) + legacy, err := conn.AuthorizeInSwapRefund( + t.Context(), lntypes.Hash{}, "source:0", 1, nil, nil, + req.CheckpointPsbt, + ) + require.NoError(t, err) + require.Nil(t, legacy.PayoutSignature) + reply.PayoutSignature = &swaprpc.TaprootScriptSignature{ + Signature: []byte{ + 2, + }, + } + both, err := conn.AuthorizeInSwapRefundPackage(t.Context(), req) + require.NoError(t, err) + require.Equal(t, []byte{1}, both.Signature.Signature) + require.NotNil(t, both.PayoutSignature) + require.Equal(t, []byte{2}, both.PayoutSignature.Signature) +} + // TestAcknowledgeOutSwapHTLCPreservesStatusCode verifies the receive session // can distinguish retryable or terminal server ACK failures by their original // gRPC status code. diff --git a/sdk/swaps/in_swap.go b/sdk/swaps/in_swap.go index 9bcf91143..61c94f0a1 100644 --- a/sdk/swaps/in_swap.go +++ b/sdk/swaps/in_swap.go @@ -1765,6 +1765,9 @@ func (s *paySession) tryCooperativeRefund(ctx context.Context) (bool, error) { return false, nil } + signer, ok := s.client.server.(refundPayoutAuthorizer) + fullPayout := ok && signer.SupportsRefundPayout() + funded, err := s.observeRefundableVHTLC(ctx) if err != nil { return false, newRetryableActionError( @@ -1794,11 +1797,12 @@ func (s *paySession) tryCooperativeRefund(ctx context.Context) (bool, error) { } input := CustomInput{ - Outpoint: s.vhtlcOutpoint, - VTXOPolicyTemplate: s.vhtlcPolicyTemplate, - SpendPath: spendPath, - AmountSat: s.vhtlcAmount, - PkScript: s.vhtlcPkScript, + Outpoint: s.vhtlcOutpoint, + VTXOPolicyTemplate: s.vhtlcPolicyTemplate, + SpendPath: spendPath, + AmountSat: s.vhtlcAmount, + PkScript: s.vhtlcPkScript, + PreserveSourceOwners: fullPayout, } prepared, err := s.client.daemon.PrepareOORWithCustomInputs( @@ -1815,6 +1819,16 @@ func (s *paySession) tryCooperativeRefund(ctx context.Context) (bool, error) { if err != nil { return false, err } + var request *swaprpc.AuthorizeInSwapRefundRequest + if fullPayout { + request, err = s.refundPayoutRequest( + ctx, input, preparedInput.CheckpointPSBT, + prepared.ArkPSBT, refundPubKey, + ) + if err != nil { + return false, newRetryableActionError(err) + } + } // Bound only the external authorization peer. Preparing, submitting // and persisting an accepted OOR keep the caller's lifetime so a slow @@ -1822,10 +1836,18 @@ func (s *paySession) tryCooperativeRefund(ctx context.Context) (bool, error) { authCtx, cancel := context.WithTimeout( ctx, cooperativeRefundAuthTimeout, ) - authorization, err := s.client.server.AuthorizeInSwapRefund( - authCtx, s.cfg.PaymentHash, s.vhtlcOutpoint, s.vhtlcAmount, - s.vhtlcPolicyTemplate, spendPath, preparedInput.CheckpointPSBT, - ) + var authorization *InSwapRefundAuthorization + if fullPayout { + authorization, err = signer.AuthorizeInSwapRefundPackage( + authCtx, request, + ) + } else { + authorization, err = s.client.server.AuthorizeInSwapRefund( + authCtx, s.cfg.PaymentHash, input.Outpoint, + input.AmountSat, input.VTXOPolicyTemplate, + input.SpendPath, preparedInput.CheckpointPSBT, + ) + } cancel() if err != nil { code := status.Code(err) @@ -1854,10 +1876,20 @@ func (s *paySession) tryCooperativeRefund(ctx context.Context) (bool, error) { "empty response"), ) } + // A legacy peer may ignore the payout request. Do not record an OOR + // session that cannot settle, or starve the sender-only timeout. + if fullPayout && authorization.PayoutSignature == nil { + return false, nil + } input.ExternalSignatures = []TaprootScriptSignature{ authorization.Signature, } + if fullPayout { + input.PayoutSignatures = []TaprootScriptSignature{ + *authorization.PayoutSignature, + } + } refundSessionID, err := s.client.daemon.SendOORWithCustomInputs( ctx, refundPubKey, s.vhtlcAmount, []CustomInput{input}, @@ -1900,6 +1932,43 @@ func (s *paySession) tryCooperativeRefund(ctx context.Context) (bool, error) { return true, nil } +// refundPayoutRequest authorizes this exact package to pay the wallet's fresh +// receive key. The swap server cannot infer that key from the original swap. +func (s *paySession) refundPayoutRequest(ctx context.Context, input CustomInput, + checkpointPSBT, arkPSBT, refundKey []byte) ( + *swaprpc.AuthorizeInSwapRefundRequest, error) { + + if input.AmountSat <= 0 || len(checkpointPSBT) == 0 || + len(arkPSBT) == 0 { + return nil, fmt.Errorf("incomplete prepared refund package") + } + identity, err := s.client.daemon.IdentityPubKey(ctx) + if err != nil { + return nil, err + } + hash := s.cfg.PaymentHash + proof, err := newSwapOwnerProof( + ctx, s.client.daemon, identity, swapRecoveryAuthRefundPayout, + s.client.currentTime().Unix(), hash[:], checkpointPSBT, arkPSBT, + refundKey, + ) + if err != nil { + return nil, err + } + + return &swaprpc.AuthorizeInSwapRefundRequest{ + PaymentHash: hash[:], + VhtlcOutpoint: input.Outpoint, + VhtlcAmountSat: uint64(input.AmountSat), + VhtlcPolicyTemplate: input.VTXOPolicyTemplate, + RefundSpendPath: input.SpendPath, + CheckpointPsbt: checkpointPSBT, + ArkPsbt: arkPSBT, + OwnerProof: proof, + RefundPubkey: refundKey, + }, nil +} + // preparedCustomInput returns the prepared checkpoint signing data for one // custom input outpoint. func preparedCustomInput(prepared *PreparedOOR, diff --git a/sdk/swaps/in_swap_observation_test.go b/sdk/swaps/in_swap_observation_test.go index bef7b4492..e4692df04 100644 --- a/sdk/swaps/in_swap_observation_test.go +++ b/sdk/swaps/in_swap_observation_test.go @@ -26,7 +26,7 @@ func TestPayWaitKeepsPollingInconclusiveFunding(t *testing.T) { return nil, errors.New("pending funding observation") }, } - client := NewSwapClient(nil, daemon, nil, nil) + client := NewSwapClient(&testInSwapServerConn{}, daemon, nil, nil) client.waitPollInterval = time.Millisecond session := &paySession{ client: client, diff --git a/sdk/swaps/in_swap_test.go b/sdk/swaps/in_swap_test.go index 838a274dc..fc1debd69 100644 --- a/sdk/swaps/in_swap_test.go +++ b/sdk/swaps/in_swap_test.go @@ -14,6 +14,7 @@ import ( "github.com/btcsuite/btcd/btcec/v2/schnorr" "github.com/btcsuite/btcd/btcutil/v2" "github.com/btcsuite/btcd/chaincfg/v2" + "github.com/btcsuite/btcd/chainhash/v2" "github.com/btcsuite/btcd/psbt/v2" "github.com/btcsuite/btcd/txscript/v2" "github.com/btcsuite/btcd/wire/v2" @@ -53,16 +54,24 @@ type testInSwapServerConn struct { createMaxCreditSat uint64 refundAuthorization *InSwapRefundAuthorization refundAuthorizeErr error - refundAuthorizeReq *testRefundAuthorizeReq + refundAuthorizeReq *swaprpc.AuthorizeInSwapRefundRequest } -type testRefundAuthorizeReq struct { - paymentHash lntypes.Hash - vhtlcOutpoint string - vhtlcAmountSat int64 - vhtlcPolicy []byte - refundSpendPath []byte - checkpointPSBT []byte +// testRefundAuthorization distinguishes the two tapscript signing targets. +func testRefundAuthorization(key *btcec.PublicKey) *InSwapRefundAuthorization { + return &InSwapRefundAuthorization{ + Signature: TaprootScriptSignature{ + PubKey: key.SerializeCompressed(), + WitnessScript: []byte("witness"), + Signature: []byte("server-sig"), + }, + PayoutSignature: &TaprootScriptSignature{ + PubKey: key.SerializeCompressed(), + WitnessScript: []byte("payout-leaf"), + Signature: []byte("payout-sig"), + }, + FailureReason: "payment failed", + } } type failAtExecDBTX struct { @@ -159,21 +168,25 @@ func (c *testInSwapServerConn) QuoteInSwap(_ context.Context, invoice string, return c.quote, nil } -// AuthorizeInSwapRefund records and returns the preconfigured refund -// authorization. -func (c *testInSwapServerConn) AuthorizeInSwapRefund(_ context.Context, - paymentHash lntypes.Hash, vhtlcOutpoint string, vhtlcAmountSat int64, - vhtlcPolicyTemplate, refundSpendPath, checkpointPSBT []byte) ( +// AuthorizeInSwapRefund rejects unexpected use of the checkpoint-only path. +func (c *testInSwapServerConn) AuthorizeInSwapRefund(context.Context, + lntypes.Hash, string, int64, []byte, []byte, []byte) ( *InSwapRefundAuthorization, error) { - c.refundAuthorizeReq = &testRefundAuthorizeReq{ - paymentHash: paymentHash, - vhtlcOutpoint: vhtlcOutpoint, - vhtlcAmountSat: vhtlcAmountSat, - vhtlcPolicy: append([]byte(nil), vhtlcPolicyTemplate...), - refundSpendPath: append([]byte(nil), refundSpendPath...), - checkpointPSBT: append([]byte(nil), checkpointPSBT...), - } + return nil, errors.New("unexpected checkpoint-only refund request") +} + +// SupportsRefundPayout identifies this fixture as an explicitly capable peer. +func (*testInSwapServerConn) SupportsRefundPayout() bool { + return true +} + +// AuthorizeInSwapRefundPackage records the complete transcript for assertions. +func (c *testInSwapServerConn) AuthorizeInSwapRefundPackage(_ context.Context, + req *swaprpc.AuthorizeInSwapRefundRequest) (*InSwapRefundAuthorization, + error) { + + c.refundAuthorizeReq = req if c.refundAuthorizeErr != nil { return nil, c.refundAuthorizeErr } @@ -1320,19 +1333,13 @@ func TestPaySessionCooperativeRefundsBeforeTimeout(t *testing.T) { }, Expiry: time.Now().Add(time.Minute), }, - refundAuthorization: &InSwapRefundAuthorization{ - Signature: TaprootScriptSignature{ - PubKey: serverPriv. - PubKey(). - SerializeCompressed(), - WitnessScript: []byte("witness"), - Signature: []byte("server-sig"), - }, - FailureReason: "payment failed", - }, + refundAuthorization: testRefundAuthorization( + serverPriv.PubKey(), + ), } daemonConn := &testDaemonConn{ + identityPriv: clientPriv, identityKey: clientPriv.PubKey(), operatorKey: operatorPriv.PubKey(), blockHeight: 50, @@ -1368,17 +1375,43 @@ func TestPaySessionCooperativeRefundsBeforeTimeout(t *testing.T) { require.Equal(t, 1, daemonConn.sendCustomCalls) require.NotNil(t, serverConn.refundAuthorizeReq) require.Equal( - t, "funding:0", serverConn.refundAuthorizeReq.vhtlcOutpoint, + t, "funding:0", + serverConn.refundAuthorizeReq.GetVhtlcOutpoint(), ) require.EqualValues( t, testInSwapAmountSat, - serverConn.refundAuthorizeReq.vhtlcAmountSat, + serverConn.refundAuthorizeReq.GetVhtlcAmountSat(), ) require.Equal( t, []byte("checkpoint"), - serverConn.refundAuthorizeReq.checkpointPSBT, + serverConn.refundAuthorizeReq.GetCheckpointPsbt(), + ) + require.Equal( + t, []byte("ark"), serverConn.refundAuthorizeReq.GetArkPsbt(), + ) + req := serverConn.refundAuthorizeReq + proof := req.GetOwnerProof() + require.NotNil(t, proof) + require.Equal( + t, daemonConn.receiveInfo.PubKeyXOnly, req.GetRefundPubkey(), + ) + authorization, err := schnorr.ParseSignature(proof.GetSignature()) + require.NoError(t, err) + message := swapRecoveryAuthMessage( + swapRecoveryAuthRefundPayout, proof.GetClientIdentityPubkey(), + proof.GetTimestampUnix(), proof.GetNonce(), + req.GetPaymentHash(), req.GetCheckpointPsbt(), req.GetArkPsbt(), + req.GetRefundPubkey(), ) + digest := chainhash.TaggedHash([]byte(swapRecoveryAuthTag), message) + require.True(t, authorization.Verify(digest[:], clientPriv.PubKey())) require.Len(t, daemonConn.lastClaimInput, 1) + require.True(t, daemonConn.lastClaimInput[0].PreserveSourceOwners) + require.Len(t, daemonConn.lastClaimInput[0].PayoutSignatures, 1) + require.Equal( + t, []byte("payout-sig"), + daemonConn.lastClaimInput[0].PayoutSignatures[0].Signature, + ) require.Len(t, daemonConn.lastClaimInput[0].ExternalSignatures, 1) require.Equal( t, []byte("server-sig"), @@ -1430,16 +1463,9 @@ func TestPaySessionCooperativeRefundUsesLocalFundingMetadata(t *testing.T) { }, Expiry: time.Now().Add(time.Minute), }, - refundAuthorization: &InSwapRefundAuthorization{ - Signature: TaprootScriptSignature{ - PubKey: serverPriv. - PubKey(). - SerializeCompressed(), - WitnessScript: []byte("witness"), - Signature: []byte("server-sig"), - }, - FailureReason: "payment failed", - }, + refundAuthorization: testRefundAuthorization( + serverPriv.PubKey(), + ), } daemonConn := &testDaemonConn{ @@ -1489,11 +1515,12 @@ func TestPaySessionCooperativeRefundUsesLocalFundingMetadata(t *testing.T) { require.Equal(t, 1, daemonConn.sendCustomCalls) require.NotNil(t, serverConn.refundAuthorizeReq) require.Equal( - t, "funding:0", serverConn.refundAuthorizeReq.vhtlcOutpoint, + t, "funding:0", + serverConn.refundAuthorizeReq.GetVhtlcOutpoint(), ) require.EqualValues( t, testInSwapAmountSat, - serverConn.refundAuthorizeReq.vhtlcAmountSat, + serverConn.refundAuthorizeReq.GetVhtlcAmountSat(), ) require.Equal(t, "funding:0", session.vhtlcOutpoint) require.EqualValues(t, testInSwapAmountSat, session.vhtlcAmount) @@ -1537,16 +1564,9 @@ func TestPaySessionCooperativeRefundWaitsForOutputBeforeTerminal(t *testing.T) { }, Expiry: time.Now().Add(time.Minute), }, - refundAuthorization: &InSwapRefundAuthorization{ - Signature: TaprootScriptSignature{ - PubKey: serverPriv. - PubKey(). - SerializeCompressed(), - WitnessScript: []byte("witness"), - Signature: []byte("server-sig"), - }, - FailureReason: "payment failed", - }, + refundAuthorization: testRefundAuthorization( + serverPriv.PubKey(), + ), } daemonConn := &testDaemonConn{ @@ -1749,16 +1769,9 @@ func TestPaySessionCooperativeRefundKeepsAcceptedSessionOnPersistFailure( }, Expiry: time.Now().Add(time.Minute), }, - refundAuthorization: &InSwapRefundAuthorization{ - Signature: TaprootScriptSignature{ - PubKey: serverPriv. - PubKey(). - SerializeCompressed(), - WitnessScript: []byte("witness"), - Signature: []byte("server-sig"), - }, - FailureReason: "payment failed", - }, + refundAuthorization: testRefundAuthorization( + serverPriv.PubKey(), + ), } daemonConn := &testDaemonConn{ @@ -1868,16 +1881,9 @@ func TestPaySessionResumeAfterAcceptedRefundFindsOutput(t *testing.T) { }, Expiry: time.Now().Add(time.Minute), }, - refundAuthorization: &InSwapRefundAuthorization{ - Signature: TaprootScriptSignature{ - PubKey: serverPriv. - PubKey(). - SerializeCompressed(), - WitnessScript: []byte("witness"), - Signature: []byte("server-sig"), - }, - FailureReason: "payment failed", - }, + refundAuthorization: testRefundAuthorization( + serverPriv.PubKey(), + ), } daemonConn := &testDaemonConn{ @@ -2021,16 +2027,9 @@ func TestPaySessionResumeAfterAcceptedRefundUsesSpentVHTLCFallback( }, Expiry: time.Now().Add(time.Minute), }, - refundAuthorization: &InSwapRefundAuthorization{ - Signature: TaprootScriptSignature{ - PubKey: serverPriv. - PubKey(). - SerializeCompressed(), - WitnessScript: []byte("witness"), - Signature: []byte("server-sig"), - }, - FailureReason: "payment failed", - }, + refundAuthorization: testRefundAuthorization( + serverPriv.PubKey(), + ), } daemonConn := &testDaemonConn{ diff --git a/sdk/swaps/out_swap.go b/sdk/swaps/out_swap.go index f7c081f6a..d652c6829 100644 --- a/sdk/swaps/out_swap.go +++ b/sdk/swaps/out_swap.go @@ -914,7 +914,7 @@ func (s *ReceiveSession) waitForHTLCEvent(ctx context.Context) error { defer cancel() notification, err := s.waitIncomingVHTLCNotification( - waitCtx, authKey, + waitCtx, ctx, authKey, ) if err != nil { if invoiceDeadlineExceeded(ctx, waitCtx, err) { @@ -1011,9 +1011,11 @@ func (s *ReceiveSession) waitForFunding(ctx context.Context) error { } // waitIncomingVHTLCNotification waits for and validates the server notification -// that tells this receiver which vHTLC script should be funded. -func (s *ReceiveSession) waitIncomingVHTLCNotification(ctx context.Context, - authKey ReceiveAuthKey) (*IncomingVHTLCNotification, error) { +// that tells this receiver which vHTLC script should be funded. Acceptance uses +// the parent context so the delivery deadline cannot interrupt persistence. +func (s *ReceiveSession) waitIncomingVHTLCNotification( + ctx, acceptCtx context.Context, authKey ReceiveAuthKey) ( + *IncomingVHTLCNotification, error) { if receiver, ok := s.client.outEvents.(IncomingVHTLCEventReceiver); ok { notification, err := receiver.WaitIncomingVHTLC( @@ -1028,7 +1030,7 @@ func (s *ReceiveSession) waitIncomingVHTLCNotification(ctx context.Context, } return s.acceptIncomingVHTLCNotification( - ctx, notification, authKey, + acceptCtx, notification, authKey, ) } @@ -1052,7 +1054,7 @@ func (s *ReceiveSession) waitIncomingVHTLCNotification(ctx context.Context, return nil, err } - return s.acceptIncomingVHTLCNotification(ctx, incoming, authKey) + return s.acceptIncomingVHTLCNotification(acceptCtx, incoming, authKey) } // validateIncomingVHTLCAck checks mailbox ack metadata before the notification diff --git a/sdk/swaps/out_swap_test.go b/sdk/swaps/out_swap_test.go index e0cc79a6e..a4ebd0adf 100644 --- a/sdk/swaps/out_swap_test.go +++ b/sdk/swaps/out_swap_test.go @@ -2332,7 +2332,9 @@ func TestWaitIncomingVHTLCNotificationRejectsMissingAckCursor(t *testing.T) { clientPubKey: clientPriv.PubKey(), } - _, err = session.waitIncomingVHTLCNotification(t.Context(), nil) + _, err = session.waitIncomingVHTLCNotification( + t.Context(), t.Context(), nil, + ) require.ErrorContains(t, err, "incoming vHTLC ack cursor") require.Equal(t, ReceiveStateInvoiceCreated, session.State()) require.Zero(t, session.pendingHTLCAckCursor) @@ -2903,6 +2905,7 @@ func (d *testDaemonConn) PrepareOORWithCustomInputs(_ context.Context, } return &PreparedOOR{ + ArkPSBT: []byte("ark"), CustomInputs: []PreparedOORCustomInput{{ Outpoint: inputs[0].Outpoint, CheckpointPSBT: []byte("checkpoint"), @@ -4283,7 +4286,9 @@ func TestReceiveSessionOverdueInvoiceAcceptsDeliveredEvent(t *testing.T) { client := NewSwapClientWithStore( serverConn, daemonConn, nil, creator, store, ) - client.overdueReceivePollWindow = 100 * time.Millisecond + // The cached event is already delivered, so acceptance must persist + // under the parent context even after the polling window closes. + client.overdueReceivePollWindow = 0 useTestOnionDecoder(client, 42_000) session, err := client.StartReceiveViaLightning( diff --git a/sdk/swaps/recovery_auth.go b/sdk/swaps/recovery_auth.go index ec21d9526..86963b777 100644 --- a/sdk/swaps/recovery_auth.go +++ b/sdk/swaps/recovery_auth.go @@ -19,6 +19,7 @@ const ( swapRecoveryAuthList = "list-recoverable-swaps" swapRecoveryAuthCreateIn = "create-in-swap" swapRecoveryAuthRequestChannel = "request-channel-id" + swapRecoveryAuthRefundPayout = "authorize-in-swap-refund-payout" swapRecoveryNonceLen = 16 ) diff --git a/sdk/swaps/refund_auth_context_test.go b/sdk/swaps/refund_auth_context_test.go index 519b59e14..a1a1af6f5 100644 --- a/sdk/swaps/refund_auth_context_test.go +++ b/sdk/swaps/refund_auth_context_test.go @@ -59,6 +59,9 @@ func TestCooperativeRefundBoundsOnlyAuthorization(t *testing.T) { WitnessScript: []byte("witness"), Signature: []byte("authorized-refund"), }, + PayoutSignature: &TaprootScriptSignature{ + Signature: []byte("payout-sig"), + }, }, } client.server = remote diff --git a/sdk/swaps/server_recovery_settlement_test.go b/sdk/swaps/server_recovery_settlement_test.go index 1d0f56e93..f991cfa56 100644 --- a/sdk/swaps/server_recovery_settlement_test.go +++ b/sdk/swaps/server_recovery_settlement_test.go @@ -25,10 +25,15 @@ type restoredRefundServer struct { bounded bool } -// AuthorizeInSwapRefund simulates a safely failed payment or unavailable peer. -func (s *restoredRefundServer) AuthorizeInSwapRefund(ctx context.Context, - _ lntypes.Hash, _ string, _ int64, _ []byte, _ []byte, _ []byte) ( - *InSwapRefundAuthorization, error) { +// SupportsRefundPayout selects the two-signature protocol for this fixture. +func (*restoredRefundServer) SupportsRefundPayout() bool { + return true +} + +// AuthorizeInSwapRefundPackage simulates a failed payment or unavailable peer. +func (s *restoredRefundServer) AuthorizeInSwapRefundPackage(ctx context.Context, + _ *swaprpc.AuthorizeInSwapRefundRequest) (*InSwapRefundAuthorization, + error) { s.calls++ deadline, ok := ctx.Deadline() @@ -66,6 +71,84 @@ func TestRestoredRefundBoundsCooperation(t *testing.T) { require.Equal(t, 1, daemon.sendCustomCalls) } +// legacyRefundServer implements only the ordinary checkpoint authorization. +type legacyRefundServer struct { + *testSwapServerConn + checkpoint []byte +} + +// AuthorizeInSwapRefund records the legacy request before maturity. +func (s *legacyRefundServer) AuthorizeInSwapRefund(_ context.Context, + _ lntypes.Hash, _ string, _ int64, _, _, checkpoint []byte) ( + *InSwapRefundAuthorization, error) { + + s.checkpoint = checkpoint + + return &InSwapRefundAuthorization{ + Signature: TaprootScriptSignature{ + Signature: []byte("checkpoint"), + }, + }, nil +} + +// TestDefaultRefundUsesLegacyPackage exercises ordinary recovery with an +// older server. Success means submitting before expiry, not waiting until it. +func TestDefaultRefundUsesLegacyPackage(t *testing.T) { + client, daemon, remote, row := newRefundRecoveryFixture(t) + legacy := &legacyRefundServer{testSwapServerConn: remote} + client.server = legacy + daemon.blockHeight = row.GetRefundLocktime() - 1 + daemon.sendSessionID = "ordinary-refund" + _, err := client.RecoverSwapserverVHTLCs(t.Context()) + require.NoError(t, err) + hash, err := lntypes.MakeHash(row.GetPaymentHash()) + require.NoError(t, err) + s, err := client.ResumePayViaLightning(t.Context(), hash) + require.NoError(t, err) + submitted, err := s.tryCooperativeRefund(t.Context()) + require.NoError(t, err) + require.True(t, submitted) + require.NotEmpty(t, legacy.checkpoint) + require.Equal(t, daemon.sendSessionID, s.refundSessionID) + require.Len(t, daemon.lastClaimInput, 1) + require.False(t, daemon.lastClaimInput[0].PreserveSourceOwners) + require.Empty(t, daemon.lastClaimInput[0].PayoutSignatures) +} + +// TestCheckpointOnlyReplyKeepsTimeoutRefund rejects a legacy peer's partial +// authorization without creating an OOR or blocking the mature timeout path. +func TestCheckpointOnlyReplyKeepsTimeoutRefund(t *testing.T) { + t.Parallel() + client, daemon, server, row := newRefundRecoveryFixture(t) + client.server = &restoredRefundServer{ + testSwapServerConn: server, + authorization: &InSwapRefundAuthorization{ + Signature: TaprootScriptSignature{ + Signature: []byte("only-the-checkpoint"), + }, + }, + } + client.waitPollInterval = time.Millisecond + daemon.blockHeight = row.GetRefundLocktime() - 1 + daemon.sendSessionID = "timeout-refund" + _, err := client.RecoverSwapserverVHTLCs(t.Context()) + require.NoError(t, err) + hash, err := lntypes.MakeHash(row.GetPaymentHash()) + require.NoError(t, err) + session, err := client.ResumePayViaLightning(t.Context(), hash) + require.NoError(t, err) + accepted, err := session.tryCooperativeRefund(t.Context()) + require.NoError(t, err) + require.False(t, accepted) + require.Zero(t, daemon.sendCustomCalls) + require.Empty(t, session.refundSessionID) + + daemon.blockHeight = row.GetRefundLocktime() + require.NoError(t, session.completeRefund(t.Context())) + require.Equal(t, 1, daemon.sendCustomCalls) + require.Empty(t, daemon.lastClaimInput[0].ExternalSignatures) +} + // TestRestoredLateReceiveStaysPending prevents both cooperative disclosure and // automatic exit admission once the sender's refund path is already open. func TestRestoredLateReceiveStaysPending(t *testing.T) { @@ -193,8 +276,11 @@ func TestRestoredRefundSessionSettles(t *testing.T) { if cooperative { daemon.blockHeight = 50 daemon.spendOnCustom = true + payout := signature + payout.Signature = []byte("payout-sig") authorization := &InSwapRefundAuthorization{ - Signature: signature, + Signature: signature, + PayoutSignature: &payout, } refundServer.authorization = authorization } else { diff --git a/serverconn/AGENTS.md b/serverconn/AGENTS.md index ed1fec312..97ba3c2a3 100644 --- a/serverconn/AGENTS.md +++ b/serverconn/AGENTS.md @@ -9,10 +9,25 @@ background ingress polling with event routing. ## Key Types - `Runtime` — Main entry point wrapping DurableActor, ServerConnectionActor, and UnaryFacade. The egress DurableActor runs on the Read/Commit (`TxBehavior`) path: each handler builds its envelope and calls `Edge.Send` with NO SQLite writer held, then a short lease-fenced Commit folds the ack + dedup. It runs as a competing-consumer pool of `ConnectorConfig.EgressWorkers` worker loops, so the round and out-of-round actors' sends proceed concurrently; the single ingress puller is separate and unaffected. +- `DurableActorID(replyMailboxID)` — Derives the durable actor ID + (`serverconn-`) shared by the egress mailbox and ingress + checkpoint. The effective reply mailbox, rather than the authenticated + sender identity, keys the ID so two connectors on one identity get separate + runtimes and delivery cursors. - `ServerConnectionActor` — Core behavior handling egress messages and the ingress loop. Dispatches `DurableUnaryQuery` values generically via `buildDurableUnary`. - `ArkVersionNegotiator` — Single home for Ark protocol version selection (`ark_version.go`). `Bootstrap` performs the one bootstrap `GetInfo` over the operator's **direct** ArkService connection (`ArkVersionGetInfoClient`, never the mailbox edge) and returns the response + selected version; the daemon parses domain terms from the same response. The free function `ValidateRefreshSelection(resp, boundVersion)` enforces that a refresh-only `GetInfo` keeps the runtime bound (returns a permanent `*StatusError` on drift/disable). Enabled versions are derived from the response's ACTIVE `ArkVersionPolicy` entries. - `UnaryFacade` — Implements `mailboxrpc.RPCClient` for generated RPC stubs (low-latency path). Bounded waits come from the caller's context plus the response registry TTL; there is no separate timeout entry point. `SendRPC` gates on `ConnectorConfig.MaxInFlightUnary` and fails a send that would exceed it with `codes.ResourceExhausted`. - `ConnectorConfig` — Wiring configuration (edge address, mailbox IDs, dispatchers, store, durable unary builder, `EgressWorkers`, `MaxInFlightUnary`). `EgressWorkers` sizes the egress worker pool (default `DefaultEgressWorkers` = 4); `<= 1` keeps the legacy single sender. The `DurableUnaryBuilder` field must be set to handle `DurableUnaryQuery` message types; otherwise those messages are rejected. The `AuthSignature` field holds the Schnorr auth sig injected into every outbound envelope via `mergeAuthHeaders` (auth header always wins over caller-provided headers). +- `LocalMailboxID` and `ReplyMailboxID` on `ConnectorConfig` — + `LocalMailboxID` is the authenticated identity stamped as the sender of + outbound envelopes. Optional `ReplyMailboxID` names the mailbox in every + `RpcMeta.ReplyTo`, the stream that ingress pulls and acknowledges, the + durable runtime and checkpoint, and the namespace for ingress receipts and + poison quarantine. An empty value uses `LocalMailboxID`. A distinct reply + mailbox lets several connectors share one transport and identity key without + sharing service registrations or delivery cursors. Ingress and reply call + sites use `ConnectorConfig.replyMailboxID()` rather than reading + `LocalMailboxID` directly. - `PubKeyMailboxID` — Derives canonical mailbox ID from a public key (hex-encoded compressed SEC). Panics on nil. - `MailboxAuthDigest` / `MailboxAuthMessage` — BIP-340 tagged hash digest construction for mailbox auth signatures. Uses `chainhash.TaggedHash` with the `MailboxAuthTagStr` domain separator over `senderCompressedPubKey || recipientMailboxID`. **Do not read this as preventing cross-server replay on its own** — see the invariant below for which callers get that property and which do not. - `SignMailboxAuth` / `VerifyMailboxAuth` / `ParseMailboxPubKey` — Schnorr sign/verify helpers for pubkey-derived mailbox identity. @@ -49,7 +64,10 @@ background ingress polling with event routing. replaces the concrete inner message with a `rawServerMessage` that no longer implements `CorrelationKey()`. This ensures the durable mailbox enqueues events into the correct per-key FIFO lane (e.g. `oor/`, - `round/`) even after a crash-replay decode cycle. + `round/`) even after a crash-replay decode cycle. The actor also stamps + this key into the outbound KIND_EVENT envelope's `RpcMeta.CorrelationId`, so + the peer admits the event under the same lane identity used for local + ordering. ## Relationships @@ -75,14 +93,30 @@ background ingress polling with event routing. it addresses, but only `Send` gets the strong version: it passes the compound `operator:client` recipient, which embeds the operator's pubkey-derived ID, so a `Send` signature is useless at any other operator. - `Pull` and `AckUpTo` pass the client's own **plain** mailbox ID (from - `ConnectorConfig.LocalMailboxID`), which carries no operator component — so - that digest is identical at every operator, and one `Pull`/`Ack` signature - authorizes that client's mailbox at every operator its identity key is known - to. Identity keys are a deterministic derivation, so a wallet driving two - operators presents the same credential to both. Closing the `Pull`/`Ack` - case means folding a server identity into the digest, which is a wire change - on both sides. + `Pull` and `AckUpTo` pass the client's own **plain** mailbox ID (the effective + reply mailbox from `ConnectorConfig.replyMailboxID()`), which carries no + operator component. The digest is therefore identical at every operator, + and one `Pull`/`Ack` signature authorizes that client's mailbox wherever its + identity key is known. Identity keys are deterministic, so a wallet driving + two operators presents the same credential to both. Closing the `Pull`/`Ack` + case requires folding a server identity into the digest, which is a wire + change on both sides. +- **All ingress-owned durable state is keyed by the reply mailbox, never the + authenticated sender identity.** The durable runtime ID, ack checkpoint, + receipt occurrence ID (`ingress-event/v1` field list), and poison-quarantine + lane digest all derive from `ConnectorConfig.replyMailboxID()`. Keying any of + them by `LocalMailboxID` would let connectors sharing one identity also share + a delivery cursor, receipt namespace, and quarantine reservation. One + runtime could then acknowledge an envelope that another never dispatched, + or one stream's poison traffic could exhaust another's recovery capacity. +- `loadCheckpoint` rejects a checkpoint whose `ActorID` differs from this + runtime's ID or whose `StateType` is not `ackStateType` before decoding + `StateData`. A cursor from another ingress stream is a wrong-stream fault, + not a decoding problem. +- `validateInboundEnvelope` rejects any non-empty `Recipient` that differs + from the effective reply mailbox. An empty recipient remains valid because + the wire field is optional; an explicit mismatch fails before replay, + receipt, or dispatch processing. - Ack watermark only advances AFTER durable local dispatch commit (prevents message loss on crash). - The ingress fold never holds the database writer across network IO. `runFoldedDispatch` runs waiter-backed responses and the `ConnectorConfig.NonTxRoutes` requests BEFORE opening the write transaction; only durable enqueues and the cursor checkpoint go inside it. A route is hoisted only when it is listed in `NonTxRoutes` AND the envelope is a `KIND_REQUEST`, so a durable actor `Tell` can never escape the fold. An envelope of any other kind arriving on a marked route is skip-warned by `dispatchBatch` rather than dispatched, because the mux bridge ignores `env.Rpc.Kind` and would otherwise serve a sender-mislabeled envelope over the network with the writer held. Any new dispatcher that terminates in `Edge.Send` rather than a durable enqueue MUST be added to `NonTxRoutes` at wiring time (see `waved.Server.buildRPCDispatchers`), otherwise it pins the SQLite global writer lock (production opens with `_txlock=immediate`) or a SERIALIZABLE Postgres snapshot for the length of a round trip to the operator. - Pre-transaction dispatch happens before the commit, never after. A crash in between re-pulls the batch and redelivers, which is the at-least-once contract; committing first would advance the cursor past a request that was never answered. @@ -154,6 +188,11 @@ are consumed at durable inbox insertion, not at an in-memory Tell. Quarantine uses per-lane reservations inside a global bound and is never aged out; recovery removes it only with a durable handoff. +`ingressScope{reply, remote}` is the trust-domain pair used by receipts and +quarantine. `ServerConnectionActor.ingressEvidenceScope()` derives it from +local configuration for both transactional ingress and quarantine retry; it +does not trust peer-controlled envelope routing fields. + ## Warm receipt windows Host mode transitions retain the daemon and join ingress ownership. Restricted diff --git a/serverconn/CLAUDE.md b/serverconn/CLAUDE.md index ed1fec312..97ba3c2a3 100644 --- a/serverconn/CLAUDE.md +++ b/serverconn/CLAUDE.md @@ -9,10 +9,25 @@ background ingress polling with event routing. ## Key Types - `Runtime` — Main entry point wrapping DurableActor, ServerConnectionActor, and UnaryFacade. The egress DurableActor runs on the Read/Commit (`TxBehavior`) path: each handler builds its envelope and calls `Edge.Send` with NO SQLite writer held, then a short lease-fenced Commit folds the ack + dedup. It runs as a competing-consumer pool of `ConnectorConfig.EgressWorkers` worker loops, so the round and out-of-round actors' sends proceed concurrently; the single ingress puller is separate and unaffected. +- `DurableActorID(replyMailboxID)` — Derives the durable actor ID + (`serverconn-`) shared by the egress mailbox and ingress + checkpoint. The effective reply mailbox, rather than the authenticated + sender identity, keys the ID so two connectors on one identity get separate + runtimes and delivery cursors. - `ServerConnectionActor` — Core behavior handling egress messages and the ingress loop. Dispatches `DurableUnaryQuery` values generically via `buildDurableUnary`. - `ArkVersionNegotiator` — Single home for Ark protocol version selection (`ark_version.go`). `Bootstrap` performs the one bootstrap `GetInfo` over the operator's **direct** ArkService connection (`ArkVersionGetInfoClient`, never the mailbox edge) and returns the response + selected version; the daemon parses domain terms from the same response. The free function `ValidateRefreshSelection(resp, boundVersion)` enforces that a refresh-only `GetInfo` keeps the runtime bound (returns a permanent `*StatusError` on drift/disable). Enabled versions are derived from the response's ACTIVE `ArkVersionPolicy` entries. - `UnaryFacade` — Implements `mailboxrpc.RPCClient` for generated RPC stubs (low-latency path). Bounded waits come from the caller's context plus the response registry TTL; there is no separate timeout entry point. `SendRPC` gates on `ConnectorConfig.MaxInFlightUnary` and fails a send that would exceed it with `codes.ResourceExhausted`. - `ConnectorConfig` — Wiring configuration (edge address, mailbox IDs, dispatchers, store, durable unary builder, `EgressWorkers`, `MaxInFlightUnary`). `EgressWorkers` sizes the egress worker pool (default `DefaultEgressWorkers` = 4); `<= 1` keeps the legacy single sender. The `DurableUnaryBuilder` field must be set to handle `DurableUnaryQuery` message types; otherwise those messages are rejected. The `AuthSignature` field holds the Schnorr auth sig injected into every outbound envelope via `mergeAuthHeaders` (auth header always wins over caller-provided headers). +- `LocalMailboxID` and `ReplyMailboxID` on `ConnectorConfig` — + `LocalMailboxID` is the authenticated identity stamped as the sender of + outbound envelopes. Optional `ReplyMailboxID` names the mailbox in every + `RpcMeta.ReplyTo`, the stream that ingress pulls and acknowledges, the + durable runtime and checkpoint, and the namespace for ingress receipts and + poison quarantine. An empty value uses `LocalMailboxID`. A distinct reply + mailbox lets several connectors share one transport and identity key without + sharing service registrations or delivery cursors. Ingress and reply call + sites use `ConnectorConfig.replyMailboxID()` rather than reading + `LocalMailboxID` directly. - `PubKeyMailboxID` — Derives canonical mailbox ID from a public key (hex-encoded compressed SEC). Panics on nil. - `MailboxAuthDigest` / `MailboxAuthMessage` — BIP-340 tagged hash digest construction for mailbox auth signatures. Uses `chainhash.TaggedHash` with the `MailboxAuthTagStr` domain separator over `senderCompressedPubKey || recipientMailboxID`. **Do not read this as preventing cross-server replay on its own** — see the invariant below for which callers get that property and which do not. - `SignMailboxAuth` / `VerifyMailboxAuth` / `ParseMailboxPubKey` — Schnorr sign/verify helpers for pubkey-derived mailbox identity. @@ -49,7 +64,10 @@ background ingress polling with event routing. replaces the concrete inner message with a `rawServerMessage` that no longer implements `CorrelationKey()`. This ensures the durable mailbox enqueues events into the correct per-key FIFO lane (e.g. `oor/`, - `round/`) even after a crash-replay decode cycle. + `round/`) even after a crash-replay decode cycle. The actor also stamps + this key into the outbound KIND_EVENT envelope's `RpcMeta.CorrelationId`, so + the peer admits the event under the same lane identity used for local + ordering. ## Relationships @@ -75,14 +93,30 @@ background ingress polling with event routing. it addresses, but only `Send` gets the strong version: it passes the compound `operator:client` recipient, which embeds the operator's pubkey-derived ID, so a `Send` signature is useless at any other operator. - `Pull` and `AckUpTo` pass the client's own **plain** mailbox ID (from - `ConnectorConfig.LocalMailboxID`), which carries no operator component — so - that digest is identical at every operator, and one `Pull`/`Ack` signature - authorizes that client's mailbox at every operator its identity key is known - to. Identity keys are a deterministic derivation, so a wallet driving two - operators presents the same credential to both. Closing the `Pull`/`Ack` - case means folding a server identity into the digest, which is a wire change - on both sides. + `Pull` and `AckUpTo` pass the client's own **plain** mailbox ID (the effective + reply mailbox from `ConnectorConfig.replyMailboxID()`), which carries no + operator component. The digest is therefore identical at every operator, + and one `Pull`/`Ack` signature authorizes that client's mailbox wherever its + identity key is known. Identity keys are deterministic, so a wallet driving + two operators presents the same credential to both. Closing the `Pull`/`Ack` + case requires folding a server identity into the digest, which is a wire + change on both sides. +- **All ingress-owned durable state is keyed by the reply mailbox, never the + authenticated sender identity.** The durable runtime ID, ack checkpoint, + receipt occurrence ID (`ingress-event/v1` field list), and poison-quarantine + lane digest all derive from `ConnectorConfig.replyMailboxID()`. Keying any of + them by `LocalMailboxID` would let connectors sharing one identity also share + a delivery cursor, receipt namespace, and quarantine reservation. One + runtime could then acknowledge an envelope that another never dispatched, + or one stream's poison traffic could exhaust another's recovery capacity. +- `loadCheckpoint` rejects a checkpoint whose `ActorID` differs from this + runtime's ID or whose `StateType` is not `ackStateType` before decoding + `StateData`. A cursor from another ingress stream is a wrong-stream fault, + not a decoding problem. +- `validateInboundEnvelope` rejects any non-empty `Recipient` that differs + from the effective reply mailbox. An empty recipient remains valid because + the wire field is optional; an explicit mismatch fails before replay, + receipt, or dispatch processing. - Ack watermark only advances AFTER durable local dispatch commit (prevents message loss on crash). - The ingress fold never holds the database writer across network IO. `runFoldedDispatch` runs waiter-backed responses and the `ConnectorConfig.NonTxRoutes` requests BEFORE opening the write transaction; only durable enqueues and the cursor checkpoint go inside it. A route is hoisted only when it is listed in `NonTxRoutes` AND the envelope is a `KIND_REQUEST`, so a durable actor `Tell` can never escape the fold. An envelope of any other kind arriving on a marked route is skip-warned by `dispatchBatch` rather than dispatched, because the mux bridge ignores `env.Rpc.Kind` and would otherwise serve a sender-mislabeled envelope over the network with the writer held. Any new dispatcher that terminates in `Edge.Send` rather than a durable enqueue MUST be added to `NonTxRoutes` at wiring time (see `waved.Server.buildRPCDispatchers`), otherwise it pins the SQLite global writer lock (production opens with `_txlock=immediate`) or a SERIALIZABLE Postgres snapshot for the length of a round trip to the operator. - Pre-transaction dispatch happens before the commit, never after. A crash in between re-pulls the batch and redelivers, which is the at-least-once contract; committing first would advance the cursor past a request that was never answered. @@ -154,6 +188,11 @@ are consumed at durable inbox insertion, not at an in-memory Tell. Quarantine uses per-lane reservations inside a global bound and is never aged out; recovery removes it only with a durable handoff. +`ingressScope{reply, remote}` is the trust-domain pair used by receipts and +quarantine. `ServerConnectionActor.ingressEvidenceScope()` derives it from +local configuration for both transactional ingress and quarantine retry; it +does not trust peer-controlled envelope routing fields. + ## Warm receipt windows Host mode transitions retain the daemon and join ingress ownership. Restricted diff --git a/serverconn/actor.go b/serverconn/actor.go index f2a111831..e23b1220e 100644 --- a/serverconn/actor.go +++ b/serverconn/actor.go @@ -695,6 +695,12 @@ type ServerConnectionActor struct { ingressCancel atomic.Pointer[context.CancelFunc] } +// runtimeID binds durable egress and ingress checkpoint state to the mailbox +// whose delivery cursor that state advances. +func (a *ServerConnectionActor) runtimeID() string { + return DurableActorID(a.cfg.replyMailboxID()) +} + // NewServerConnectionActor creates a new server connection actor with the // given configuration. The actor must be started via its DurableActor wrapper // and the ingress loop must be started separately via StartIngress. @@ -855,10 +861,11 @@ func (a *ServerConnectionActor) handleSendClientEvent(ctx context.Context, Headers: a.cfg.mergeAuthHeaders(nil), Body: body, Rpc: &mailboxpb.RpcMeta{ - Kind: mailboxpb.RpcMeta_KIND_EVENT, - Service: service, - Method: method, - ReplyTo: a.cfg.LocalMailboxID, + Kind: mailboxpb.RpcMeta_KIND_EVENT, + Service: service, + Method: method, + CorrelationId: req.CorrelationKey(), + ReplyTo: a.cfg.replyMailboxID(), }, } @@ -1019,7 +1026,7 @@ func (a *ServerConnectionActor) sendUnaryEnvelope(ctx context.Context, Service: service, Method: method, CorrelationId: correlationID, - ReplyTo: a.cfg.LocalMailboxID, + ReplyTo: a.cfg.replyMailboxID(), }, } diff --git a/serverconn/actor_correlation_key_test.go b/serverconn/actor_correlation_key_test.go index 5f24d3004..d15702820 100644 --- a/serverconn/actor_correlation_key_test.go +++ b/serverconn/actor_correlation_key_test.go @@ -7,6 +7,7 @@ import ( "time" "github.com/lightninglabs/wavelength/baselib/actor" + mailboxpb "github.com/lightninglabs/wavelength/mailbox/pb" mailboxrpc "github.com/lightninglabs/wavelength/mailbox/rpc" fn "github.com/lightningnetwork/lnd/fn/v2" "github.com/stretchr/testify/require" @@ -264,3 +265,33 @@ func TestSendClientEventRequestPlumbsCorrelationKeyToStore(t *testing.T) { "wrapper must forward inner CorrelationKey into EnqueueParams", ) } + +// TestSendClientEventRequestEmitsCorrelationID verifies that the durable +// claim key also crosses the final transport boundary. The server uses this +// field to bind channel protocol messages to one durable process. +func TestSendClientEventRequestEmitsCorrelationID(t *testing.T) { + t.Parallel() + + const innerKey = "channel/001122" + + conn, mb, _ := newTestConnector(t, nil) + result := conn.Receive( + t.Context(), &SendClientEventRequest{ + Message: &keyedServerMessage{ + key: innerKey, + payload: []byte("channel-event"), + }, + }, &fakeEgressExec{}, + ) + require.NoError(t, result.Err()) + + mb.mu.Lock() + require.Len(t, mb.mailboxes["server-1"], 1) + envelope, ok := proto.Clone( + mb.mailboxes["server-1"][0], + ).(*mailboxpb.Envelope) + require.True(t, ok) + mb.mu.Unlock() + + require.Equal(t, innerKey, envelope.GetRpc().GetCorrelationId()) +} diff --git a/serverconn/heartbeat.go b/serverconn/heartbeat.go index 1a5d4e4e9..c13531f5f 100644 --- a/serverconn/heartbeat.go +++ b/serverconn/heartbeat.go @@ -118,7 +118,7 @@ func (a *ServerConnectionActor) sendHeartbeatOnce(ctx context.Context) error { Kind: mailboxpb.RpcMeta_KIND_EVENT, Service: HeartbeatService, Method: HeartbeatMethod, - ReplyTo: a.cfg.LocalMailboxID, + ReplyTo: a.cfg.replyMailboxID(), }, } diff --git a/serverconn/inbound_version.go b/serverconn/inbound_version.go index 7ee2a20e2..519e026d9 100644 --- a/serverconn/inbound_version.go +++ b/serverconn/inbound_version.go @@ -1,16 +1,19 @@ package serverconn import ( + "fmt" + mailboxconn "github.com/lightninglabs/wavelength/mailbox/conn" mailboxpb "github.com/lightninglabs/wavelength/mailbox/pb" ) // validateInboundEnvelope checks that an inbound server envelope carries the -// mailbox transport and Ark protocol versions bound to this runtime. It -// returns a typed permanent version StatusError on mismatch so the ingress -// loop refuses to acknowledge or dispatch the envelope and the connector can -// classify the failure as permanent. A nil return means the envelope is -// compatible and may be delivered. +// mailbox transport and Ark protocol versions bound to this runtime and, when +// present, names its effective reply mailbox. It returns a typed permanent +// version StatusError on version mismatch so the ingress loop refuses to +// acknowledge or dispatch the envelope and the connector can classify the +// failure as permanent. A nil return means the envelope is compatible and may +// be delivered. // // There is no legacy fallback: an inbound Ark version of zero is treated as a // mismatch like any other wrong version. The client and operator are deployed @@ -42,6 +45,13 @@ func (a *ServerConnectionActor) validateInboundEnvelope( ) } + recipient := env.GetRecipient() + if recipient != "" && recipient != a.cfg.replyMailboxID() { + return fmt.Errorf("inbound envelope recipient %q does not "+ + "match reply mailbox %q", recipient, + a.cfg.replyMailboxID()) + } + return nil } diff --git a/serverconn/ingress.go b/serverconn/ingress.go index 8a2b58a4b..350bc4f7f 100644 --- a/serverconn/ingress.go +++ b/serverconn/ingress.go @@ -56,7 +56,7 @@ func (a *ServerConnectionActor) ingressLoop(ctx context.Context, state AckState) { a.log.InfoS(ctx, "Ingress loop starting", - slog.String("mailbox_id", a.cfg.LocalMailboxID), + slog.String("mailbox_id", a.cfg.replyMailboxID()), ) var failCount int @@ -506,7 +506,7 @@ func (a *ServerConnectionActor) pullPhase(ctx context.Context, state *AckState, // logIngressExit emits the common ingress shutdown log line. func (a *ServerConnectionActor) logIngressExit(ctx context.Context) { a.log.InfoS(ctx, "Ingress loop exiting", - slog.String("mailbox_id", a.cfg.LocalMailboxID), + slog.String("mailbox_id", a.cfg.replyMailboxID()), ) } @@ -535,7 +535,7 @@ func (a *ServerConnectionActor) pullBatchWithWait(ctx context.Context, error) { resp, err := a.cfg.Edge.Pull(ctx, &mailboxpb.PullRequest{ - MailboxId: a.cfg.LocalMailboxID, + MailboxId: a.cfg.replyMailboxID(), MaxEnvelopes: a.cfg.PullMaxEnvelopes, WaitTimeoutMs: uint32(wait.Milliseconds()), Cursor: cursor, @@ -809,7 +809,7 @@ func (a *ServerConnectionActor) ackRemote( ) error { resp, err := a.cfg.Edge.AckUpTo(ctx, &mailboxpb.AckUpToRequest{ - MailboxId: a.cfg.LocalMailboxID, + MailboxId: a.cfg.replyMailboxID(), Cursor: cursor, }) @@ -821,7 +821,7 @@ func (a *ServerConnectionActor) ackRemote( func (a *ServerConnectionActor) loadCheckpoint(ctx context.Context) (AckState, error) { - actorID := DurableActorID(a.cfg.LocalMailboxID) + actorID := a.runtimeID() checkpoint, err := a.cfg.Store.LoadCheckpoint(ctx, actorID) if err != nil { @@ -830,6 +830,15 @@ func (a *ServerConnectionActor) loadCheckpoint(ctx context.Context) (AckState, if checkpoint == nil { return AckState{}, nil } + if checkpoint.ActorID != actorID { + return AckState{}, fmt.Errorf("checkpoint actor ID %q does "+ + "not match ingress runtime %q", checkpoint.ActorID, + actorID) + } + if checkpoint.StateType != ackStateType { + return AckState{}, fmt.Errorf("checkpoint state type %q does "+ + "not match %q", checkpoint.StateType, ackStateType) + } var state AckState stateReader := bytes.NewReader(checkpoint.StateData) @@ -963,10 +972,9 @@ func (a *ServerConnectionActor) runFoldedDispatch(ctx context.Context, // skip it. Everything else in the closure derives from the caller's // state and is safe to redo. ctx = withDeliveredOutsideTx(ctx) - ctx = context.WithValue(ctx, ingressScopeKey{}, ingressScope{ - local: a.cfg.LocalMailboxID, - remote: a.cfg.RemoteMailboxID, - }) + ctx = context.WithValue( + ctx, ingressScopeKey{}, a.ingressEvidenceScope(), + ) var ( newState AckState @@ -1410,7 +1418,7 @@ func (a *ServerConnectionActor) saveCheckpointTo(ctx context.Context, return err } - actorID := DurableActorID(a.cfg.LocalMailboxID) + actorID := a.runtimeID() return store.SaveCheckpoint(ctx, actor.CheckpointParams{ ActorID: actorID, diff --git a/serverconn/ingress_error_test.go b/serverconn/ingress_error_test.go index db5328f68..a8a754693 100644 --- a/serverconn/ingress_error_test.go +++ b/serverconn/ingress_error_test.go @@ -196,6 +196,48 @@ func TestAckRemote_StatusFailure(t *testing.T) { require.Contains(t, stErr.Error(), "ack failed") } +// TestIngressUsesSeparateReplyMailbox verifies Pull and AckUpTo use the +// connector's isolated inbound mailbox instead of its sender identity. +func TestIngressUsesSeparateReplyMailbox(t *testing.T) { + t.Parallel() + + var pulled, acknowledged string + edge := &mailboxClientStub{ + pullFn: func(_ context.Context, request *mailboxpb.PullRequest, + _ ...grpc.CallOption) (*mailboxpb.PullResponse, error) { + + pulled = request.GetMailboxId() + + return &mailboxpb.PullResponse{ + Status: &mailboxpb.Status{ + Ok: true, + }, + }, nil + }, + ackFn: func(_ context.Context, + request *mailboxpb.AckUpToRequest, + _ ...grpc.CallOption) (*mailboxpb.AckUpToResponse, + error) { + + acknowledged = request.GetMailboxId() + + return &mailboxpb.AckUpToResponse{ + Status: &mailboxpb.Status{ + Ok: true, + }, + }, nil + }, + } + actor := newErrorPathActor(edge, newMemCheckpointStore()) + actor.cfg.ReplyMailboxID = "client-channel-1" + + _, _, err := actor.pullBatch(t.Context(), 0) + require.NoError(t, err) + require.NoError(t, actor.ackRemote(t.Context(), 1)) + require.Equal(t, "client-channel-1", pulled) + require.Equal(t, "client-channel-1", acknowledged) +} + // TestIsIngressShutdownErr verifies expected shutdown cancellation is // distinguished from retryable ingress failures. func TestIsIngressShutdownErr(t *testing.T) { @@ -286,6 +328,30 @@ func TestLoadCheckpoint_Errors(t *testing.T) { _, err = decodeErrActor.loadCheckpoint(t.Context()) require.Error(t, err) + + wrongActor := newErrorPathActor( + edge, &checkpointLoadStore{ + memCheckpointStore: newMemCheckpointStore(), + loadCheckpoint: &actor.Checkpoint{ + ActorID: "serverconn-another-mailbox", + StateType: ackStateType, + }, + }, + ) + _, err = wrongActor.loadCheckpoint(t.Context()) + require.ErrorContains(t, err, "does not match ingress runtime") + + wrongType := newErrorPathActor( + edge, &checkpointLoadStore{ + memCheckpointStore: newMemCheckpointStore(), + loadCheckpoint: &actor.Checkpoint{ + ActorID: "serverconn-client-1", + StateType: "AnotherState", + }, + }, + ) + _, err = wrongType.loadCheckpoint(t.Context()) + require.ErrorContains(t, err, "does not match \"AckState\"") } // TestSaveCheckpoint_Error verifies saveCheckpoint surfaces store save errors. diff --git a/serverconn/ingress_namespace_test.go b/serverconn/ingress_namespace_test.go new file mode 100644 index 000000000..d6cc406e4 --- /dev/null +++ b/serverconn/ingress_namespace_test.go @@ -0,0 +1,140 @@ +package serverconn + +import ( + "context" + "testing" + + mailboxconn "github.com/lightninglabs/wavelength/mailbox/conn" + mailboxpb "github.com/lightninglabs/wavelength/mailbox/pb" + "github.com/stretchr/testify/require" +) + +// recordingQuarantineStore records the lane selected for startup recovery. +type recordingQuarantineStore struct { + *memCheckpointStore + listedLanes []string +} + +// newRecordingQuarantineStore creates an empty recovery-listing test store. +func newRecordingQuarantineStore() *recordingQuarantineStore { + return &recordingQuarantineStore{ + memCheckpointStore: newMemCheckpointStore(), + } +} + +// QuarantineIngress satisfies the ingress evidence store contract. +func (s *recordingQuarantineStore) QuarantineIngress(context.Context, + mailboxconn.IngressQuarantine) error { + + return nil +} + +// ListIngressQuarantine records the recovery namespace selected by ingress. +func (s *recordingQuarantineStore) ListIngressQuarantine(_ context.Context, + lane string) ([]mailboxconn.IngressQuarantine, error) { + + s.listedLanes = append(s.listedLanes, lane) + + return nil, nil +} + +// NoteIngressQuarantineAttempt satisfies the ingress evidence store contract. +func (s *recordingQuarantineStore) NoteIngressQuarantineAttempt(context.Context, + string) error { + + return nil +} + +// DeleteIngressQuarantine satisfies the ingress evidence store contract. +func (s *recordingQuarantineStore) DeleteIngressQuarantine(context.Context, + string) error { + + return nil +} + +// scopedReceiptID derives an occurrence receipt through the connector's +// configured ingress-evidence namespace. +func scopedReceiptID(t *testing.T, conn *ServerConnectionActor, + env *mailboxpb.Envelope) string { + + t.Helper() + ctx := context.WithValue( + t.Context(), ingressScopeKey{}, conn.ingressEvidenceScope(), + ) + ctx, err := withEventReceipt(ctx, env) + require.NoError(t, err) + id, ok := mailboxconn.IngressReceiptFromContext(ctx) + require.True(t, ok) + + return id +} + +// TestIngressEvidenceUsesReplyMailboxNamespace proves independent reply +// streams cannot alias receipts, quarantine limits, or recovery listings when +// their authenticated local and remote identities are identical. +func TestIngressEvidenceUsesReplyMailboxNamespace(t *testing.T) { + t.Parallel() + + env := &mailboxpb.Envelope{ + MsgId: "delivery-v1:12345678-1234-4234-8234-123456789abc", + Sender: "shared-remote", + Rpc: &mailboxpb.RpcMeta{ + Kind: mailboxpb.RpcMeta_KIND_EVENT, + Service: "test.Service", + Method: "Event", + }, + } + store := newRecordingQuarantineStore() + newConnector := func(reply string) *ServerConnectionActor { + cfg := DefaultConnectorConfig() + cfg.LocalMailboxID = "shared-local" + cfg.RemoteMailboxID = "shared-remote" + cfg.ReplyMailboxID = reply + cfg.Store = store + + return NewServerConnectionActor(cfg) + } + + first := newConnector("reply-one") + second := newConnector("reply-two") + firstLane := first.quarantineLane() + secondLane := second.quarantineLane() + + require.NotEqual( + t, scopedReceiptID(t, first, env), + scopedReceiptID(t, second, env), + ) + require.NotEqual(t, firstLane, secondLane) + + first.retryQuarantinedIngress(t.Context(), store) + second.retryQuarantinedIngress(t.Context(), store) + require.Equal(t, []string{firstLane, secondLane}, store.listedLanes) +} + +// TestValidateInboundEnvelopeReplyMailbox rejects explicitly misaddressed +// envelopes while preserving compatibility with legacy envelopes that omitted +// the recipient field. +func TestValidateInboundEnvelopeReplyMailbox(t *testing.T) { + t.Parallel() + + cfg := DefaultConnectorConfig() + cfg.LocalMailboxID = "shared-local" + cfg.RemoteMailboxID = "shared-remote" + cfg.ReplyMailboxID = "reply-one" + cfg.ArkProtocolVersion = 1 + conn := NewServerConnectionActor(cfg) + env := &mailboxpb.Envelope{ + ProtocolVersion: cfg.MailboxProtocolVersion, + ArkProtocolVersion: cfg.ArkProtocolVersion, + Recipient: "reply-two", + } + + err := conn.validateInboundEnvelope(env) + require.ErrorContains(t, err, "does not match reply mailbox") + + env.Recipient = cfg.ReplyMailboxID + require.NoError(t, conn.validateInboundEnvelope(env)) + + env.Recipient = "" + require.NoError(t, conn.validateInboundEnvelope(env)) +} diff --git a/serverconn/ingress_quarantine.go b/serverconn/ingress_quarantine.go index e5f1fd34e..5f0c3bf89 100644 --- a/serverconn/ingress_quarantine.go +++ b/serverconn/ingress_quarantine.go @@ -31,12 +31,13 @@ func (e *poisonEnvelopeError) Unwrap() error { return e.err } // ingressQuarantineKey exposes only the active fold's evidence store. type ingressQuarantineKey struct{} -// quarantineLane identifies the configured peer and local mailbox without +// quarantineLane identifies the configured peer and reply mailbox without // relying on untrusted envelope routing fields. func (a *ServerConnectionActor) quarantineLane() string { + ingressScope := a.ingressEvidenceScope() scope := fmt.Appendf( - nil, "%d:%s%s", len(a.cfg.LocalMailboxID), a.cfg.LocalMailboxID, - a.cfg.RemoteMailboxID, + nil, "%d:%s%s", len(ingressScope.reply), ingressScope.reply, + ingressScope.remote, ) digest := sha256.Sum256(scope) @@ -161,10 +162,8 @@ func (a *ServerConnectionActor) retryQuarantinedIngress(ctx context.Context, "is unavailable") } txCtx = context.WithValue( - txCtx, ingressScopeKey{}, ingressScope{ - local: a.cfg.LocalMailboxID, - remote: a.cfg.RemoteMailboxID, - }, + txCtx, ingressScopeKey{}, + a.ingressEvidenceScope(), ) txCtx, err := withEventReceipt(txCtx, env) if err != nil { diff --git a/serverconn/ingress_receipts.go b/serverconn/ingress_receipts.go index 99eb81105..8e8e34897 100644 --- a/serverconn/ingress_receipts.go +++ b/serverconn/ingress_receipts.go @@ -19,8 +19,18 @@ const ingressReceiptPruneInterval = time.Hour // identities. Only the transactional ingress path installs this scope. type ingressScopeKey struct{} -// ingressScope fixes local trust-domain routing independently of peer fields. -type ingressScope struct{ local, remote string } +// ingressScope fixes reply and remote trust-domain routing independently of +// peer-controlled envelope fields. +type ingressScope struct{ reply, remote string } + +// ingressEvidenceScope binds receipts and quarantine to the mailbox stream +// whose cursor the connector advances. +func (a *ServerConnectionActor) ingressEvidenceScope() ingressScope { + return ingressScope{ + reply: a.cfg.replyMailboxID(), + remote: a.cfg.RemoteMailboxID, + } +} // withEventReceipt attaches a producer-persisted delivery occurrence ID to // asynchronous events. Legacy body-derived IDs and operation idempotency keys @@ -38,7 +48,7 @@ func withEventReceipt(ctx context.Context, return ctx, nil } fields := []string{ - "ingress-event/v1", scope.local, scope.remote, env.Sender, + "ingress-event/v1", scope.reply, scope.remote, env.Sender, env.Rpc.Service, env.Rpc.Method, env.MsgId, } encoded, err := json.Marshal(fields) diff --git a/serverconn/ingress_receipts_test.go b/serverconn/ingress_receipts_test.go index 9428ea563..aa23b81fc 100644 --- a/serverconn/ingress_receipts_test.go +++ b/serverconn/ingress_receipts_test.go @@ -23,7 +23,7 @@ func TestIngressReceiptScopeAndCompatibility(t *testing.T) { Method: "method", }, } - scope := ingressScope{local: "local", remote: "remote"} + scope := ingressScope{reply: "local", remote: "remote"} receipt := func(scope ingressScope, env *mailboxpb.Envelope) string { ctx := context.WithValue( context.Background(), ingressScopeKey{}, scope, @@ -38,11 +38,11 @@ func TestIngressReceiptScopeAndCompatibility(t *testing.T) { require.NotEmpty(t, original) for _, changed := range []ingressScope{ { - local: "other", + reply: "other", remote: "remote", }, { - local: "local", + reply: "local", remote: "other", }, } { diff --git a/serverconn/runtime.go b/serverconn/runtime.go index 8f1f0f084..9d807b592 100644 --- a/serverconn/runtime.go +++ b/serverconn/runtime.go @@ -10,10 +10,10 @@ import ( mailboxpb "github.com/lightninglabs/wavelength/mailbox/pb" ) -// DurableActorID returns the durable actor mailbox ID used for serverconn -// ingress checkpointing and egress mailbox persistence. -func DurableActorID(localMailboxID string) string { - return "serverconn-" + localMailboxID +// DurableActorID returns the durable actor ID bound to the effective ingress +// mailbox used for checkpointing and egress persistence. +func DurableActorID(replyMailboxID string) string { + return "serverconn-" + replyMailboxID } // Runtime embeds a DurableActor for serverconn egress and wires it together @@ -69,8 +69,8 @@ func NewRuntime(cfg ConnectorConfig) (*Runtime, error) { durableCfg := actor.DefaultDurableTxActorConfig[ ServerConnMsg, ServerConnResp, egressTx, ]( - DurableActorID(cfg.LocalMailboxID), connector, - connector.bindStores, cfg.Store, cfg.Codec, + connector.runtimeID(), connector, connector.bindStores, + cfg.Store, cfg.Codec, ) durableCfg.Log = cfg.Log diff --git a/serverconn/runtime_test.go b/serverconn/runtime_test.go index 6d4d03815..3d605913a 100644 --- a/serverconn/runtime_test.go +++ b/serverconn/runtime_test.go @@ -120,6 +120,34 @@ func TestNewRuntime_DefaultCodec(t *testing.T) { ) } +// TestNewRuntimeReplyMailboxNamespace verifies two independent remote services +// derive distinct durable state from their distinct ingress mailboxes. +func TestNewRuntimeReplyMailboxNamespace(t *testing.T) { + t.Parallel() + + mb := newInMemoryMailbox() + baseCfg := newTestConnectorConfig(mb, newMemCheckpointStore()) + baseCfg.ReplyMailboxID = "lumos-client-1" + + lumosRuntime, err := NewRuntime(baseCfg) + require.NoError(t, err) + require.Equal( + t, DurableActorID(baseCfg.ReplyMailboxID), + lumosRuntime.Ref().ID(), + ) + + swapCfg := baseCfg + swapCfg.ReplyMailboxID = "swap-client-1" + swapCfg.RemoteMailboxID = "swap-server-1" + swapRuntime, err := NewRuntime(swapCfg) + require.NoError(t, err) + require.Equal( + t, DurableActorID(swapCfg.ReplyMailboxID), + swapRuntime.Ref().ID(), + ) + require.NotEqual(t, lumosRuntime.Ref().ID(), swapRuntime.Ref().ID()) +} + // TestRuntime_StartStop verifies runtime lifecycle methods run and return // promptly when the parent context is cancelled. func TestRuntime_StartStop(t *testing.T) { diff --git a/serverconn/types.go b/serverconn/types.go index 0d047adbd..3a0f1b279 100644 --- a/serverconn/types.go +++ b/serverconn/types.go @@ -127,11 +127,17 @@ type ConnectorConfig struct { // providing Send, Pull, and AckUpTo operations. Edge mailboxpb.MailboxServiceClient - // LocalMailboxID is this client's mailbox identifier. Inbound - // envelopes are pulled from this mailbox, and it is set as the - // sender on outbound envelopes. + // LocalMailboxID is this client's authenticated mailbox identity. It is + // set as the sender on outbound envelopes and is also the default reply + // mailbox when ReplyMailboxID is empty. LocalMailboxID string + // ReplyMailboxID isolates this connector's inbound traffic from other + // connectors using the same authenticated identity. Replies name this + // mailbox, ingress pulls and acknowledges it, and its value derives the + // durable runtime and checkpoint ID. Empty uses LocalMailboxID. + ReplyMailboxID string + // RemoteMailboxID is the remote server's mailbox identifier. Outbound // envelopes are addressed to this mailbox. RemoteMailboxID string @@ -399,6 +405,15 @@ func (c *ConnectorConfig) mergeAuthHeaders( return merged } +// replyMailboxID returns the mailbox dedicated to replies and ingress. +func (c *ConnectorConfig) replyMailboxID() string { + if c.ReplyMailboxID != "" { + return c.ReplyMailboxID + } + + return c.LocalMailboxID +} + // DefaultEgressWorkers is the default size of the egress worker pool. It is // greater than one so the round and out-of-round actors can push outbound sends // concurrently out of the box; per-session ordering still holds via the diff --git a/serverconn/unary_facade.go b/serverconn/unary_facade.go index 5cd01a7be..319f55461 100644 --- a/serverconn/unary_facade.go +++ b/serverconn/unary_facade.go @@ -96,16 +96,16 @@ func (f *UnaryFacade) SendRPC(ctx context.Context, } } - // Defaulting the correlation ID to the idempotency key means a retry - // reuses the abandoned attempt's correlation ID too. That is - // deliberate: SendRPC registers the waiter before it sends, so an - // answer to the abandoned attempt that lands after the retry is on the - // wire is delivered to the retry's waiter instead of being acked into - // the void. Retries of one logical request are sequential by - // construction, so the shared ID never spans two live waiters. + // Correlation identifies one transport attempt, while idempotency + // identifies the logical operation across attempts. Reusing the + // idempotency key here would also reuse the server response's mailbox + // message ID. Once an earlier response has been acknowledged, the + // mailbox tombstone would suppress that cached response and leave the + // retry waiting forever. The request message ID is already fresh for + // every send, so it is also a suitable default correlation ID. correlationID := opts.CorrelationID if correlationID == "" { - correlationID = idempotencyKey + correlationID = msgID } // Pre-register the response waiter before sending so a fast response @@ -138,7 +138,7 @@ func (f *UnaryFacade) SendRPC(ctx context.Context, Service: method.Service, Method: method.Method, CorrelationId: correlationID, - ReplyTo: cfg.LocalMailboxID, + ReplyTo: cfg.replyMailboxID(), }, } diff --git a/serverconn/unary_facade_test.go b/serverconn/unary_facade_test.go index 0b5be679a..22dd0b358 100644 --- a/serverconn/unary_facade_test.go +++ b/serverconn/unary_facade_test.go @@ -46,6 +46,7 @@ func TestUnaryFacade_SendRPC(t *testing.T) { require.Len(t, envs, 1) require.Equal(t, "client-1", envs[0].Sender) require.Equal(t, "server-1", envs[0].Recipient) + require.Equal(t, "client-1", envs[0].GetRpc().GetReplyTo()) require.Equal(t, mailboxpb.RpcMeta_KIND_REQUEST, envs[0].Rpc.Kind, ) @@ -56,6 +57,34 @@ func TestUnaryFacade_SendRPC(t *testing.T) { ) } +// TestUnaryFacadeSeparateReplyMailbox verifies one connector can retain its +// authenticated sender identity while receiving replies on an isolated +// mailbox. +func TestUnaryFacadeSeparateReplyMailbox(t *testing.T) { + t.Parallel() + + mailbox := newInMemoryMailbox() + cfg := newTestConnectorConfig(mailbox, newMemCheckpointStore()) + cfg.ReplyMailboxID = "client-channel-1" + facade := NewUnaryFacade(NewServerConnectionActor(cfg)) + + _, err := facade.SendRPC( + t.Context(), mailboxrpc.ServiceMethod{ + Service: "test.Svc", Method: "GetInfo", + }, wrapperspb.String("hello"), mailboxrpc.RPCOptions{}, + ) + require.NoError(t, err) + + mailbox.mu.Lock() + envelopes := mailbox.mailboxes["server-1"] + mailbox.mu.Unlock() + require.Len(t, envelopes, 1) + require.Equal(t, "client-1", envelopes[0].GetSender()) + require.Equal( + t, "client-channel-1", envelopes[0].GetRpc().GetReplyTo(), + ) +} + // TestUnaryFacade_SendRPC_ExplicitOptions verifies that caller-provided // correlation ID and idempotency key are preserved. func TestUnaryFacade_SendRPC_ExplicitOptions(t *testing.T) { diff --git a/serverconn/unary_inflight_test.go b/serverconn/unary_inflight_test.go index eeeef248a..37be38551 100644 --- a/serverconn/unary_inflight_test.go +++ b/serverconn/unary_inflight_test.go @@ -33,9 +33,9 @@ func newBoundedTestFacade(t *testing.T, } // TestSendRPCReusesCallerIdempotencyKey pins that the transport forwards a -// caller-owned key verbatim on every attempt while still rotating the message -// ID. The stable key is what lets the operator recognize a retry, and the -// fresh message ID is what keeps the two sends distinct on the wire. +// caller-owned key verbatim while rotating both message and correlation IDs. +// A fresh correlation lets the operator re-enqueue a cached response after an +// earlier attempt's response has already been acknowledged. func TestSendRPCReusesCallerIdempotencyKey(t *testing.T) { t.Parallel() @@ -43,6 +43,7 @@ func TestSendRPCReusesCallerIdempotencyKey(t *testing.T) { const key = "idem-one-logical-request" opts := mailboxrpc.RPCOptions{IdempotencyKey: key} + correlationIDs := make(map[string]struct{}) for i := 0; i < 3; i++ { result, err := facade.SendRPC( @@ -51,10 +52,13 @@ func TestSendRPCReusesCallerIdempotencyKey(t *testing.T) { ) require.NoError(t, err) require.Equal(t, key, result.IdempotencyKey) - - // A retry reuses the correlation ID too, so an answer to the - // abandoned attempt lands on the retry's waiter. - require.Equal(t, key, result.CorrelationID) + require.NotEmpty(t, result.CorrelationID) + _, duplicate := correlationIDs[result.CorrelationID] + require.False( + t, duplicate, "correlation ID %s reused", + result.CorrelationID, + ) + correlationIDs[result.CorrelationID] = struct{}{} } mb.mu.Lock() @@ -66,7 +70,11 @@ func TestSendRPCReusesCallerIdempotencyKey(t *testing.T) { msgIDs := make(map[string]struct{}, len(envs)) for _, env := range envs { require.Equal(t, key, env.IdempotencyKey) - require.Equal(t, key, env.Rpc.CorrelationId) + _, ok := correlationIDs[env.Rpc.CorrelationId] + require.True( + t, ok, "unknown correlation ID %s", + env.Rpc.CorrelationId, + ) require.NotEmpty(t, env.MsgId) _, dup := msgIDs[env.MsgId] diff --git a/swapclientserver/service.go b/swapclientserver/service.go index 0be0c00aa..1a5985029 100644 --- a/swapclientserver/service.go +++ b/swapclientserver/service.go @@ -168,6 +168,12 @@ type swapClientService struct { // and duplicate in-flight checks before swap creation mutates remote // swapdk-server state. chainParams *chaincfg.Params + + // workerRetryDelay is the pause between daemon-owned attempts to resume + // a durable swap that remains pending after a transient driver error. + // Keeping the delay on the service makes the retry loop deterministic + // in tests without moving retry policy into the swap FSM. + workerRetryDelay time.Duration } // receiveScanKey orders durable receives by creation time and payment hash. @@ -194,6 +200,8 @@ const ( receiveRefillRetryDelay = time.Second ) +const defaultWorkerRetryDelay = time.Second + // operatorPubKeyFetcher returns the current Ark operator pubkey. It exists so // daemon-hosted swap clients can bypass the cached GetInfo snapshot when they // construct fresh vHTLC policies. @@ -720,6 +728,7 @@ func newSwapClientService(ctx context.Context, rpcServer *waved.RPCServer, receiveMinAmount: minAmount, payMinAmount: minAmount, chainParams: chainParams, + workerRetryDelay: defaultWorkerRetryDelay, } service.pendingReceiveSet = make(map[string]struct{}) @@ -2280,18 +2289,18 @@ func (s *swapClientService) startPayWorker(hash lntypes.Hash) { defer s.markInactive(key) defer s.publishHash(hash) - session, err := s.client.ResumePayViaLightning(s.rootCtx, hash) - if err != nil { - s.log.Warnf("unable to resume pay swap %s: %v", key, - err) + s.runSwapWorker(hash, "pay", func(ctx context.Context) error { + session, err := s.client.ResumePayViaLightning( + ctx, hash, + ) + if err != nil { + return err + } - return - } + _, err = session.Wait(ctx) - _, err = session.Wait(s.rootCtx) - if err != nil && !errors.Is(err, context.Canceled) { - s.log.Warnf("pay swap %s stopped: %v", key, err) - } + return err + }) }) } @@ -2331,21 +2340,76 @@ func (s *swapClientService) runReceiveWorker(hash lntypes.Hash, key string) { defer s.finishReceiveWorker(key) defer s.publishHash(hash) - session, err := s.client.ResumeReceiveViaLightning( - s.rootCtx, hash, + s.runSwapWorker( + hash, "receive", + func(ctx context.Context) error { + session, err := + s.client.ResumeReceiveViaLightning( + ctx, hash, + ) + if err != nil { + return err + } + + _, err = session.Wait(ctx) + + return err + }, ) - if err != nil { - s.log.Warnf("unable to resume receive swap %s: %v", key, - err) + }) +} + +// runSwapWorker drives one durable swap until the SDK reports success, the +// persisted FSM becomes terminal, or the daemon stops. A Wait or resume error +// alone is not terminal: transport loss can interrupt the process-local driver +// while the durable FSM remains resumable. +func (s *swapClientService) runSwapWorker(hash lntypes.Hash, direction string, + drive func(context.Context) error) { + + key := hex.EncodeToString(hash[:]) + for { + err := drive(s.rootCtx) + if err == nil || errors.Is(err, context.Canceled) || + s.rootCtx.Err() != nil { + return + } + summary, summaryErr := s.client.GetSwapSummary(s.rootCtx, hash) + if errors.Is(summaryErr, swaps.ErrSwapSummaryNotFound) { + return + } + if summaryErr == nil && !summary.Pending { return } - _, err = session.Wait(s.rootCtx) - if err != nil && !errors.Is(err, context.Canceled) { - s.log.Warnf("receive swap %s stopped: %v", key, err) + if summaryErr != nil { + s.log.Warnf("%s swap %s stopped and durable state "+ + "could not be checked: %v (driver error: %v)", + direction, key, summaryErr, err) + } else { + s.log.Warnf("%s swap %s stopped while still pending; "+ + "retrying: %v", direction, key, err) } - }) + + delay := s.workerRetryDelay + if delay <= 0 { + delay = defaultWorkerRetryDelay + } + timer := time.NewTimer(delay) + select { + case <-s.rootCtx.Done(): + if !timer.Stop() { + select { + case <-timer.C: + default: + } + } + + return + + case <-timer.C: + } + } } // markActive records that the daemon has an in-process worker responsible for diff --git a/swapclientserver/service_test.go b/swapclientserver/service_test.go index 2c84074d8..2d2653a99 100644 --- a/swapclientserver/service_test.go +++ b/swapclientserver/service_test.go @@ -483,6 +483,39 @@ func TestStartReceiveReleasesReservationOnCreationFailure(t *testing.T) { require.True(t, service.reserveReceiveWorker()) } +// TestReceiveWorkerRetriesWhileDurableSwapIsPending verifies a transient +// process-local Wait failure does not strand a resumable receive FSM until the +// daemon restarts. The worker keeps ownership across the retry and resumes the +// same payment hash once more. +func TestReceiveWorkerRetriesWhileDurableSwapIsPending(t *testing.T) { + t.Parallel() + + receiveHash := testHash(3) + fakeClient := newFakeSwapRuntime(swaps.SwapSummary{ + Direction: swaps.SwapDirectionReceive, + PaymentHash: receiveHash, + State: "claim_initiated", + Pending: true, + }) + fakeClient.receiveResumeSessions = []receiveSwapSession{ + &fakeReceiveSession{ + hash: receiveHash, + waitErr: errors.New("temporary mailbox disconnect"), + }, + &fakeReceiveSession{ + hash: receiveHash, + }, + } + service := newTestSwapClientService(fakeClient) + service.workerRetryDelay = 10 * time.Millisecond + defer service.cancel() + + service.startReceiveWorker(receiveHash) + fakeClient.awaitReceiveResume(t, receiveHash) + fakeClient.awaitReceiveResume(t, receiveHash) + require.Equal(t, 2, fakeClient.receiveResumeCount(receiveHash)) +} + // TestChainParamsForNetworkAcceptsTestNet4 verifies the swapruntime daemon // subserver accepts every network string the main daemon config advertises. func TestChainParamsForNetworkAcceptsTestNet4(t *testing.T) { @@ -1967,6 +2000,7 @@ type fakeSwapRuntime struct { payResumeCalls map[lntypes.Hash]int receiveResumeCalls map[lntypes.Hash]int receiveDone map[lntypes.Hash]chan struct{} + receiveResumeSessions []receiveSwapSession payResumeCh chan lntypes.Hash receiveResumeCh chan lntypes.Hash @@ -2066,6 +2100,10 @@ func (f *fakeSwapRuntime) ResumeReceiveViaLightning(ctx context.Context, f.receiveResumeCalls[hash]++ f.receiveResumeCh <- hash + resumeIndex := f.receiveResumeCalls[hash] - 1 + if resumeIndex < len(f.receiveResumeSessions) { + return f.receiveResumeSessions[resumeIndex], nil + } return &fakeReceiveSession{hash: hash, done: f.receiveDone[hash]}, nil } @@ -2269,6 +2307,7 @@ type fakeReceiveSession struct { done <-chan struct{} hash lntypes.Hash invoice string + waitErr error } func (f *fakeReceiveSession) PaymentHash() lntypes.Hash { @@ -2283,9 +2322,13 @@ func (f *fakeReceiveSession) Invoice() string { func (f *fakeReceiveSession) Wait(ctx context.Context) (*swaps.ReceiveResult, error) { + if f.waitErr != nil { + return nil, f.waitErr + } + select { case <-f.done: - return nil, errors.New("temporary receive failure") + return nil, nil case <-ctx.Done(): } diff --git a/swaprpc/swap.pb.go b/swaprpc/swap.pb.go index 8dcd72034..4ba1a2b24 100644 --- a/swaprpc/swap.pb.go +++ b/swaprpc/swap.pb.go @@ -3090,8 +3090,17 @@ type AuthorizeInSwapRefundRequest struct { RefundSpendPath []byte `protobuf:"bytes,5,opt,name=refund_spend_path,json=refundSpendPath,proto3" json:"refund_spend_path,omitempty"` // checkpoint_psbt is the prepared custom OOR checkpoint PSBT to sign. CheckpointPsbt []byte `protobuf:"bytes,6,opt,name=checkpoint_psbt,json=checkpointPsbt,proto3" json:"checkpoint_psbt,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // ark_psbt spends the checkpoint and commits to the complete refund. + // A client that supplies this packet needs both signatures before submit. + ArkPsbt []byte `protobuf:"bytes,7,opt,name=ark_psbt,json=arkPsbt,proto3" json:"ark_psbt,omitempty"` + // owner_proof binds the wallet's chosen refund destination to this swap + // by authorizing the hash, checkpoint PSBT, Ark PSBT, and refund pubkey. + OwnerProof *SwapOwnerProof `protobuf:"bytes,8,opt,name=owner_proof,json=ownerProof,proto3" json:"owner_proof,omitempty"` + // refund_pubkey is the wallet's fresh x-only receive key. The signer + // rebuilds the full-value destination from this authorized key. + RefundPubkey []byte `protobuf:"bytes,9,opt,name=refund_pubkey,json=refundPubkey,proto3" json:"refund_pubkey,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *AuthorizeInSwapRefundRequest) Reset() { @@ -3166,6 +3175,27 @@ func (x *AuthorizeInSwapRefundRequest) GetCheckpointPsbt() []byte { return nil } +func (x *AuthorizeInSwapRefundRequest) GetArkPsbt() []byte { + if x != nil { + return x.ArkPsbt + } + return nil +} + +func (x *AuthorizeInSwapRefundRequest) GetOwnerProof() *SwapOwnerProof { + if x != nil { + return x.OwnerProof + } + return nil +} + +func (x *AuthorizeInSwapRefundRequest) GetRefundPubkey() []byte { + if x != nil { + return x.RefundPubkey + } + return nil +} + type AuthorizeInSwapRefundResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // signature is the swap server receiver key's tapscript signature. @@ -3173,8 +3203,11 @@ type AuthorizeInSwapRefundResponse struct { // failure_reason is the terminal Lightning payment failure that made the // refund safe to authorize. FailureReason string `protobuf:"bytes,2,opt,name=failure_reason,json=failureReason,proto3" json:"failure_reason,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // payout_signature authorizes the Ark input spending the checkpoint. + // It cannot be substituted for the signature spending the source vHTLC. + PayoutSignature *TaprootScriptSignature `protobuf:"bytes,3,opt,name=payout_signature,json=payoutSignature,proto3" json:"payout_signature,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *AuthorizeInSwapRefundResponse) Reset() { @@ -3221,6 +3254,13 @@ func (x *AuthorizeInSwapRefundResponse) GetFailureReason() string { return "" } +func (x *AuthorizeInSwapRefundResponse) GetPayoutSignature() *TaprootScriptSignature { + if x != nil { + return x.PayoutSignature + } + return nil +} + // ForfeitSignaturePayload is the exact transcript one vHTLC refresh // participant signs after an Ark round assigns connector outputs. type ForfeitSignaturePayload struct { @@ -3966,17 +4006,22 @@ const file_swap_proto_rawDesc = "" + "\n" + "amount_sat\x18\x04 \x01(\x04R\tamountSat\x129\n" + "\n" + - "created_at\x18\x05 \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\"\x9b\x02\n" + + "created_at\x18\x05 \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\"\x95\x03\n" + "\x1cAuthorizeInSwapRefundRequest\x12!\n" + "\fpayment_hash\x18\x01 \x01(\fR\vpaymentHash\x12%\n" + "\x0evhtlc_outpoint\x18\x02 \x01(\tR\rvhtlcOutpoint\x12(\n" + "\x10vhtlc_amount_sat\x18\x03 \x01(\x04R\x0evhtlcAmountSat\x122\n" + "\x15vhtlc_policy_template\x18\x04 \x01(\fR\x13vhtlcPolicyTemplate\x12*\n" + "\x11refund_spend_path\x18\x05 \x01(\fR\x0frefundSpendPath\x12'\n" + - "\x0fcheckpoint_psbt\x18\x06 \x01(\fR\x0echeckpointPsbt\"\x85\x01\n" + + "\x0fcheckpoint_psbt\x18\x06 \x01(\fR\x0echeckpointPsbt\x12\x19\n" + + "\bark_psbt\x18\a \x01(\fR\aarkPsbt\x128\n" + + "\vowner_proof\x18\b \x01(\v2\x17.swaprpc.SwapOwnerProofR\n" + + "ownerProof\x12#\n" + + "\rrefund_pubkey\x18\t \x01(\fR\frefundPubkey\"\xd1\x01\n" + "\x1dAuthorizeInSwapRefundResponse\x12=\n" + "\tsignature\x18\x01 \x01(\v2\x1f.swaprpc.TaprootScriptSignatureR\tsignature\x12%\n" + - "\x0efailure_reason\x18\x02 \x01(\tR\rfailureReason\"\xb0\x04\n" + + "\x0efailure_reason\x18\x02 \x01(\tR\rfailureReason\x12J\n" + + "\x10payout_signature\x18\x03 \x01(\v2\x1f.swaprpc.TaprootScriptSignatureR\x0fpayoutSignature\"\xb0\x04\n" + "\x17ForfeitSignaturePayload\x12\x1d\n" + "\n" + "request_id\x18\x01 \x01(\fR\trequestId\x12!\n" + @@ -4162,41 +4207,43 @@ var file_swap_proto_depIdxs = []int32{ 46, // 37: swaprpc.CreditOperation.updated_at:type_name -> google.protobuf.Timestamp 46, // 38: swaprpc.CreditOperation.completed_at:type_name -> google.protobuf.Timestamp 46, // 39: swaprpc.CreditLedgerEntry.created_at:type_name -> google.protobuf.Timestamp - 45, // 40: swaprpc.AuthorizeInSwapRefundResponse.signature:type_name -> swaprpc.TaprootScriptSignature - 38, // 41: swaprpc.SignInSwapForfeitRequest.payload:type_name -> swaprpc.ForfeitSignaturePayload - 39, // 42: swaprpc.SignInSwapForfeitResponse.signature:type_name -> swaprpc.ForfeitParticipantSignature - 38, // 43: swaprpc.OutSwapForfeitSignatureRequest.payload:type_name -> swaprpc.ForfeitSignaturePayload - 38, // 44: swaprpc.SubmitOutSwapForfeitSignatureRequest.payload:type_name -> swaprpc.ForfeitSignaturePayload - 39, // 45: swaprpc.SubmitOutSwapForfeitSignatureRequest.signature:type_name -> swaprpc.ForfeitParticipantSignature - 6, // 46: swaprpc.SwapService.RequestChannelId:input_type -> swaprpc.RequestChannelIdRequest - 17, // 47: swaprpc.SwapService.CreateInSwap:input_type -> swaprpc.CreateInSwapRequest - 24, // 48: swaprpc.SwapService.QuoteInSwap:input_type -> swaprpc.QuoteInSwapRequest - 28, // 49: swaprpc.SwapService.CreateCredit:input_type -> swaprpc.CreateCreditRequest - 30, // 50: swaprpc.SwapService.RedeemCredit:input_type -> swaprpc.RedeemCreditRequest - 32, // 51: swaprpc.SwapService.ListCredits:input_type -> swaprpc.ListCreditsRequest - 36, // 52: swaprpc.SwapService.AuthorizeInSwapRefund:input_type -> swaprpc.AuthorizeInSwapRefundRequest - 8, // 53: swaprpc.SwapService.AcknowledgeOutSwapHtlc:input_type -> swaprpc.AcknowledgeOutSwapHtlcRequest - 40, // 54: swaprpc.SwapService.SignInSwapForfeit:input_type -> swaprpc.SignInSwapForfeitRequest - 43, // 55: swaprpc.SwapService.SubmitOutSwapForfeitSignature:input_type -> swaprpc.SubmitOutSwapForfeitSignatureRequest - 18, // 56: swaprpc.SwapService.ListRecoverableSwaps:input_type -> swaprpc.ListRecoverableSwapsRequest - 20, // 57: swaprpc.SwapService.GetSwapRecoveryInfo:input_type -> swaprpc.GetSwapRecoveryInfoRequest - 7, // 58: swaprpc.SwapService.RequestChannelId:output_type -> swaprpc.RequestChannelIdResponse - 23, // 59: swaprpc.SwapService.CreateInSwap:output_type -> swaprpc.CreateInSwapResponse - 25, // 60: swaprpc.SwapService.QuoteInSwap:output_type -> swaprpc.QuoteInSwapResponse - 29, // 61: swaprpc.SwapService.CreateCredit:output_type -> swaprpc.CreateCreditResponse - 31, // 62: swaprpc.SwapService.RedeemCredit:output_type -> swaprpc.RedeemCreditResponse - 33, // 63: swaprpc.SwapService.ListCredits:output_type -> swaprpc.ListCreditsResponse - 37, // 64: swaprpc.SwapService.AuthorizeInSwapRefund:output_type -> swaprpc.AuthorizeInSwapRefundResponse - 9, // 65: swaprpc.SwapService.AcknowledgeOutSwapHtlc:output_type -> swaprpc.AcknowledgeOutSwapHtlcResponse - 41, // 66: swaprpc.SwapService.SignInSwapForfeit:output_type -> swaprpc.SignInSwapForfeitResponse - 44, // 67: swaprpc.SwapService.SubmitOutSwapForfeitSignature:output_type -> swaprpc.SubmitOutSwapForfeitSignatureResponse - 19, // 68: swaprpc.SwapService.ListRecoverableSwaps:output_type -> swaprpc.ListRecoverableSwapsResponse - 21, // 69: swaprpc.SwapService.GetSwapRecoveryInfo:output_type -> swaprpc.GetSwapRecoveryInfoResponse - 58, // [58:70] is the sub-list for method output_type - 46, // [46:58] is the sub-list for method input_type - 46, // [46:46] is the sub-list for extension type_name - 46, // [46:46] is the sub-list for extension extendee - 0, // [0:46] is the sub-list for field type_name + 5, // 40: swaprpc.AuthorizeInSwapRefundRequest.owner_proof:type_name -> swaprpc.SwapOwnerProof + 45, // 41: swaprpc.AuthorizeInSwapRefundResponse.signature:type_name -> swaprpc.TaprootScriptSignature + 45, // 42: swaprpc.AuthorizeInSwapRefundResponse.payout_signature:type_name -> swaprpc.TaprootScriptSignature + 38, // 43: swaprpc.SignInSwapForfeitRequest.payload:type_name -> swaprpc.ForfeitSignaturePayload + 39, // 44: swaprpc.SignInSwapForfeitResponse.signature:type_name -> swaprpc.ForfeitParticipantSignature + 38, // 45: swaprpc.OutSwapForfeitSignatureRequest.payload:type_name -> swaprpc.ForfeitSignaturePayload + 38, // 46: swaprpc.SubmitOutSwapForfeitSignatureRequest.payload:type_name -> swaprpc.ForfeitSignaturePayload + 39, // 47: swaprpc.SubmitOutSwapForfeitSignatureRequest.signature:type_name -> swaprpc.ForfeitParticipantSignature + 6, // 48: swaprpc.SwapService.RequestChannelId:input_type -> swaprpc.RequestChannelIdRequest + 17, // 49: swaprpc.SwapService.CreateInSwap:input_type -> swaprpc.CreateInSwapRequest + 24, // 50: swaprpc.SwapService.QuoteInSwap:input_type -> swaprpc.QuoteInSwapRequest + 28, // 51: swaprpc.SwapService.CreateCredit:input_type -> swaprpc.CreateCreditRequest + 30, // 52: swaprpc.SwapService.RedeemCredit:input_type -> swaprpc.RedeemCreditRequest + 32, // 53: swaprpc.SwapService.ListCredits:input_type -> swaprpc.ListCreditsRequest + 36, // 54: swaprpc.SwapService.AuthorizeInSwapRefund:input_type -> swaprpc.AuthorizeInSwapRefundRequest + 8, // 55: swaprpc.SwapService.AcknowledgeOutSwapHtlc:input_type -> swaprpc.AcknowledgeOutSwapHtlcRequest + 40, // 56: swaprpc.SwapService.SignInSwapForfeit:input_type -> swaprpc.SignInSwapForfeitRequest + 43, // 57: swaprpc.SwapService.SubmitOutSwapForfeitSignature:input_type -> swaprpc.SubmitOutSwapForfeitSignatureRequest + 18, // 58: swaprpc.SwapService.ListRecoverableSwaps:input_type -> swaprpc.ListRecoverableSwapsRequest + 20, // 59: swaprpc.SwapService.GetSwapRecoveryInfo:input_type -> swaprpc.GetSwapRecoveryInfoRequest + 7, // 60: swaprpc.SwapService.RequestChannelId:output_type -> swaprpc.RequestChannelIdResponse + 23, // 61: swaprpc.SwapService.CreateInSwap:output_type -> swaprpc.CreateInSwapResponse + 25, // 62: swaprpc.SwapService.QuoteInSwap:output_type -> swaprpc.QuoteInSwapResponse + 29, // 63: swaprpc.SwapService.CreateCredit:output_type -> swaprpc.CreateCreditResponse + 31, // 64: swaprpc.SwapService.RedeemCredit:output_type -> swaprpc.RedeemCreditResponse + 33, // 65: swaprpc.SwapService.ListCredits:output_type -> swaprpc.ListCreditsResponse + 37, // 66: swaprpc.SwapService.AuthorizeInSwapRefund:output_type -> swaprpc.AuthorizeInSwapRefundResponse + 9, // 67: swaprpc.SwapService.AcknowledgeOutSwapHtlc:output_type -> swaprpc.AcknowledgeOutSwapHtlcResponse + 41, // 68: swaprpc.SwapService.SignInSwapForfeit:output_type -> swaprpc.SignInSwapForfeitResponse + 44, // 69: swaprpc.SwapService.SubmitOutSwapForfeitSignature:output_type -> swaprpc.SubmitOutSwapForfeitSignatureResponse + 19, // 70: swaprpc.SwapService.ListRecoverableSwaps:output_type -> swaprpc.ListRecoverableSwapsResponse + 21, // 71: swaprpc.SwapService.GetSwapRecoveryInfo:output_type -> swaprpc.GetSwapRecoveryInfoResponse + 60, // [60:72] is the sub-list for method output_type + 48, // [48:60] is the sub-list for method input_type + 48, // [48:48] is the sub-list for extension type_name + 48, // [48:48] is the sub-list for extension extendee + 0, // [0:48] is the sub-list for field type_name } func init() { file_swap_proto_init() } diff --git a/swaprpc/swap.proto b/swaprpc/swap.proto index 412aea1bb..1799c17f1 100644 --- a/swaprpc/swap.proto +++ b/swaprpc/swap.proto @@ -767,6 +767,18 @@ message AuthorizeInSwapRefundRequest { // checkpoint_psbt is the prepared custom OOR checkpoint PSBT to sign. bytes checkpoint_psbt = 6; + + // ark_psbt spends the checkpoint and commits to the complete refund. + // A client that supplies this packet needs both signatures before submit. + bytes ark_psbt = 7; + + // owner_proof binds the wallet's chosen refund destination to this swap + // by authorizing the hash, checkpoint PSBT, Ark PSBT, and refund pubkey. + SwapOwnerProof owner_proof = 8; + + // refund_pubkey is the wallet's fresh x-only receive key. The signer + // rebuilds the full-value destination from this authorized key. + bytes refund_pubkey = 9; } message AuthorizeInSwapRefundResponse { @@ -776,6 +788,10 @@ message AuthorizeInSwapRefundResponse { // failure_reason is the terminal Lightning payment failure that made the // refund safe to authorize. string failure_reason = 2; + + // payout_signature authorizes the Ark input spending the checkpoint. + // It cannot be substituted for the signature spending the source vHTLC. + TaprootScriptSignature payout_signature = 3; } // ForfeitSignaturePayload is the exact transcript one vHTLC refresh diff --git a/unroll/actor.go b/unroll/actor.go index a8ce884b7..d6a1375db 100644 --- a/unroll/actor.go +++ b/unroll/actor.go @@ -2152,7 +2152,7 @@ func (b *behavior) sourceSpendCallerID(outpoint wire.OutPoint) string { // when a proof output is consumed on chain, and we have to classify what we // are looking at before deciding whether the unroll job is dead. // -// Four cases: +// Five cases: // // 1. The spent output belongs to a known node in our recovery proof. // That proves the parent transaction confirmed, even if txconfirm's @@ -2165,7 +2165,11 @@ func (b *behavior) sourceSpendCallerID(outpoint wire.OutPoint) string { // transaction for fee accounting and complete the exit, including when // an earlier candidate wins the replacement race. // -// 4. Anything else: the watched output was spent by someone else. This can +// 4. The exit policy has an immutable pre-signed final spend and that exact +// transaction spent the target. This is success even when the peer won +// the publication race. +// +// 5. Anything else: the watched output was spent by someone else. This can // happen if the operator cooperatively claims it, if a fraud party // beats us to a signed spend, or if a reorg replays a different // history. In all cases the unroll job cannot finish; drive FailEvent @@ -2216,7 +2220,21 @@ func (b *behavior) handleSpendObserved(ctx context.Context, ) } - // Case 4: neither of the above. Someone else spent the watched output. + // Case 4: some policies, such as Ark channel materialization, bind the + // final transaction before the unroll starts. Either authorized party + // may publish it after CSV maturity. Recognize the exact pre-signed + // txid and record both its broadcast and confirmation so the durable + // actor converges regardless of which participant reached the chain + // first. + matched, err := b.ackPreSignedExitSpend(ctx, ax, msg) + if err != nil { + return fn.Err[Resp](err) + } + if matched { + return fn.Ok[Resp](&AckResp{}) + } + + // Case 5: neither of the above. Someone else spent the watched output. // This happens if the operator cooperatively claimed the VTXO, // if a reorg replaced history, or in fraud scenarios. There is // no way for this unroll to proceed, so terminate with a @@ -2284,6 +2302,137 @@ func (b *behavior) handleSpendObserved(ctx context.Context, return b.handleEvent(ctx, ax, &FailEvent{Reason: reason}) } +// ackPreSignedExitSpend completes an unroll when another authorized party +// publishes the exact immutable final spend supplied by the exit policy. +func (b *behavior) ackPreSignedExitSpend(ctx context.Context, + ax actor.Exec[unrollTx], msg *SpendObservedMsg) (bool, error) { + + // Standard timeout exits have no immutable pre-signed final spend. + // Avoid policy resolution so asset sweep safety cannot prevent a + // foreign spend from terminalizing the job. + if b.exitPolicyKind() == StandardVTXOTimeoutExitPolicyKind { + return false, nil + } + + spentOutpoint := msg.Outpoint + if spentOutpoint == (wire.OutPoint{}) { + spentOutpoint = b.cfg.TargetOutpoint + } + if spentOutpoint != b.cfg.TargetOutpoint { + return false, nil + } + + policy, err := b.resolveExitSpendPolicy(ctx) + if err != nil { + return false, err + } + preSigned, ok := policy.(PreSignedExitSpendPolicy) + if !ok { + return false, nil + } + + tx, err := preSigned.PreSignedSpendTx() + if err != nil { + return false, fmt.Errorf("load pre-signed exit spend: %w", err) + } + if tx == nil || tx.TxHash() != msg.SpendingTxid { + return false, nil + } + if !transactionSpendsOutpoint(tx, b.cfg.TargetOutpoint) { + return false, fmt.Errorf("pre-signed exit spend %s does not "+ + "spend target %s", msg.SpendingTxid, + b.cfg.TargetOutpoint) + } + + // Preserve the transaction itself, not only its txid. Checkpoint replay + // and exit-cost accounting both require the exact final transaction. + b.sweepTx = tx + + state, err := b.currentState() + if err != nil { + return false, err + } + job := stateJob(state) + if !containsHash( + job.PlannerState.ConfirmedTxids, b.cfg.TargetOutpoint.Hash, + ) { + + // A CSV-delayed spend confirmed at H proves its parent + // confirmed no later than H-CSV. Record that conservative upper + // bound instead of H, which would make the already-confirmed + // spend appear immature. + parentHeight := int64(msg.SpendingHeight) - + int64(policy.CSVDelay()) + if parentHeight < 0 { + return false, fmt.Errorf("pre-signed exit spend "+ + "height %d cannot satisfy CSV delay %d", + msg.SpendingHeight, policy.CSVDelay()) + } + + err := b.driveEvent(ctx, ax, &TxConfirmedEvent{ + Txid: b.cfg.TargetOutpoint.Hash, + Height: int32(parentHeight), + }) + if err != nil { + return false, err + } + } + + state, err = b.currentState() + if err != nil { + return false, err + } + job = stateJob(state) + if job.PlannerState.Sweep.Txid.IsSome() { + if job.PlannerState.Sweep.Txid.UnsafeFromSome() != + msg.SpendingTxid { + return false, fmt.Errorf("pre-signed exit spend %s "+ + "conflicts with recorded sweep %s", + msg.SpendingTxid, + job.PlannerState.Sweep.Txid.UnsafeFromSome()) + } + } else { + if err := b.driveEvent(ctx, ax, &SweepBroadcastedEvent{ + Txid: msg.SpendingTxid, + }); err != nil { + return false, err + } + } + + state, err = b.currentState() + if err != nil { + return false, err + } + job = stateJob(state) + if job.PlannerState.Sweep.Status != + unrollplan.SweepStatusConfirmed { + + if err := b.driveEvent(ctx, ax, &TxConfirmedEvent{ + Txid: msg.SpendingTxid, + Height: msg.SpendingHeight, + }); err != nil { + return false, err + } + } + + return true, nil +} + +// transactionSpendsOutpoint reports whether tx consumes the exact outpoint. +func transactionSpendsOutpoint(tx *wire.MsgTx, outpoint wire.OutPoint) bool { + if tx == nil { + return false + } + + for _, txIn := range tx.TxIn { + if txIn != nil && txIn.PreviousOutPoint == outpoint { + return true + } + } + + return false +} + // ackProofOutputSpend records proof-output spend evidence and reports whether // the observation is fully handled. If a proof output is spent by an unknown // transaction, the parent proof tx is still confirmed, but the caller must diff --git a/unroll/actor_test.go b/unroll/actor_test.go index 54e6de445..83165db80 100644 --- a/unroll/actor_test.go +++ b/unroll/actor_test.go @@ -41,6 +41,76 @@ import ( const testTimeout = time.Second +const testPreSignedExitPolicyKind ExitPolicyKind = "test_pre_signed" + +// testPreSignedExitPolicy exposes one immutable final spend for actor tests. +type testPreSignedExitPolicy struct { + tx *wire.MsgTx + csvDelay uint32 +} + +// Kind returns the test policy identity. +func (p *testPreSignedExitPolicy) Kind() ExitPolicyKind { + return testPreSignedExitPolicyKind +} + +// CSVDelay returns the configured relative delay. +func (p *testPreSignedExitPolicy) CSVDelay() uint32 { + return p.csvDelay +} + +// RequiredLockTime reports no absolute timelock. +func (*testPreSignedExitPolicy) RequiredLockTime() uint32 { + return 0 +} + +// FeeEstimateFallbackSatPerVByte disables the emergency fee fallback. +func (*testPreSignedExitPolicy) FeeEstimateFallbackSatPerVByte() int64 { + return 0 +} + +// ValidateTarget accepts the actor fixture's proof output. +func (*testPreSignedExitPolicy) ValidateTarget(target *wire.TxOut) error { + if target == nil { + return fmt.Errorf("target output is required") + } + + return nil +} + +// BuildSpendTx returns the same transaction as the pre-signed fast path. +func (p *testPreSignedExitPolicy) BuildSpendTx(context.Context, + ExitSpendRequest) (*wire.MsgTx, error) { + + return p.PreSignedSpendTx() +} + +// PreSignedSpendTx returns an isolated copy of the fixed spend. +func (p *testPreSignedExitPolicy) PreSignedSpendTx() (*wire.MsgTx, error) { + if p == nil || p.tx == nil { + return nil, fmt.Errorf("pre-signed transaction is required") + } + + return p.tx.Copy(), nil +} + +// testExitPolicyResolver serves one custom policy to the unroll actor. +type testExitPolicyResolver struct { + policy ExitSpendPolicy +} + +// ResolveExitSpendPolicy returns the configured policy for its exact kind. +func (r *testExitPolicyResolver) ResolveExitSpendPolicy(_ context.Context, + req ExitSpendPolicyRequest) (ExitSpendPolicy, error) { + + if r == nil || r.policy == nil || req.Kind != r.policy.Kind() { + return nil, fmt.Errorf("unsupported test exit policy %q", + req.Kind) + } + + return r.policy, nil +} + // mockProofAssembler is a programmable proof assembler test double. type mockProofAssembler struct { proof *recovery.Proof @@ -1277,6 +1347,15 @@ func newActorHarnessExec(t *testing.T, proof *recovery.Proof, desc *vtxo.Descriptor) (*actor.Actor[Msg, Resp], *behavior, *fakeTxConfirmRef, *memCheckpointStore, *memExec) { + return newActorHarnessExecWithConfig(t, proof, desc, nil) +} + +// newActorHarnessExecWithConfig allows focused tests to install optional +// production seams while preserving the common actor fixture. +func newActorHarnessExecWithConfig(t *testing.T, proof *recovery.Proof, + desc *vtxo.Descriptor, mutate func(*Config)) (*actor.Actor[Msg, Resp], + *behavior, *fakeTxConfirmRef, *memCheckpointStore, *memExec) { + t.Helper() txconfirmRef := &fakeTxConfirmRef{} @@ -1296,6 +1375,9 @@ func newActorHarnessExec(t *testing.T, proof *recovery.Proof, Wallet: &fakeSweepWallet{}, Log: fn.Some(btclog.Disabled), } + if mutate != nil { + mutate(&cfg) + } behavior := &behavior{ cfg: cfg, log: btclog.Disabled, @@ -4749,6 +4831,115 @@ func TestExternalSpendTerminatesActor(t *testing.T) { require.Contains(t, stateResp.FailReason, "spent externally") } +// TestPreSignedExitSpendPublishedByPeerCompletesActor verifies a peer can win +// the publication race for an immutable final spend without making the local +// unroller classify the exact expected transaction as an external conflict. +func TestPreSignedExitSpendPublishedByPeerCompletesActor(t *testing.T) { + proof := buildLinearProof(t) + desc := testDescriptor(t, proof.TargetOutpoint(), proof.CSVDelay()) + targetOutput, err := proof.TargetOutput() + require.NoError(t, err) + + exitTx := wire.NewMsgTx(2) + exitTx.AddTxIn(&wire.TxIn{ + PreviousOutPoint: proof.TargetOutpoint(), + Sequence: proof.CSVDelay(), + }) + exitTx.AddTxOut(&wire.TxOut{ + Value: targetOutput.Value - 1, + PkScript: []byte{txscript.OP_TRUE}, + }) + policy := &testPreSignedExitPolicy{ + tx: exitTx, + csvDelay: proof.CSVDelay(), + } + unrollActor, behavior, txconfirmRef, store, _ := + newActorHarnessExecWithConfig( + t, proof, desc, func(cfg *Config) { + cfg.ExitSpendPolicyResolver = + &testExitPolicyResolver{policy: policy} + }, + ) + + chainSource, ok := behavior.cfg.ChainSource.(*fakeChainSourceRef) + require.True(t, ok) + mustAsk(t, unrollActor.Ref(), &StartUnrollRequest{ + Height: 100, + Trigger: TriggerManual, + ExitPolicyKind: testPreSignedExitPolicyKind, + ExitPolicyRef: "fixed", + }) + + rootTxid := proof.RootTxids()[0] + txconfirmRef.emitConfirmed(t, 0, rootTxid, 101) + require.Eventually(t, func() bool { + return txconfirmRef.requestCountForTxid( + proof.TargetOutpoint().Hash, + ) == 1 + }, testTimeout, 10*time.Millisecond) + + chainSource.emitSpendForOutpoint( + t, proof.TargetOutpoint(), exitTx.TxHash(), 110, + ) + require.Eventually(t, func() bool { + state, ok := mustAsk( + t, unrollActor.Ref(), &GetStateRequest{}, + ).(*GetStateResp) + require.True(t, ok) + + return state.Phase == PhaseCompleted + }, testTimeout, 10*time.Millisecond) + + checkpoint := mustDecodeCheckpoint(t, store, "unroll-test") + require.NotNil(t, checkpoint.SweepTx) + require.Equal(t, exitTx.TxHash(), checkpoint.SweepTx.TxHash()) + require.True(t, checkpoint.State.Sweep.Txid.IsSome()) + require.Equal( + t, exitTx.TxHash(), + checkpoint.State.Sweep.Txid.UnsafeFromSome(), + ) + require.Equal( + t, int32(110)-int32(policy.CSVDelay()), + checkpoint.State.TargetConfirmHeight.UnwrapOrFail(t), + ) +} + +// TestConfirmedFinalSpendCompletesActor verifies the target spend watch can +// finish a locally broadcast exit when its direct confirmation is delayed. +func TestConfirmedFinalSpendCompletesActor(t *testing.T) { + proof := buildLinearProof(t) + desc := testDescriptor(t, proof.TargetOutpoint(), proof.CSVDelay()) + unrollActor, behavior, txconfirmRef, store, _ := newActorHarnessExec( + t, proof, desc, + ) + sweepTxid := driveLinearToSweep( + t, unrollActor.Ref(), txconfirmRef, store, proof, + ) + chainSource, ok := behavior.cfg.ChainSource.(*fakeChainSourceRef) + require.True(t, ok) + + // Withhold txconfirm's direct confirmation. The confirmed target + // spend is independent evidence of the exact persisted exit tx. + chainSource.emitSpendForOutpoint( + t, proof.TargetOutpoint(), sweepTxid, 110, + ) + require.Eventually(t, func() bool { + state, ok := mustAsk( + t, unrollActor.Ref(), &GetStateRequest{}, + ).(*GetStateResp) + require.True(t, ok) + + return state.Phase == PhaseCompleted + }, testTimeout, 10*time.Millisecond) + + checkpoint := mustDecodeCheckpoint(t, store, "unroll-test") + require.Equal(t, sweepTxid, checkpoint.SweepTx.TxHash()) + require.Equal( + t, int32(110), + checkpoint.State.Sweep.ConfirmHeight.UnwrapOrFail(t), + ) +} + // TestStartUnrollIsIdempotent verifies that reissuing start does not duplicate // already-in-flight proof requests. func TestStartUnrollIsIdempotent(t *testing.T) { @@ -4777,6 +4968,8 @@ func TestStartUnrollIsIdempotent(t *testing.T) { var _ input.Signature = testSignature{} var _ SweepWallet = (*fakeSweepWallet)(nil) +var _ PreSignedExitSpendPolicy = (*testPreSignedExitPolicy)(nil) +var _ ExitSpendPolicyResolver = (*testExitPolicyResolver)(nil) var _ vtxo.VTXOStore = (*mockVTXOStore)(nil) var _ actor.DeliveryStore = (*memCheckpointStore)(nil) var _ actor.ActorRef[txconfirm.Msg, txconfirm.Resp] = (*fakeTxConfirmRef)(nil) diff --git a/unroll/asset_terminalization_test.go b/unroll/asset_terminalization_test.go new file mode 100644 index 000000000..3ecd43345 --- /dev/null +++ b/unroll/asset_terminalization_test.go @@ -0,0 +1,159 @@ +package unroll + +import ( + "testing" + "time" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/lightninglabs/wavelength/baselib/actor" + "github.com/lightninglabs/wavelength/lib/actormsg" + "github.com/lightninglabs/wavelength/vtxo" + fn "github.com/lightningnetwork/lnd/fn/v2" + "github.com/stretchr/testify/require" +) + +// TestAssetForeignTargetSpendTerminalizes verifies that asset sweep safety +// does not prevent a foreign target spend from failing the real child actor +// and reaching the registry's terminal persistence and manager feedback paths. +func TestAssetForeignTargetSpendTerminalizes(t *testing.T) { + tests := []struct { + name string + trigger StartTrigger + recoverable bool + }{ + { + name: "materializing", + trigger: TriggerManual, + }, + { + name: "deferredCheckpoint", + trigger: TriggerFraudSpend, + recoverable: true, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + proof := buildOORProof(t) + target := proof.TargetOutpoint() + desc := testDescriptor(t, target, proof.CSVDelay()) + assetRoot := chainhash.Hash{1} + desc.TaprootAssetRoot = &assetRoot + + observer := &captureExitObserver{} + observerRef := actor.TellOnlyRef[vtxo.ManagerMsg]( + observer, + ) + store := newMemRegistryStore() + checkpoints := newMemCheckpointStore() + txconfirmRef := &fakeTxConfirmRef{} + chainSource := &fakeChainSourceRef{} + registry := newRegistryHarnessWithSpawn( + t, RegistryConfig{ + Store: store, + DeliveryStore: checkpoints, + ProofAssembler: &mockProofAssembler{ + proof: proof, + }, + VTXOStore: &mockVTXOStore{ + desc: desc, + }, + TxConfirmRef: txconfirmRef, + ChainSource: chainSource, + Wallet: &fakeSweepWallet{}, + VTXOExitObserver: fn.Some(observerRef), + }, + ) + t.Cleanup(registry.Stop) + + _, err := registry.Ref().Ask( + t.Context(), &EnsureUnrollRequest{ + Outpoint: target, + Trigger: test.trigger, + }, + ).Await(t.Context()).Unpack() + require.NoError(t, err) + require.Contains( + t, chainSource.spendRegistrations(), target, + ) + + checkpoint := mustDecodeCheckpoint( + t, checkpoints, actorIDForTarget(target), + ) + require.True(t, checkpoint.Started) + require.Equal( + t, StandardVTXOTimeoutExitPolicyKind, + checkpoint.ExitPolicyKind, + ) + if test.recoverable { + // Deferral supplies a real active exit with no + // local broadcasts, so failure must reach the + // manager. + require.Len( + t, checkpoint.DeferredCheckpoints, 1, + ) + require.Zero(t, txconfirmRef.requestCount()) + } else { + require.Equal(t, 1, txconfirmRef.requestCount()) + } + + externalTxid := chainhash.Hash{0xee} + chainSource.emitSpendForOutpoint( + t, target, externalTxid, 101, + ) + require.Eventually(t, func() bool { + record, err := store.GetRecord( + t.Context(), target, + ) + require.NoError(t, err) + + if record == nil { + return false + } + + return record.Phase == PhaseFailed + }, testTimeout, 10*time.Millisecond) + + record, err := store.GetRecord(t.Context(), target) + require.NoError(t, err) + require.Contains( + t, record.FailReason, "spent externally", + ) + require.Contains(t, record.FailReason, target.String()) + require.Contains( + t, record.FailReason, externalTxid.String(), + ) + require.Contains(t, record.FailReason, "height 101") + require.Equal( + t, test.recoverable, record.RecoverableFailure, + ) + require.False(t, record.ConflictedFailure) + + checkpoint = mustDecodeCheckpoint( + t, checkpoints, actorIDForTarget(target), + ) + require.Equal(t, record.FailReason, checkpoint.Fail) + require.Nil(t, checkpoint.SweepTx) + if !test.recoverable { + require.Empty(t, observer.notifications()) + + return + } + + require.Eventually(t, func() bool { + return len(observer.notifications()) == 1 + }, testTimeout, 10*time.Millisecond) + note := observer.notifications()[0] + require.Equal(t, target, note.Outpoint) + require.Equal( + t, vtxo.ExitOutcomeRecoverable, note.Outcome, + ) + require.Equal(t, record.FailReason, note.Reason) + require.Equal( + t, actormsg.ExitPolicyKind( + StandardVTXOTimeoutExitPolicyKind, + ), + note.ExitPolicyKind, + ) + }) + } +} diff --git a/unroll/interfaces.go b/unroll/interfaces.go index c93554b79..586e711f3 100644 --- a/unroll/interfaces.go +++ b/unroll/interfaces.go @@ -152,6 +152,19 @@ type AssetClaimer interface { heightHint uint32) (*wire.MsgTx, error) } +// PreSignedExitSpendPolicy is implemented by policies whose final spend is +// fixed before the unroll actor reaches CSV maturity. Another authorized +// participant may publish that exact transaction first, so the target spend +// watcher must recognize it as successful completion instead of an external +// conflict. +type PreSignedExitSpendPolicy interface { + ExitSpendPolicy + + // PreSignedSpendTx returns an isolated copy of the immutable, fully + // signed final spend. + PreSignedSpendTx() (*wire.MsgTx, error) +} + // ExitSpendPolicyResolver reconstructs a policy from the durable identity // stored with an unroll job. Custom actor factories can inject resolvers for // their policy families; the built-in actor default handles standard VTXO diff --git a/unroll/policy_resolvers.go b/unroll/policy_resolvers.go new file mode 100644 index 000000000..c245a6840 --- /dev/null +++ b/unroll/policy_resolvers.go @@ -0,0 +1,70 @@ +package unroll + +import ( + "context" + "fmt" +) + +// PolicyResolvers dispatches durable non-standard exit policies by kind. +// Each child resolver remains responsible for validating its own reference. +type PolicyResolvers []ExitSpendPolicyResolver + +// SupportsKind reports whether one child resolver advertises the policy kind. +func (r PolicyResolvers) SupportsKind(kind ExitPolicyKind) bool { + hasLegacyResolver := false + for _, resolver := range r { + if resolver == nil { + continue + } + support, ok := resolver.(ResolverKindSupport) + if !ok { + hasLegacyResolver = true + + continue + } + if support.SupportsKind(kind) { + return true + } + } + + // A legacy resolver cannot advertise its coverage. Preserve its former + // behavior by admitting the kind and consulting it at resolution time. + return hasLegacyResolver +} + +// ResolveExitSpendPolicy delegates to the one resolver advertising the kind. +func (r PolicyResolvers) ResolveExitSpendPolicy(ctx context.Context, + req ExitSpendPolicyRequest) (ExitSpendPolicy, error) { + + for _, resolver := range r { + if resolver == nil { + continue + } + support, ok := resolver.(ResolverKindSupport) + if !ok || !support.SupportsKind(req.Kind) { + continue + } + + return resolver.ResolveExitSpendPolicy(ctx, req) + } + + // Prefer explicit kind routing above, then fall back to the first + // legacy resolver exactly as a standalone pre-advertisement resolver + // behaved. + for _, resolver := range r { + if resolver == nil { + continue + } + if _, ok := resolver.(ResolverKindSupport); ok { + continue + } + + return resolver.ResolveExitSpendPolicy(ctx, req) + } + + return nil, fmt.Errorf("no exit spend policy resolver for kind %q", + req.Kind) +} + +var _ ExitSpendPolicyResolver = PolicyResolvers{} +var _ ResolverKindSupport = PolicyResolvers{} diff --git a/unroll/registry_test.go b/unroll/registry_test.go index f72234e83..cd35b3a79 100644 --- a/unroll/registry_test.go +++ b/unroll/registry_test.go @@ -2229,6 +2229,25 @@ func TestRegistryRestoreSkipsCheckWhenResolverHasNoKindSupport(t *testing.T) { require.NoError(t, r.validateResolverCoversRecords(records)) } +// TestPolicyResolversPreservesLegacyResolver verifies wrapping an older +// resolver in the composite neither hides its advertised coverage nor skips +// it when the policy is reconstructed. +func TestPolicyResolversPreservesLegacyResolver(t *testing.T) { + legacy := &recordingExitSpendPolicyResolver{} + resolvers := PolicyResolvers{legacy} + kind := ExitPolicyKind("legacy-kind") + + require.True(t, resolvers.SupportsKind(kind)) + _, err := resolvers.ResolveExitSpendPolicy( + t.Context(), ExitSpendPolicyRequest{ + Kind: kind, + }, + ) + require.ErrorContains(t, err, "recording resolver") + require.Len(t, legacy.requests, 1) + require.Equal(t, kind, legacy.requests[0].Kind) +} + var _ RegistryStore = (*memRegistryStore)(nil) var _ RegistryStore = (*flakyRegistryStore)(nil) var _ RegistryStore = (*terminalFlakyRegistryStore)(nil) diff --git a/vtxo/filter.go b/vtxo/filter.go index 5e8aa2667..c3c1dc669 100644 --- a/vtxo/filter.go +++ b/vtxo/filter.go @@ -102,7 +102,7 @@ func SumPendingBalance(descs []*Descriptor) btcutil.Amount { // Spendable, terminal, or separately accounted. case VTXOStatusLive, VTXOStatusForfeited, VTXOStatusSpent, VTXOStatusUnilateralExit, VTXOStatusFailed, - VTXOStatusExpired: + VTXOStatusExpired, VTXOStatusRecoveryOnly: } } diff --git a/vtxo/filter_test.go b/vtxo/filter_test.go index 2b5e9f110..5b3e32314 100644 --- a/vtxo/filter_test.go +++ b/vtxo/filter_test.go @@ -81,7 +81,8 @@ func TestSumSpendableBalanceEmpty(t *testing.T) { } // TestSumPendingBalance checks that only PendingForfeit, Forfeiting, and -// Spending are summed, excluding Live, Expired, and the terminal states. +// Spending are summed, excluding Live, Expired, RecoveryOnly, and the terminal +// states. func TestSumPendingBalance(t *testing.T) { t.Parallel() @@ -122,6 +123,10 @@ func TestSumPendingBalance(t *testing.T) { Amount: 23_000, Status: VTXOStatusExpired, }, + { + Amount: 29_000, + Status: VTXOStatusRecoveryOnly, + }, } require.Equal( diff --git a/vtxo/interfaces.go b/vtxo/interfaces.go index ad42085fc..d89682d61 100644 --- a/vtxo/interfaces.go +++ b/vtxo/interfaces.go @@ -313,6 +313,18 @@ const ( // NOTE: Appended last so the numeric values of existing statuses used // in SQL queries are unchanged. VTXOStatusExpired + + // VTXOStatusRecoveryOnly identifies an application-owned output whose + // descriptor exists only so the common unroller can recover its + // on-chain ancestry. It is deliberately excluded from wallet balance, + // coin selection, refresh, and VTXO actor recovery. The application FSM + // owns its lifecycle and admits the exact final-spend policy to unroll. + // It must refresh or materialize the output before BatchExpiry; + // relative CSV delays do not extend that absolute deadline. + // + // NOTE: Appended last so the numeric values of existing statuses used + // in SQL queries are unchanged. + VTXOStatusRecoveryOnly ) // String returns a human-readable representation of the VTXO status. @@ -345,6 +357,9 @@ func (s VTXOStatus) String() string { case VTXOStatusExpired: return "expired" + case VTXOStatusRecoveryOnly: + return "recovery_only" + default: return "unknown" } diff --git a/vtxo/manager.go b/vtxo/manager.go index 03048beb9..894f79639 100644 --- a/vtxo/manager.go +++ b/vtxo/manager.go @@ -1497,16 +1497,24 @@ func (m *Manager) confirmExitedVTXO(ctx context.Context, } // No live actor: persist the terminal spent status directly so a - // restarted daemon still records the on-chain spend. Only act on a VTXO - // still in the exit state so a re-delivered confirmation cannot stomp a - // VTXO that has since been reissued or recovered to live. + // restarted daemon still records the on-chain spend. Recovery-only + // descriptors are also eligible when a non-standard policy completed; + // they deliberately have no VTXO actor because their owning application + // FSM controls admission. The policy check prevents an ordinary timeout + // job from retiring an application-owned row. descriptor, err := m.cfg.Store.GetVTXO(ctx, req.Outpoint) if err != nil { return fn.Err[ManagerResp]( fmt.Errorf("load vtxo for confirm: %w", err), ) } - if descriptor == nil || descriptor.Status != VTXOStatusUnilateralExit { + if descriptor == nil { + return fn.Ok[ManagerResp](&ExitOutcomeResp{}) + } + isOrdinaryExit := descriptor.Status == VTXOStatusUnilateralExit + isRecoveryOnly := descriptor.Status == VTXOStatusRecoveryOnly && + req.ExitPolicyKind.Valid() + if !isOrdinaryExit && !isRecoveryOnly { return fn.Ok[ManagerResp](&ExitOutcomeResp{}) } @@ -2535,7 +2543,7 @@ func (m *Manager) exactSpendUnavailableError(ctx context.Context, case VTXOStatusForfeited, VTXOStatusSpent, VTXOStatusUnilateralExit, VTXOStatusFailed, - VTXOStatusExpired: + VTXOStatusExpired, VTXOStatusRecoveryOnly: return fmt.Errorf("%w: exact spend outpoint %s has status %s", ErrInsufficientSpendableFunds, op, desc.Status) } @@ -3079,11 +3087,13 @@ func (m *Manager) handleCompleteSpend(ctx context.Context, for _, op := range outpoints { ref, ok := m.actors[op] if !ok { - spent, err := m.isPersistedSpent(ctx, op) + completedWithoutActor, err := m.completePersistedSpend( + ctx, op, + ) if err != nil { return fn.Err[ManagerResp](err) } - if spent { + if completedWithoutActor { m.dropReserved(op) completed++ @@ -3120,15 +3130,17 @@ func (m *Manager) handleCompleteSpend(ctx context.Context, }) } -// isPersistedSpent returns true when an actor was already cleaned up after -// the spend status reached durable storage. It returns false with no error -// when the VTXO is absent, and returns an error when the store cannot give a -// definitive answer. +// completePersistedSpend completes the two valid actorless spend cases. A +// terminal Spent row means a previous attempt already completed. A +// RecoveryOnly row deliberately has no VTXO actor because its application FSM +// owns spend admission, so an accepted OOR spend retires it directly while +// atomically releasing the durable spend reservation. Every other state still +// requires its normal VTXO actor. // // This makes CompleteSpend idempotent across crashes that happen after the // VTXO status commit but before the OOR session checkpoints Completed. -func (m *Manager) isPersistedSpent(ctx context.Context, op wire.OutPoint) (bool, - error) { +func (m *Manager) completePersistedSpend(ctx context.Context, + op wire.OutPoint) (bool, error) { if m.cfg.Store == nil { return false, nil @@ -3140,7 +3152,7 @@ func (m *Manager) isPersistedSpent(ctx context.Context, op wire.OutPoint) (bool, return false, nil } - return false, fmt.Errorf("load vtxo for spent check %s: %w", op, + return false, fmt.Errorf("load vtxo for completion %s: %w", op, err) } @@ -3148,7 +3160,24 @@ func (m *Manager) isPersistedSpent(ctx context.Context, op wire.OutPoint) (bool, return false, nil } - return desc.Status == VTXOStatusSpent, nil + switch desc.Status { + case VTXOStatusSpent: + return true, nil + + case VTXOStatusRecoveryOnly: + err := m.cfg.Store.UpdateVTXOStatusReleasingReservation( + ctx, op, VTXOStatusSpent, + ) + if err != nil { + return false, fmt.Errorf("complete recovery-only vtxo "+ + "%s: %w", op, err) + } + + return true, nil + + default: + return false, nil + } } // ============================================================================= diff --git a/vtxo/manager_admission_test.go b/vtxo/manager_admission_test.go index 6931c4976..88ff103ba 100644 --- a/vtxo/manager_admission_test.go +++ b/vtxo/manager_admission_test.go @@ -1415,6 +1415,62 @@ func TestCompleteSpendAlreadyPersistedSpentIsIdempotent(t *testing.T) { store.AssertExpectations(t) } +// TestCompleteSpendRecoveryOnlyWithoutActor verifies that an application-owned +// VTXO can complete an admitted OOR spend even though it deliberately has no +// ordinary VTXO actor. The status transition and reservation release use the +// store's atomic operation. +func TestCompleteSpendRecoveryOnlyWithoutActor(t *testing.T) { + t.Parallel() + + vtxo := makeDescriptor(t, 50000, 0) + vtxo.Status = VTXOStatusRecoveryOnly + + mgr, store := newTestManager(t, nil) + store.On( + "GetVTXO", t.Context(), vtxo.Outpoint, + ).Return(vtxo, nil).Once() + store.On( + "UpdateVTXOStatusReleasingReservation", t.Context(), + vtxo.Outpoint, VTXOStatusSpent, + ).Return(nil).Once() + + result := mgr.Receive(t.Context(), &CompleteSpendRequest{ + Outpoints: []wire.OutPoint{vtxo.Outpoint}, + }) + resp, err := result.Unpack() + require.NoError(t, err) + + completeResp, ok := resp.(*CompleteSpendResponse) + require.True(t, ok, "expected *CompleteSpendResponse") + require.Equal(t, 1, completeResp.CompletedCount) + + store.AssertExpectations(t) +} + +// TestCompleteSpendActorlessLiveVTXOReturnsNoActor verifies that the +// recovery-only exception cannot retire a normal VTXO whose actor is missing. +func TestCompleteSpendActorlessLiveVTXOReturnsNoActor(t *testing.T) { + t.Parallel() + + vtxo := makeDescriptor(t, 50000, 0) + vtxo.Status = VTXOStatusLive + + mgr, store := newTestManager(t, nil) + store.On( + "GetVTXO", t.Context(), vtxo.Outpoint, + ).Return(vtxo, nil).Once() + + result := mgr.Receive(t.Context(), &CompleteSpendRequest{ + Outpoints: []wire.OutPoint{vtxo.Outpoint}, + }) + _, err := result.Unpack() + require.Error(t, err) + require.Contains(t, err.Error(), "no actor for outpoint") + + store.AssertNotCalled(t, "UpdateVTXOStatusReleasingReservation") + store.AssertExpectations(t) +} + // TestCompleteSpendMissingPersistedVTXOReturnsNoActor verifies that a missing // persisted VTXO remains a normal unknown-outpoint error. func TestCompleteSpendMissingPersistedVTXOReturnsNoActor(t *testing.T) { @@ -1455,7 +1511,7 @@ func TestCompleteSpendPersistedSpentCheckError(t *testing.T) { }) _, err := result.Unpack() require.ErrorIs(t, err, storeErr) - require.Contains(t, err.Error(), "load vtxo for spent check") + require.Contains(t, err.Error(), "load vtxo for completion") store.AssertExpectations(t) } diff --git a/vtxo/manager_exit_test.go b/vtxo/manager_exit_test.go index bf7383c77..26b1bf7cd 100644 --- a/vtxo/manager_exit_test.go +++ b/vtxo/manager_exit_test.go @@ -302,6 +302,40 @@ func TestHandleExitOutcomeConfirmedNoActorPersistsSpent(t *testing.T) { store.AssertExpectations(t) } +// TestHandleExitOutcomeConfirmedNoActorPersistsChannelRecoverySpent verifies +// that a confirmed channel-backing spend retires its recovery-only source even +// though the source deliberately has no live wallet actor. +func TestHandleExitOutcomeConfirmedNoActorPersistsChannelRecoverySpent( + t *testing.T) { + + t.Parallel() + + vtxo := makeDescriptor(t, 50_000, 8) + vtxo.Status = VTXOStatusRecoveryOnly + store := &MockVTXOStore{} + mgr := &Manager{ + cfg: &ManagerConfig{ + Store: store, + }, + actors: make(map[wire.OutPoint]VTXOActorRef), + } + + store.On("GetVTXO", t.Context(), vtxo.Outpoint).Return(vtxo, nil) + store.On( + "UpdateVTXOStatus", t.Context(), vtxo.Outpoint, VTXOStatusSpent, + ).Return(nil) + + resp := mgr.Receive(t.Context(), &ExitOutcomeNotification{ + Outpoint: vtxo.Outpoint, + Outcome: ExitOutcomeConfirmed, + ExitPolicyKind: actormsg.ExitPolicyArkChannelBacking, + }) + _, err := resp.Unpack() + require.NoError(t, err) + + store.AssertExpectations(t) +} + // TestHandleExitOutcomeConfirmedNoActorAlreadySpentIsNoop verifies that a // re-delivered confirmation for a VTXO that is no longer in the exit state // (e.g. already spent) does not rewrite its status. diff --git a/waved/cooperative_oor.go b/waved/cooperative_oor.go new file mode 100644 index 000000000..9234ec3a9 --- /dev/null +++ b/waved/cooperative_oor.go @@ -0,0 +1,289 @@ +package waved + +import ( + "bytes" + "context" + "fmt" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "github.com/btcsuite/btcd/psbt/v2" + "github.com/lightninglabs/wavelength/lib/arkscript" + oortx "github.com/lightninglabs/wavelength/lib/tx/oor" + "github.com/lightninglabs/wavelength/lib/tx/psbtutil" + "github.com/lightninglabs/wavelength/oor" + "github.com/lightninglabs/wavelength/vtxo" + "github.com/lightninglabs/wavelength/waverpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// checkCooperativeFunding binds an explicit funding descriptor to the wallet's +// record when known. An external VTXO's funding data comes from the authorized +// caller's swap record, not from the PSBT offered for signature. +func checkCooperativeFunding(ci *waverpc.CustomOORInput, + stored *vtxo.Descriptor, operator *btcec.PublicKey) error { + + if ci.AmountSat <= 0 || len(ci.PkScript) == 0 || + len(ci.VtxoPolicyTemplate) == 0 || len(ci.SpendPath) == 0 { + return fmt.Errorf("complete cooperative funding descriptor " + + "required") + } + if stored == nil { + return nil + } + matchesPolicy := len(stored.PolicyTemplate) == 0 || + bytes.Equal(stored.PolicyTemplate, ci.VtxoPolicyTemplate) + matchesOperator := stored.OperatorKey == nil || + sameXOnlyPubKey(stored.OperatorKey, operator) + if int64(stored.Amount) != ci.AmountSat || + !bytes.Equal(stored.PkScript, ci.PkScript) || + !matchesPolicy || !matchesOperator { + return fmt.Errorf("cooperative input differs from stored " + + "funding") + } + + return nil +} + +// checkCooperativeIntent admits only full-value, single-recipient spends in +// shared-owner mode. Prepare and cosign take unsigned inputs; Send needs both +// independent authorizations before it may dispatch a transfer. +func checkCooperativeIntent(inputs []*waverpc.CustomOORInput, + outputs []*waverpc.Output, send bool) (bool, error) { + + for _, in := range inputs { + if !in.GetPreserveSourceOwners() { + if len(in.GetPayoutSignatures()) != 0 { + return false, fmt.Errorf("unexpected payout " + + "signatures") + } + + continue + } + if len(inputs) != 1 || len(outputs) != 1 || + in.AmountSat <= 0 || + in.AmountSat != outputs[0].GetAmountSat() { + return false, fmt.Errorf("cooperative spend requires " + + "one input and one full-value payout") + } + want := 0 + if send { + want = 1 + } + if len(in.ExternalSignatures) != want || + len(in.PayoutSignatures) != want { + return false, fmt.Errorf("expected %d checkpoint and "+ + "payout signatures", want) + } + + return true, nil + } + + return false, nil +} + +// cooperativeOwnerLeaf retains the funded leaf verbatim instead of deriving a +// local-owner-only checkpoint. A constrained/unilateral leaf is not a generic +// cooperative authorization. +func cooperativeOwnerLeaf(template *arkscript.PolicyTemplate, + local, operator *btcec.PublicKey, rawPath []byte) ([]byte, []byte, + error) { + + tree, err := template.Compile() + if err != nil { + return nil, nil, err + } + for _, leaf := range template.Leaves { + multi, ok := leaf.Node.(*arkscript.Multisig) + if !ok || len(multi.Keys) != 3 || + !arkscript.ContainsKey(multi, local) || + !arkscript.ContainsKey(multi, operator) || + sameXOnlyPubKey(local, operator) { + + continue + } + seen := make(map[string]bool) + for _, key := range multi.Keys { + seen[string(schnorr.SerializePubKey(key))] = true + } + if len(seen) != len(multi.Keys) { + continue + } + path, err := tree.SpendPathForNode(multi, nil) + if err != nil { + return nil, nil, err + } + encoded, err := path.Encode() + if err != nil { + return nil, nil, err + } + if !bytes.Equal(rawPath, encoded) { + continue + } + policy, err := leaf.Encode() + + return path.WitnessScript, policy, err + } + + return nil, nil, fmt.Errorf("no matching canonical funded co-owner " + + "leaf") +} + +// verifyCooperativeSubmit checks both authorizations on the same package the +// actor will build. The operator is not a substitute for the other owner. +func verifyCooperativeSubmit(policy arkscript.CheckpointPolicy, + inputs []oor.TransferInput, recipients []oortx.RecipientOutput) error { + + ark, cps, err := oor.BuildSubmitPackage(policy, inputs, recipients) + if err != nil { + return err + } + in := &inputs[0] + for _, key := range in.CustomSpendKeys { + if sameXOnlyPubKey(key, in.VTXO.ClientKey.PubKey) || + sameXOnlyPubKey(key, policy.OperatorKey) { + + continue + } + err := oor.VerifySingleInputAuthorization( + cps[0], key, in.CustomSpend.WitnessScript, + in.ExternalSignatures[0], + ) + if err != nil { + return fmt.Errorf("checkpoint authorization: %w", err) + } + + return oor.VerifySingleInputAuthorization( + ark, key, in.OwnerLeafScript, + in.ExternalArkSignatures[0], + ) + } + + return fmt.Errorf("missing cooperative source co-owner") +} + +// signCooperativePackage signs only the canonical package rebuilt from the +// authenticated caller's funded outpoint, policy, amount and payout. Comparing +// serialized packets also binds witness UTXOs, leaf scripts and control data. +func (r *RPCServer) signCooperativePackage(ctx context.Context, + pkg *waverpc.CooperativeOORPackage) ( + *waverpc.SignOORCustomInputResponse, error) { + + inputs := []*waverpc.CustomOORInput{pkg.CustomInput} + outputs := []*waverpc.Output{pkg.Recipient} + ok, err := checkCooperativeIntent(inputs, outputs, false) + if err != nil || !ok || len(pkg.CheckpointPsbt) == 0 || + len(pkg.ArkPsbt) == 0 { + return nil, status.Error( + codes.InvalidArgument, + "incomplete cooperative signing intent", + ) + } + if r.server.vtxoStore == nil { + return nil, status.Error( + codes.Internal, "VTXO store not initialized", + ) + } + terms, err := r.server.fetchOperatorTerms(ctx) + if err != nil { + return nil, operatorTermsError( + "unable to fetch operator terms", err, + ) + } + transfer, err := BuildCustomTransferInputs( + ctx, r.server.vtxoStore, inputs, r.server.loadClientKeyDesc(), + terms.PubKey, terms.VTXOExitDelay, + ) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + recipients, err := r.buildSendOORRecipients(ctx, outputs, terms) + if err != nil { + return nil, err + } + ark, cps, err := oor.BuildSubmitPackage(arkscript.CheckpointPolicy{ + OperatorKey: terms.PubKey, CSVDelay: terms.VTXOExitDelay, + }, transfer, recipients) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } + for _, packet := range []struct { + expected *psbt.Packet + received []byte + }{ + { + ark, + pkg.ArkPsbt, + }, { + cps[0], + pkg.CheckpointPsbt, + }, + } { + raw, err := psbtutil.Serialize(packet.expected) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + if !bytes.Equal(raw, packet.received) { + return nil, status.Error( + codes.InvalidArgument, "unsigned package "+ + "does not match funded input and "+ + "payout", + ) + } + } + signer, err := r.oorSigner() + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + cpSig, err := oor.SignCustomCheckpointInput( + signer, &transfer[0], cps[0], + ) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + if err := oor.SignArkPSBT(signer, ark, cps, transfer); err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + payout := ark.Inputs[0].TaprootScriptSpendSig + if len(payout) != 1 { + return nil, status.Error( + codes.Internal, "expected one wallet payout signature", + ) + } + local := transfer[0].VTXO.ClientKey.PubKey + arkSig := &oor.ExternalTaprootScriptSignature{ + PubKey: local, WitnessScript: transfer[0].OwnerLeafScript, + Signature: payout[0].Signature, SigHash: payout[0].SigHash, + } + // A signer backend failure must never produce a partial authorization. + if err := oor.VerifySingleInputAuthorization( + cps[0], local, transfer[0].CustomSpend.WitnessScript, *cpSig, + ); err != nil { + return nil, status.Errorf(codes.Internal, "wallet checkpoint "+ + "signature: %v", err) + } + if err := oor.VerifySingleInputAuthorization( + ark, local, transfer[0].OwnerLeafScript, *arkSig, + ); err != nil { + return nil, status.Errorf(codes.Internal, "wallet payout "+ + "signature: %v", err) + } + + return &waverpc.SignOORCustomInputResponse{ + Signature: rpcScriptSignature(cpSig), + PayoutSignature: rpcScriptSignature(arkSig), + }, nil +} + +// rpcScriptSignature converts a wallet-generated signature to its wire record. +func rpcScriptSignature( + s *oor.ExternalTaprootScriptSignature) *waverpc.TaprootScriptSignature { + + return &waverpc.TaprootScriptSignature{ + Pubkey: s.PubKey.SerializeCompressed(), + WitnessScript: s.WitnessScript, + Signature: s.Signature, + Sighash: uint32(s.SigHash), + } +} diff --git a/waved/cooperative_oor_test.go b/waved/cooperative_oor_test.go new file mode 100644 index 000000000..fa0ef95a6 --- /dev/null +++ b/waved/cooperative_oor_test.go @@ -0,0 +1,301 @@ +package waved + +import ( + "bytes" + "context" + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btclog/v2" + "github.com/lightninglabs/wavelength/baselib/actor" + "github.com/lightninglabs/wavelength/lib/tx/psbtutil" + "github.com/lightninglabs/wavelength/oor" + "github.com/lightninglabs/wavelength/vtxo" + "github.com/lightninglabs/wavelength/wallet" + "github.com/lightninglabs/wavelength/waverpc" + fn "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/input" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +// TestCooperativeOORWalletRoundTrip prepares as the sender, signs with the +// receiver's wallet and sends with both independently verifiable signatures. +// Invalid signing intents release neither signature; invalid authorizations +// never reach the transfer actor. +func TestCooperativeOORWalletRoundTrip(t *testing.T) { + t.Parallel() + + f := newCustomOORRPCFixture(t) + r := f.rpcServer + ctx := t.Context() + path, err := f.policy.RefundPath() + require.NoError(t, err) + f.customIn.SpendPath, err = path.Encode() + require.NoError(t, err) + f.customIn.PreserveSourceOwners = true + f.recipient.Destination = &waverpc.Output_Pubkey{ + Pubkey: schnorr.SerializePubKey(f.senderPriv.PubKey()), + } + + r.server.clientKeyDesc.PubKey = f.senderPriv.PubKey() + prepared, err := r.PrepareOOR(ctx, &waverpc.PrepareOORRequest{ + CustomInputs: []*waverpc.CustomOORInput{f.customIn}, + Recipient: f.recipient, + }) + require.NoError(t, err) + require.Len(t, prepared.CheckpointPsbts, 1) + ark, err := psbtutil.Parse(prepared.ArkPsbt) + require.NoError(t, err) + require.Empty(t, ark.Inputs[0].TaprootScriptSpendSig) + require.Len(t, ark.Inputs[0].TaprootLeafScript, 1) + require.Equal( + t, path.WitnessScript, + ark.Inputs[0].TaprootLeafScript[0].Script, + ) + cp, err := psbtutil.Parse(prepared.CheckpointPsbts[0]) + require.NoError(t, err) + require.Equal(t, f.outpoint, cp.UnsignedTx.TxIn[0].PreviousOutPoint) + require.Equal(t, f.customIn.AmountSat, cp.Inputs[0].WitnessUtxo.Value) + require.Equal(t, f.customIn.PkScript, cp.Inputs[0].WitnessUtxo.PkScript) + require.Equal( + t, cp.UnsignedTx.TxHash(), + ark.UnsignedTx.TxIn[0].PreviousOutPoint.Hash, + ) + + r.server.clientKeyDesc.PubKey = f.clientPriv.PubKey() + pkg := &waverpc.CooperativeOORPackage{ + CustomInput: f.customIn, Recipient: f.recipient, + CheckpointPsbt: prepared.CheckpointPsbts[0], + ArkPsbt: prepared.ArkPsbt, + } + for _, tc := range []struct { + name string + change func(*waverpc.CooperativeOORPackage) + }{ + {"funded outpoint", func(p *waverpc.CooperativeOORPackage) { + op := testWalletOpsOutpoint(88) + p.CustomInput.Outpoint = op.String() + }}, + {"payout destination", func(p *waverpc.CooperativeOORPackage) { + p.Recipient.Destination = &waverpc.Output_Pubkey{ + Pubkey: schnorr.SerializePubKey( + f.clientPriv.PubKey(), + ), + } + }}, + {"funded amount", func(p *waverpc.CooperativeOORPackage) { + p.CustomInput.AmountSat++ + p.Recipient.AmountSat++ + }}, + {"partial payout", func(p *waverpc.CooperativeOORPackage) { + p.Recipient.AmountSat-- + }}, + {"funded script", func(p *waverpc.CooperativeOORPackage) { + p.CustomInput.PkScript[2] ^= 1 + }}, + {"wrong checkpoint", func(p *waverpc.CooperativeOORPackage) { + p.CheckpointPsbt = p.ArkPsbt + }}, + {"checkpoint prevout metadata", func( + p *waverpc.CooperativeOORPackage) { + + packet, err := psbtutil.Parse(p.CheckpointPsbt) + require.NoError(t, err) + packet.Inputs[0].WitnessUtxo.Value++ + p.CheckpointPsbt, err = psbtutil.Serialize(packet) + require.NoError(t, err) + }}, + {"final prevout metadata", func( + p *waverpc.CooperativeOORPackage) { + + packet, err := psbtutil.Parse(p.ArkPsbt) + require.NoError(t, err) + packet.Inputs[0].WitnessUtxo.Value++ + p.ArkPsbt, err = psbtutil.Serialize(packet) + require.NoError(t, err) + }}, + {"wrong final packet", func(p *waverpc.CooperativeOORPackage) { + p.ArkPsbt = p.CheckpointPsbt + }}, + {"conditioned leaf", func(p *waverpc.CooperativeOORPackage) { + p.CustomInput.SpendPath, err = f.claimPath.Encode() + require.NoError(t, err) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + invalid := &waverpc.CooperativeOORPackage{} + proto.Merge(invalid, pkg) + tc.change(invalid) + // An unconfigured mock fails the test on any signing + // call. + r.oorSignerOverride = &input.MockInputSigner{} + resp, err := r.SignOORCustomInput( + ctx, &waverpc.SignOORCustomInputRequest{ + CooperativePackage: invalid, + }, + ) + require.Nil(t, resp) + require.Equal( + t, codes.InvalidArgument, status.Code(err), + ) + }) + } + + r.oorSignerOverride = input.NewMockSigner( + []*btcec.PrivateKey{f.clientPriv}, nil, + ) + sigs, err := r.SignOORCustomInput( + ctx, &waverpc.SignOORCustomInputRequest{ + CooperativePackage: pkg, + }, + ) + require.NoError(t, err) + require.NotEqual( + t, sigs.Signature.Signature, sigs.PayoutSignature.Signature, + ) + require.Equal(t, path.WitnessScript, sigs.PayoutSignature.WitnessScript) + require.Equal(t, sigs.Signature.Pubkey, sigs.PayoutSignature.Pubkey) + + r.server.clientKeyDesc.PubKey = f.senderPriv.PubKey() + target := attachCooperativeTestActor(t, r) + f.customIn.ExternalSignatures = []*waverpc.TaprootScriptSignature{ + sigs.Signature, + } + f.customIn.PayoutSignatures = []*waverpc.TaprootScriptSignature{ + sigs.PayoutSignature, + } + send := &waverpc.SendOORRequest{ + Recipients: []*waverpc.Output{ + f.recipient, + }, + CustomInputs: []*waverpc.CustomOORInput{ + f.customIn, + }, + } + for _, tc := range []struct { + name string + change func(*waverpc.CustomOORInput) + }{ + { + "missing payout", + func(in *waverpc.CustomOORInput) { + in.PayoutSignatures = nil + }, + }, + { + "missing checkpoint", + func(in *waverpc.CustomOORInput) { + in.ExternalSignatures = nil + }, + }, + { + "checkpoint reused", + func(in *waverpc.CustomOORInput) { + in.PayoutSignatures = in.ExternalSignatures + }, + }, + { + "payout reused", + func(in *waverpc.CustomOORInput) { + in.ExternalSignatures = in.PayoutSignatures + }, + }, + { + "partial sighash", + func(in *waverpc.CustomOORInput) { + in.PayoutSignatures[0].Sighash = 2 + }, + }, + {"wrong signer", func(in *waverpc.CustomOORInput) { + in.PayoutSignatures[0].Pubkey = f.senderPriv. + PubKey(). + SerializeCompressed() + }}, + } { + t.Run(tc.name, func(t *testing.T) { + req := &waverpc.SendOORRequest{} + proto.Merge(req, send) + tc.change(req.CustomInputs[0]) + resp, err := r.SendOOR(ctx, req) + require.Nil(t, resp) + require.Equal( + t, codes.InvalidArgument, status.Code(err), + ) + require.Empty(t, target.capturedRequests()) + }) + } + resp, err := r.SendOOR(ctx, send) + require.NoError(t, err) + require.Equal(t, "submitted", resp.Status) + requests := target.capturedRequests() + require.Len(t, requests, 1) + require.Equal( + t, path.WitnessScript, requests[0].Inputs[0].OwnerLeafScript, + ) + require.Len(t, requests[0].Inputs[0].ExternalArkSignatures, 1) +} + +// attachCooperativeTestActor captures successful RPC dispatch without sending +// anything to the operator or requiring an integration network. +func attachCooperativeTestActor(t *testing.T, + r *RPCServer) *capturingSendOORActor { + + t.Helper() + system := actor.NewActorSystem() + t.Cleanup( + func() { + require.NoError( + t, + system.Shutdown( + context.Background(), + ), + ) + }, + ) + key := actor.NewServiceKey[wallet.WalletMsg, wallet.WalletResp]( + "refund-test-wallet", + ) + r.server.walletRef = fn.Some( + key.Spawn( + system, "refund-wallet", &sendOORTestWallet{}, + ), + ) + r.server.actorSystem = system + r.server.log = btclog.Disabled + r.server.walletServicesReady = resolvedSignal() + id := chainhash.HashH([]byte("test refund")) + target := &capturingSendOORActor{response: &oor.StartTransferResponse{ + SessionID: oor.SessionID(id), + }} + oor.NewServiceKey().Spawn(system, "refund-oor", target) + + return target +} + +// TestCooperativeFundingRecordBinding rejects caller funding data that would +// shadow a different record already held by the wallet. +func TestCooperativeFundingRecordBinding(t *testing.T) { + t.Parallel() + f := newCustomOORRPCFixture(t) + stored := &vtxo.Descriptor{ + Amount: 1, PkScript: bytes.Clone(f.customIn.PkScript), + } + require.Error(t, checkCooperativeFunding(f.customIn, stored, nil)) + stored.Amount = 42_000 + require.NoError(t, checkCooperativeFunding(f.customIn, stored, nil)) + stored.OperatorKey = f.clientPriv.PubKey() + require.Error( + t, + checkCooperativeFunding( + f.customIn, stored, f.senderPriv.PubKey(), + ), + ) + stored.OperatorKey = nil + stored.PkScript[2] ^= 1 + require.Error(t, checkCooperativeFunding(f.customIn, stored, nil)) +} diff --git a/waved/rpc_oor_custom_input_test.go b/waved/rpc_oor_custom_input_test.go index cd606faf4..8a161e14a 100644 --- a/waved/rpc_oor_custom_input_test.go +++ b/waved/rpc_oor_custom_input_test.go @@ -27,6 +27,8 @@ import ( ) type customOORRPCFixture struct { + policy *arkscript.VHTLCPolicy + senderPriv *btcec.PrivateKey rpcServer *RPCServer customIn *waverpc.CustomOORInput recipient *waverpc.Output @@ -40,7 +42,7 @@ type customOORRPCFixture struct { func newCustomOORRPCFixture(t *testing.T) *customOORRPCFixture { t.Helper() - policy, preimage, _, receiverPriv, serverPriv := + policy, preimage, senderPriv, receiverPriv, serverPriv := testVHTLCPolicyFixture(t) policyTemplate, err := policy.Template.Encode() require.NoError(t, err) @@ -92,6 +94,7 @@ func newCustomOORRPCFixture(t *testing.T) *customOORRPCFixture { outpoint := testWalletOpsOutpoint(6) return &customOORRPCFixture{ + policy: policy, senderPriv: senderPriv, rpcServer: &RPCServer{ server: server, customInputLocks: make(map[wire.OutPoint]struct{}), diff --git a/waved/rpc_server.go b/waved/rpc_server.go index 912f35522..d057fa7df 100644 --- a/waved/rpc_server.go +++ b/waved/rpc_server.go @@ -338,7 +338,9 @@ func classifyCustomOORInputs(inputs []*waverpc.CustomOORInput) ([]wire.OutPoint, len(input.GetSpendPath()) > 0 || input.GetAmountSat() != 0 || len(input.GetPkScript()) > 0 || - len(input.GetExternalSignatures()) > 0 + len(input.GetExternalSignatures()) > 0 || + input.GetPreserveSourceOwners() || + len(input.GetPayoutSignatures()) > 0 if explicit { hasCustom = true } else { @@ -3239,6 +3241,12 @@ func (r *RPCServer) SendOOR(ctx context.Context, req *waverpc.SendOORRequest) ( if err != nil { return nil, err } + cooperative, err := checkCooperativeIntent( + req.CustomInputs, requestRecipients, true, + ) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } if req.GetExistingOnly() && req.GetIdempotencyKey() == "" { return nil, status.Errorf(codes.InvalidArgument, @@ -3485,6 +3493,17 @@ func (r *RPCServer) SendOOR(ctx context.Context, req *waverpc.SendOORRequest) ( } changeOutputDuration = time.Since(phaseStart) + if cooperative { + err := verifyCooperativeSubmit( + policy, selectedInputs, recipients, + ) + if err != nil { + return nil, status.Error( + codes.InvalidArgument, err.Error(), + ) + } + } + var dispatchRequestData []byte if req.GetIdempotencyKey() != "" { dispatchRequestData, err = oor.NewOutgoingReplayData( @@ -3718,6 +3737,12 @@ func (r *RPCServer) PrepareOOR(ctx context.Context, return nil, status.Errorf(codes.InvalidArgument, "custom "+ "inputs are required") } + _, err := checkCooperativeIntent( + req.CustomInputs, []*waverpc.Output{req.Recipient}, false, + ) + if err != nil { + return nil, status.Error(codes.InvalidArgument, err.Error()) + } if r.server.vtxoStore == nil { return nil, status.Errorf(codes.Internal, "VTXO store not "+ @@ -3863,6 +3888,23 @@ func (r *RPCServer) SignOORCustomInput(ctx context.Context, return nil, err } + if pkg := req.GetCooperativePackage(); pkg != nil { + if req.CustomInput != nil || len(req.CheckpointPsbt) != 0 { + return nil, status.Error( + codes.InvalidArgument, "cannot mix package "+ + "and checkpoint-only signing", + ) + } + + return r.signCooperativePackage(ctx, pkg) + } + if req.GetCustomInput().GetPreserveSourceOwners() { + return nil, status.Error( + codes.InvalidArgument, + "cooperative signing requires both unsigned packets", + ) + } + if req.GetCustomInput() == nil { return nil, status.Errorf(codes.InvalidArgument, "custom "+ "input is required") @@ -3921,12 +3963,7 @@ func (r *RPCServer) SignOORCustomInput(ctx context.Context, } return &waverpc.SignOORCustomInputResponse{ - Signature: &waverpc.TaprootScriptSignature{ - Pubkey: sig.PubKey.SerializeCompressed(), - WitnessScript: sig.WitnessScript, - Signature: sig.Signature, - Sighash: uint32(sig.SigHash), - }, + Signature: rpcScriptSignature(sig), }, nil } diff --git a/waved/wallet_ops.go b/waved/wallet_ops.go index da4f47117..2bec0c9cf 100644 --- a/waved/wallet_ops.go +++ b/waved/wallet_ops.go @@ -188,6 +188,13 @@ func BuildCustomTransferInputs(ctx context.Context, store vtxo.VTXOStore, inputs := make([]oor.TransferInput, 0, len(customInputs)) for _, ci := range customInputs { + if ci == nil { + return nil, fmt.Errorf("missing custom input") + } + if !ci.PreserveSourceOwners && len(ci.PayoutSignatures) != 0 { + return nil, fmt.Errorf("payout signatures require " + + "preserve_source_owners") + } outpoint, err := parseOutpointString(ci.Outpoint) if err != nil { return nil, fmt.Errorf("parse outpoint %q: %w", @@ -212,6 +219,14 @@ func BuildCustomTransferInputs(ctx context.Context, store vtxo.VTXOStore, desc = stored } + if ci.PreserveSourceOwners { + if err := checkCooperativeFunding( + ci, desc, operatorKey, + ); err != nil { + return nil, err + } + } + // If the caller provided amount and pkscript, build // the descriptor directly (for VTXOs not in the local // store, e.g., received via OOR). @@ -288,8 +303,12 @@ func BuildCustomTransferInputs(ctx context.Context, store vtxo.VTXOStore, } if len(ci.SpendPath) > 0 { + deriveOwnerLeaf := findSettlementOwnerLeaf + if ci.PreserveSourceOwners { + deriveOwnerLeaf = cooperativeOwnerLeaf + } ownerLeaf, ownerLeafPolicy, err = - findSettlementOwnerLeaf( + deriveOwnerLeaf( template, clientKey.PubKey, operatorKey, ci.SpendPath, ) @@ -343,6 +362,15 @@ func BuildCustomTransferInputs(ctx context.Context, store vtxo.VTXOStore, "for %s: %w", outpoint, err) } + payoutSigs, err := customTaprootScriptSignatures( + ci.PayoutSignatures, + ) + if err != nil { + return nil, fmt.Errorf("decode payout signatures: %w", + err) + } + + input.ExternalArkSignatures = payoutSigs inputs = append(inputs, input) } diff --git a/waverpc/daemon.pb.go b/waverpc/daemon.pb.go index 99828d7b8..9f1c16ef8 100644 --- a/waverpc/daemon.pb.go +++ b/waverpc/daemon.pb.go @@ -4073,8 +4073,12 @@ type CustomOORInput struct { // validates the policy/spend-path binding and adds its own signature before // assembling the final witness. ExternalSignatures []*TaprootScriptSignature `protobuf:"bytes,6,rep,name=external_signatures,json=externalSignatures,proto3" json:"external_signatures,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Preserve the exact funded multisig leaf on the checkpoint output. + PreserveSourceOwners bool `protobuf:"varint,7,opt,name=preserve_source_owners,json=preserveSourceOwners,proto3" json:"preserve_source_owners,omitempty"` + // Independent co-owner signatures on the final Ark payout. + PayoutSignatures []*TaprootScriptSignature `protobuf:"bytes,8,rep,name=payout_signatures,json=payoutSignatures,proto3" json:"payout_signatures,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *CustomOORInput) Reset() { @@ -4149,6 +4153,20 @@ func (x *CustomOORInput) GetExternalSignatures() []*TaprootScriptSignature { return nil } +func (x *CustomOORInput) GetPreserveSourceOwners() bool { + if x != nil { + return x.PreserveSourceOwners + } + return false +} + +func (x *CustomOORInput) GetPayoutSignatures() []*TaprootScriptSignature { + if x != nil { + return x.PayoutSignatures + } + return nil +} + // TaprootScriptSignature carries one externally produced tapscript signature // for a custom OOR input. Keep this in sync with // swaprpc.TaprootScriptSignature. @@ -4519,8 +4537,10 @@ type SignOORCustomInputRequest struct { CustomInput *CustomOORInput `protobuf:"bytes,1,opt,name=custom_input,json=customInput,proto3" json:"custom_input,omitempty"` // checkpoint_psbt is the prepared checkpoint PSBT to sign. CheckpointPsbt []byte `protobuf:"bytes,2,opt,name=checkpoint_psbt,json=checkpointPsbt,proto3" json:"checkpoint_psbt,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Mutually exclusive with the legacy checkpoint-only signing fields. + CooperativePackage *CooperativeOORPackage `protobuf:"bytes,3,opt,name=cooperative_package,json=cooperativePackage,proto3" json:"cooperative_package,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *SignOORCustomInputRequest) Reset() { @@ -4567,12 +4587,21 @@ func (x *SignOORCustomInputRequest) GetCheckpointPsbt() []byte { return nil } +func (x *SignOORCustomInputRequest) GetCooperativePackage() *CooperativeOORPackage { + if x != nil { + return x.CooperativePackage + } + return nil +} + type SignOORCustomInputResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // signature is the daemon identity key's tapscript signature. - Signature *TaprootScriptSignature `protobuf:"bytes,1,opt,name=signature,proto3" json:"signature,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + Signature *TaprootScriptSignature `protobuf:"bytes,1,opt,name=signature,proto3" json:"signature,omitempty"` + // Final Ark-input signature, present only for cooperative_package. + PayoutSignature *TaprootScriptSignature `protobuf:"bytes,2,opt,name=payout_signature,json=payoutSignature,proto3" json:"payout_signature,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *SignOORCustomInputResponse) Reset() { @@ -4612,6 +4641,13 @@ func (x *SignOORCustomInputResponse) GetSignature() *TaprootScriptSignature { return nil } +func (x *SignOORCustomInputResponse) GetPayoutSignature() *TaprootScriptSignature { + if x != nil { + return x.PayoutSignature + } + return nil +} + type SignVTXOForfeitRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // vtxo_outpoint identifies the VTXO input at forfeit tx input index 0. @@ -12304,6 +12340,76 @@ func (x *DeriveSwapPreimageResponse) GetPreimage() []byte { return nil } +// CooperativeOORPackage pairs the authorized intent with the exact unsigned +// packets. The wallet reconstructs both before releasing either signature. +type CooperativeOORPackage struct { + state protoimpl.MessageState `protogen:"open.v1"` + CustomInput *CustomOORInput `protobuf:"bytes,1,opt,name=custom_input,json=customInput,proto3" json:"custom_input,omitempty"` + Recipient *Output `protobuf:"bytes,2,opt,name=recipient,proto3" json:"recipient,omitempty"` + CheckpointPsbt []byte `protobuf:"bytes,3,opt,name=checkpoint_psbt,json=checkpointPsbt,proto3" json:"checkpoint_psbt,omitempty"` + ArkPsbt []byte `protobuf:"bytes,4,opt,name=ark_psbt,json=arkPsbt,proto3" json:"ark_psbt,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CooperativeOORPackage) Reset() { + *x = CooperativeOORPackage{} + mi := &file_daemon_proto_msgTypes[149] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CooperativeOORPackage) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CooperativeOORPackage) ProtoMessage() {} + +func (x *CooperativeOORPackage) ProtoReflect() protoreflect.Message { + mi := &file_daemon_proto_msgTypes[149] + 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 CooperativeOORPackage.ProtoReflect.Descriptor instead. +func (*CooperativeOORPackage) Descriptor() ([]byte, []int) { + return file_daemon_proto_rawDescGZIP(), []int{149} +} + +func (x *CooperativeOORPackage) GetCustomInput() *CustomOORInput { + if x != nil { + return x.CustomInput + } + return nil +} + +func (x *CooperativeOORPackage) GetRecipient() *Output { + if x != nil { + return x.Recipient + } + return nil +} + +func (x *CooperativeOORPackage) GetCheckpointPsbt() []byte { + if x != nil { + return x.CheckpointPsbt + } + return nil +} + +func (x *CooperativeOORPackage) GetArkPsbt() []byte { + if x != nil { + return x.ArkPsbt + } + return nil +} + var File_daemon_proto protoreflect.FileDescriptor const file_daemon_proto_rawDesc = "" + @@ -12533,7 +12639,7 @@ const file_daemon_proto_rawDesc = "" + "\rcustom_inputs\x18\x03 \x03(\v2\x17.waverpc.CustomOORInputR\fcustomInputs\x12'\n" + "\x0fidempotency_key\x18\x04 \x01(\tR\x0eidempotencyKey\x12A\n" + "\x1dadmission_deadline_unix_nanos\x18\x05 \x01(\x03R\x1aadmissionDeadlineUnixNanos\x12#\n" + - "\rexisting_only\x18\x06 \x01(\bR\fexistingOnly\"\x8b\x02\n" + + "\rexisting_only\x18\x06 \x01(\bR\fexistingOnly\"\x8f\x03\n" + "\x0eCustomOORInput\x12\x1a\n" + "\boutpoint\x18\x01 \x01(\tR\boutpoint\x120\n" + "\x14vtxo_policy_template\x18\x02 \x01(\fR\x12vtxoPolicyTemplate\x12\x1d\n" + @@ -12542,7 +12648,9 @@ const file_daemon_proto_rawDesc = "" + "\n" + "amount_sat\x18\x04 \x01(\x03R\tamountSat\x12\x1b\n" + "\tpk_script\x18\x05 \x01(\fR\bpkScript\x12P\n" + - "\x13external_signatures\x18\x06 \x03(\v2\x1f.waverpc.TaprootScriptSignatureR\x12externalSignatures\"\x8f\x01\n" + + "\x13external_signatures\x18\x06 \x03(\v2\x1f.waverpc.TaprootScriptSignatureR\x12externalSignatures\x124\n" + + "\x16preserve_source_owners\x18\a \x01(\bR\x14preserveSourceOwners\x12L\n" + + "\x11payout_signatures\x18\b \x03(\v2\x1f.waverpc.TaprootScriptSignatureR\x10payoutSignatures\"\x8f\x01\n" + "\x16TaprootScriptSignature\x12\x16\n" + "\x06pubkey\x18\x01 \x01(\fR\x06pubkey\x12%\n" + "\x0ewitness_script\x18\x02 \x01(\fR\rwitnessScript\x12\x1c\n" + @@ -12567,12 +12675,14 @@ 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\"\x80\x01\n" + + "session_id\x18\x04 \x01(\tR\tsessionId\"\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\"[\n" + + "\x0fcheckpoint_psbt\x18\x02 \x01(\fR\x0echeckpointPsbt\x12O\n" + + "\x13cooperative_package\x18\x03 \x01(\v2\x1e.waverpc.CooperativeOORPackageR\x12cooperativePackage\"\xa7\x01\n" + "\x1aSignOORCustomInputResponse\x12=\n" + - "\tsignature\x18\x01 \x01(\v2\x1f.waverpc.TaprootScriptSignatureR\tsignature\"\xd6\x03\n" + + "\tsignature\x18\x01 \x01(\v2\x1f.waverpc.TaprootScriptSignatureR\tsignature\x12J\n" + + "\x10payout_signature\x18\x02 \x01(\v2\x1f.waverpc.TaprootScriptSignatureR\x0fpayoutSignature\"\xd6\x03\n" + "\x16SignVTXOForfeitRequest\x12#\n" + "\rvtxo_outpoint\x18\x01 \x01(\tR\fvtxoOutpoint\x12&\n" + "\x0fvtxo_amount_sat\x18\x02 \x01(\x03R\rvtxoAmountSat\x12$\n" + @@ -13158,7 +13268,12 @@ const file_daemon_proto_rawDesc = "" + "\x19DeriveSwapPreimageRequest\x12'\n" + "\x0frecovery_params\x18\x01 \x01(\fR\x0erecoveryParams\"8\n" + "\x1aDeriveSwapPreimageResponse\x12\x1a\n" + - "\bpreimage\x18\x01 \x01(\fR\bpreimage*\x8d\x01\n" + + "\bpreimage\x18\x01 \x01(\fR\bpreimage\"\xc6\x01\n" + + "\x15CooperativeOORPackage\x12:\n" + + "\fcustom_input\x18\x01 \x01(\v2\x17.waverpc.CustomOORInputR\vcustomInput\x12-\n" + + "\trecipient\x18\x02 \x01(\v2\x0f.waverpc.OutputR\trecipient\x12'\n" + + "\x0fcheckpoint_psbt\x18\x03 \x01(\fR\x0echeckpointPsbt\x12\x19\n" + + "\bark_psbt\x18\x04 \x01(\fR\aarkPsbt*\x8d\x01\n" + "\vWalletState\x12\x1c\n" + "\x18WALLET_STATE_UNSPECIFIED\x10\x00\x12\x15\n" + "\x11WALLET_STATE_NONE\x10\x01\x12\x17\n" + @@ -13335,7 +13450,7 @@ func file_daemon_proto_rawDescGZIP() []byte { } var file_daemon_proto_enumTypes = make([]protoimpl.EnumInfo, 12) -var file_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 152) +var file_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 153) var file_daemon_proto_goTypes = []any{ (WalletState)(0), // 0: waverpc.WalletState (VTXOStatus)(0), // 1: waverpc.VTXOStatus @@ -13498,9 +13613,10 @@ var file_daemon_proto_goTypes = []any{ (*ListPermissionsResponse)(nil), // 158: waverpc.ListPermissionsResponse (*DeriveSwapPreimageRequest)(nil), // 159: waverpc.DeriveSwapPreimageRequest (*DeriveSwapPreimageResponse)(nil), // 160: waverpc.DeriveSwapPreimageResponse - nil, // 161: waverpc.LeaveVTXOsRequest.DestinationsEntry - nil, // 162: waverpc.LeaveVTXOsResponse.ErrorsEntry - nil, // 163: waverpc.ListPermissionsResponse.MethodPermissionsEntry + (*CooperativeOORPackage)(nil), // 161: waverpc.CooperativeOORPackage + nil, // 162: waverpc.LeaveVTXOsRequest.DestinationsEntry + nil, // 163: waverpc.LeaveVTXOsResponse.ErrorsEntry + nil, // 164: waverpc.ListPermissionsResponse.MethodPermissionsEntry } var file_daemon_proto_depIdxs = []int32{ 0, // 0: waverpc.GetInfoResponse.wallet_state:type_name -> waverpc.WalletState @@ -13522,190 +13638,195 @@ var file_daemon_proto_depIdxs = []int32{ 49, // 16: waverpc.SendOORRequest.recipients:type_name -> waverpc.Output 53, // 17: waverpc.SendOORRequest.custom_inputs:type_name -> waverpc.CustomOORInput 54, // 18: waverpc.CustomOORInput.external_signatures:type_name -> waverpc.TaprootScriptSignature - 49, // 19: waverpc.PrepareOORRequest.recipient:type_name -> waverpc.Output - 53, // 20: waverpc.PrepareOORRequest.custom_inputs:type_name -> waverpc.CustomOORInput - 57, // 21: waverpc.PrepareOORResponse.custom_inputs:type_name -> waverpc.PreparedOORCustomInput - 53, // 22: waverpc.SignOORCustomInputRequest.custom_input:type_name -> waverpc.CustomOORInput - 54, // 23: waverpc.SignOORCustomInputResponse.signature:type_name -> waverpc.TaprootScriptSignature - 3, // 24: waverpc.ForfeitSigningContext.signing_route:type_name -> waverpc.ForfeitSigningRoute - 64, // 25: waverpc.RefreshVTXOsRequest.outpoints:type_name -> waverpc.OutpointSelection - 67, // 26: waverpc.RefreshVTXOsResponse.fee_estimate:type_name -> waverpc.RefreshFeeEstimate - 68, // 27: waverpc.RefreshFeeEstimate.outpoints:type_name -> waverpc.OutpointFeeEstimate - 63, // 28: waverpc.CustomRefreshVTXOInput.forfeit_signing_context:type_name -> waverpc.ForfeitSigningContext - 69, // 29: waverpc.RefreshCustomVTXOsRequest.inputs:type_name -> waverpc.CustomRefreshVTXOInput - 70, // 30: waverpc.RefreshCustomVTXOsRequest.outputs:type_name -> waverpc.CustomRefreshVTXOOutput - 3, // 31: waverpc.PendingForfeitParticipantSignatureRequest.signing_route:type_name -> waverpc.ForfeitSigningRoute - 73, // 32: waverpc.ListPendingForfeitParticipantSignatureRequestsResponse.requests:type_name -> waverpc.PendingForfeitParticipantSignatureRequest - 76, // 33: waverpc.SubmitForfeitParticipantSignaturesRequest.signatures:type_name -> waverpc.ForfeitParticipantSignature - 64, // 34: waverpc.LeaveVTXOsRequest.outpoints:type_name -> waverpc.OutpointSelection - 79, // 35: waverpc.LeaveVTXOsRequest.default_destination:type_name -> waverpc.LeaveDestination - 161, // 36: waverpc.LeaveVTXOsRequest.destinations:type_name -> waverpc.LeaveVTXOsRequest.DestinationsEntry - 162, // 37: waverpc.LeaveVTXOsResponse.errors:type_name -> waverpc.LeaveVTXOsResponse.ErrorsEntry - 79, // 38: waverpc.SendOnChainRequest.destination:type_name -> waverpc.LeaveDestination - 91, // 39: waverpc.ListAssetDepositsResponse.deposits:type_name -> waverpc.AssetDeposit - 4, // 40: waverpc.AssetDeposit.status:type_name -> waverpc.AssetDepositStatus - 99, // 41: waverpc.ListOwnedAssetsResponse.assets:type_name -> waverpc.OwnedAsset - 103, // 42: waverpc.SweepBoardingUTXOsResponse.sweepable_outputs:type_name -> waverpc.BoardingSweepOutput - 106, // 43: waverpc.BoardingSweep.inputs:type_name -> waverpc.BoardingSweepInput - 107, // 44: waverpc.ListBoardingSweepsResponse.sweeps:type_name -> waverpc.BoardingSweep - 5, // 45: waverpc.RoundInfo.state:type_name -> waverpc.RoundState - 109, // 46: waverpc.RoundInfo.vtxos:type_name -> waverpc.RoundVTXOInfo - 110, // 47: waverpc.RoundInfo.batch_window:type_name -> waverpc.ScheduledBatchWindow - 5, // 48: waverpc.ListRoundsRequest.state_filter:type_name -> waverpc.RoundState - 111, // 49: waverpc.GetRoundResponse.round:type_name -> waverpc.RoundInfo - 111, // 50: waverpc.ListRoundsResponse.rounds:type_name -> waverpc.RoundInfo - 111, // 51: waverpc.WatchRoundsResponse.round:type_name -> waverpc.RoundInfo - 6, // 52: waverpc.OORSessionInfo.direction:type_name -> waverpc.OORSessionDirection - 7, // 53: waverpc.OORSessionInfo.status:type_name -> waverpc.OORSessionStatus - 6, // 54: waverpc.ListOORSessionsRequest.direction_filter:type_name -> waverpc.OORSessionDirection - 7, // 55: waverpc.ListOORSessionsRequest.status_filter:type_name -> waverpc.OORSessionStatus - 118, // 56: waverpc.ListOORSessionsResponse.sessions:type_name -> waverpc.OORSessionInfo - 118, // 57: waverpc.GetOORSessionResponse.session:type_name -> waverpc.OORSessionInfo - 126, // 58: waverpc.GetFeeHistoryResponse.entries:type_name -> waverpc.FeeHistoryEntry - 129, // 59: waverpc.ListTransactionsResponse.transactions:type_name -> waverpc.TransactionHistoryEntry - 8, // 60: waverpc.GetUnrollStatusResponse.status:type_name -> waverpc.UnrollJobStatus - 134, // 61: waverpc.GetUnrollStatusResponse.progress:type_name -> waverpc.UnrollProgress - 135, // 62: waverpc.GetUnrollStatusResponse.csv:type_name -> waverpc.UnrollCSV - 136, // 63: waverpc.GetUnrollStatusResponse.fees:type_name -> waverpc.UnrollFees - 9, // 64: waverpc.ArmVHTLCRecoveryRequest.direction:type_name -> waverpc.VHTLCRecoveryDirection - 10, // 65: waverpc.ArmVHTLCRecoveryRequest.action:type_name -> waverpc.VHTLCRecoveryAction - 148, // 66: waverpc.ArmVHTLCRecoveryResponse.status:type_name -> waverpc.VHTLCRecoveryStatus - 148, // 67: waverpc.EscalateVHTLCRecoveryResponse.status:type_name -> waverpc.VHTLCRecoveryStatus - 148, // 68: waverpc.CancelVHTLCRecoveryResponse.status:type_name -> waverpc.VHTLCRecoveryStatus - 148, // 69: waverpc.GetVHTLCRecoveryStatusResponse.status:type_name -> waverpc.VHTLCRecoveryStatus - 148, // 70: waverpc.ListVHTLCRecoveriesResponse.statuses:type_name -> waverpc.VHTLCRecoveryStatus - 9, // 71: waverpc.VHTLCRecoveryStatus.direction:type_name -> waverpc.VHTLCRecoveryDirection - 10, // 72: waverpc.VHTLCRecoveryStatus.action:type_name -> waverpc.VHTLCRecoveryAction - 11, // 73: waverpc.VHTLCRecoveryStatus.state:type_name -> waverpc.VHTLCRecoveryState - 8, // 74: waverpc.VHTLCRecoveryStatus.unroll_status:type_name -> waverpc.UnrollJobStatus - 153, // 75: waverpc.BakeMacaroonRequest.permissions:type_name -> waverpc.MacaroonPermission - 153, // 76: waverpc.MacaroonPermissionList.permissions:type_name -> waverpc.MacaroonPermission - 163, // 77: waverpc.ListPermissionsResponse.method_permissions:type_name -> waverpc.ListPermissionsResponse.MethodPermissionsEntry - 79, // 78: waverpc.LeaveVTXOsRequest.DestinationsEntry.value:type_name -> waverpc.LeaveDestination - 156, // 79: waverpc.ListPermissionsResponse.MethodPermissionsEntry.value:type_name -> waverpc.MacaroonPermissionList - 12, // 80: waverpc.DaemonService.GetInfo:input_type -> waverpc.GetInfoRequest - 15, // 81: waverpc.DaemonService.GenSeed:input_type -> waverpc.GenSeedRequest - 17, // 82: waverpc.DaemonService.InitWallet:input_type -> waverpc.InitWalletRequest - 19, // 83: waverpc.DaemonService.UnlockWallet:input_type -> waverpc.UnlockWalletRequest - 21, // 84: waverpc.DaemonService.GetBalance:input_type -> waverpc.GetBalanceRequest - 27, // 85: waverpc.DaemonService.ListVTXOs:input_type -> waverpc.ListVTXOsRequest - 29, // 86: waverpc.DaemonService.NewAddress:input_type -> waverpc.NewAddressRequest - 31, // 87: waverpc.DaemonService.NewReceiveScript:input_type -> waverpc.NewReceiveScriptRequest - 33, // 88: waverpc.DaemonService.ReceiveAuthKey:input_type -> waverpc.ReceiveAuthKeyRequest - 35, // 89: waverpc.DaemonService.SignReceiveAuthMessage:input_type -> waverpc.SignReceiveAuthMessageRequest - 37, // 90: waverpc.DaemonService.SignReceiveAuthMessageCompact:input_type -> waverpc.SignReceiveAuthMessageCompactRequest - 39, // 91: waverpc.DaemonService.SignIdentitySchnorr:input_type -> waverpc.SignIdentitySchnorrRequest - 41, // 92: waverpc.DaemonService.ReceiveAuthECDH:input_type -> waverpc.ReceiveAuthECDHRequest - 159, // 93: waverpc.DaemonService.DeriveSwapPreimage:input_type -> waverpc.DeriveSwapPreimageRequest - 43, // 94: waverpc.DaemonService.GetIndexedVTXOByPkScript:input_type -> waverpc.GetIndexedVTXOByPkScriptRequest - 45, // 95: waverpc.DaemonService.GetVTXOExpiryInfo:input_type -> waverpc.GetVTXOExpiryInfoRequest - 47, // 96: waverpc.DaemonService.GetIndexedOORSessionByTxid:input_type -> waverpc.GetIndexedOORSessionByTxidRequest - 50, // 97: waverpc.DaemonService.SendVTXO:input_type -> waverpc.SendVTXORequest - 52, // 98: waverpc.DaemonService.SendOOR:input_type -> waverpc.SendOORRequest - 56, // 99: waverpc.DaemonService.PrepareOOR:input_type -> waverpc.PrepareOORRequest - 59, // 100: waverpc.DaemonService.SignOORCustomInput:input_type -> waverpc.SignOORCustomInputRequest - 61, // 101: waverpc.DaemonService.SignVTXOForfeit:input_type -> waverpc.SignVTXOForfeitRequest - 65, // 102: waverpc.DaemonService.RefreshVTXOs:input_type -> waverpc.RefreshVTXOsRequest - 71, // 103: waverpc.DaemonService.RefreshCustomVTXOs:input_type -> waverpc.RefreshCustomVTXOsRequest - 74, // 104: waverpc.DaemonService.ListPendingForfeitParticipantSignatureRequests:input_type -> waverpc.ListPendingForfeitParticipantSignatureRequestsRequest - 77, // 105: waverpc.DaemonService.SubmitForfeitParticipantSignatures:input_type -> waverpc.SubmitForfeitParticipantSignaturesRequest - 80, // 106: waverpc.DaemonService.LeaveVTXOs:input_type -> waverpc.LeaveVTXOsRequest - 82, // 107: waverpc.DaemonService.SendOnChain:input_type -> waverpc.SendOnChainRequest - 84, // 108: waverpc.DaemonService.Board:input_type -> waverpc.BoardRequest - 86, // 109: waverpc.DaemonService.DepositAsset:input_type -> waverpc.DepositAssetRequest - 87, // 110: waverpc.DaemonService.ListAssetDeposits:input_type -> waverpc.ListAssetDepositsRequest - 88, // 111: waverpc.DaemonService.BoardAssetDeposit:input_type -> waverpc.BoardAssetDepositRequest - 89, // 112: waverpc.DaemonService.ClaimAssetDeposit:input_type -> waverpc.ClaimAssetDepositRequest - 92, // 113: waverpc.DaemonService.NewAssetReceiveKeys:input_type -> waverpc.NewAssetReceiveKeysRequest - 94, // 114: waverpc.DaemonService.ImportAssetProof:input_type -> waverpc.ImportAssetProofRequest - 97, // 115: waverpc.DaemonService.ListOwnedAssets:input_type -> waverpc.ListOwnedAssetsRequest - 95, // 116: waverpc.DaemonService.NewAssetFundingAddress:input_type -> waverpc.NewAssetFundingAddressRequest - 100, // 117: waverpc.DaemonService.JoinNextRound:input_type -> waverpc.JoinNextRoundRequest - 102, // 118: waverpc.DaemonService.SweepBoardingUTXOs:input_type -> waverpc.SweepBoardingUTXOsRequest - 105, // 119: waverpc.DaemonService.ListBoardingSweeps:input_type -> waverpc.ListBoardingSweepsRequest - 112, // 120: waverpc.DaemonService.ListRounds:input_type -> waverpc.ListRoundsRequest - 113, // 121: waverpc.DaemonService.GetRound:input_type -> waverpc.GetRoundRequest - 116, // 122: waverpc.DaemonService.WatchRounds:input_type -> waverpc.WatchRoundsRequest - 119, // 123: waverpc.DaemonService.ListOORSessions:input_type -> waverpc.ListOORSessionsRequest - 121, // 124: waverpc.DaemonService.GetOORSession:input_type -> waverpc.GetOORSessionRequest - 123, // 125: waverpc.DaemonService.EstimateFee:input_type -> waverpc.EstimateFeeRequest - 125, // 126: waverpc.DaemonService.GetFeeHistory:input_type -> waverpc.GetFeeHistoryRequest - 128, // 127: waverpc.DaemonService.ListTransactions:input_type -> waverpc.ListTransactionsRequest - 131, // 128: waverpc.DaemonService.Unroll:input_type -> waverpc.UnrollRequest - 133, // 129: waverpc.DaemonService.GetUnrollStatus:input_type -> waverpc.GetUnrollStatusRequest - 138, // 130: waverpc.DaemonService.ArmVHTLCRecovery:input_type -> waverpc.ArmVHTLCRecoveryRequest - 140, // 131: waverpc.DaemonService.EscalateVHTLCRecovery:input_type -> waverpc.EscalateVHTLCRecoveryRequest - 142, // 132: waverpc.DaemonService.CancelVHTLCRecovery:input_type -> waverpc.CancelVHTLCRecoveryRequest - 144, // 133: waverpc.DaemonService.GetVHTLCRecoveryStatus:input_type -> waverpc.GetVHTLCRecoveryStatusRequest - 146, // 134: waverpc.DaemonService.ListVHTLCRecoveries:input_type -> waverpc.ListVHTLCRecoveriesRequest - 149, // 135: waverpc.DaemonService.SignOutSwapHtlcAck:input_type -> waverpc.SignOutSwapHtlcAckRequest - 151, // 136: waverpc.DaemonService.SignCreditAccountAuthorization:input_type -> waverpc.SignCreditAccountAuthorizationRequest - 154, // 137: waverpc.MacaroonService.BakeMacaroon:input_type -> waverpc.BakeMacaroonRequest - 157, // 138: waverpc.MacaroonService.ListPermissions:input_type -> waverpc.ListPermissionsRequest - 13, // 139: waverpc.DaemonService.GetInfo:output_type -> waverpc.GetInfoResponse - 16, // 140: waverpc.DaemonService.GenSeed:output_type -> waverpc.GenSeedResponse - 18, // 141: waverpc.DaemonService.InitWallet:output_type -> waverpc.InitWalletResponse - 20, // 142: waverpc.DaemonService.UnlockWallet:output_type -> waverpc.UnlockWalletResponse - 22, // 143: waverpc.DaemonService.GetBalance:output_type -> waverpc.GetBalanceResponse - 28, // 144: waverpc.DaemonService.ListVTXOs:output_type -> waverpc.ListVTXOsResponse - 30, // 145: waverpc.DaemonService.NewAddress:output_type -> waverpc.NewAddressResponse - 32, // 146: waverpc.DaemonService.NewReceiveScript:output_type -> waverpc.NewReceiveScriptResponse - 34, // 147: waverpc.DaemonService.ReceiveAuthKey:output_type -> waverpc.ReceiveAuthKeyResponse - 36, // 148: waverpc.DaemonService.SignReceiveAuthMessage:output_type -> waverpc.SignReceiveAuthMessageResponse - 38, // 149: waverpc.DaemonService.SignReceiveAuthMessageCompact:output_type -> waverpc.SignReceiveAuthMessageCompactResponse - 40, // 150: waverpc.DaemonService.SignIdentitySchnorr:output_type -> waverpc.SignIdentitySchnorrResponse - 42, // 151: waverpc.DaemonService.ReceiveAuthECDH:output_type -> waverpc.ReceiveAuthECDHResponse - 160, // 152: waverpc.DaemonService.DeriveSwapPreimage:output_type -> waverpc.DeriveSwapPreimageResponse - 44, // 153: waverpc.DaemonService.GetIndexedVTXOByPkScript:output_type -> waverpc.GetIndexedVTXOByPkScriptResponse - 46, // 154: waverpc.DaemonService.GetVTXOExpiryInfo:output_type -> waverpc.GetVTXOExpiryInfoResponse - 48, // 155: waverpc.DaemonService.GetIndexedOORSessionByTxid:output_type -> waverpc.GetIndexedOORSessionByTxidResponse - 51, // 156: waverpc.DaemonService.SendVTXO:output_type -> waverpc.SendVTXOResponse - 55, // 157: waverpc.DaemonService.SendOOR:output_type -> waverpc.SendOORResponse - 58, // 158: waverpc.DaemonService.PrepareOOR:output_type -> waverpc.PrepareOORResponse - 60, // 159: waverpc.DaemonService.SignOORCustomInput:output_type -> waverpc.SignOORCustomInputResponse - 62, // 160: waverpc.DaemonService.SignVTXOForfeit:output_type -> waverpc.SignVTXOForfeitResponse - 66, // 161: waverpc.DaemonService.RefreshVTXOs:output_type -> waverpc.RefreshVTXOsResponse - 72, // 162: waverpc.DaemonService.RefreshCustomVTXOs:output_type -> waverpc.RefreshCustomVTXOsResponse - 75, // 163: waverpc.DaemonService.ListPendingForfeitParticipantSignatureRequests:output_type -> waverpc.ListPendingForfeitParticipantSignatureRequestsResponse - 78, // 164: waverpc.DaemonService.SubmitForfeitParticipantSignatures:output_type -> waverpc.SubmitForfeitParticipantSignaturesResponse - 81, // 165: waverpc.DaemonService.LeaveVTXOs:output_type -> waverpc.LeaveVTXOsResponse - 83, // 166: waverpc.DaemonService.SendOnChain:output_type -> waverpc.SendOnChainResponse - 85, // 167: waverpc.DaemonService.Board:output_type -> waverpc.BoardResponse - 91, // 168: waverpc.DaemonService.DepositAsset:output_type -> waverpc.AssetDeposit - 90, // 169: waverpc.DaemonService.ListAssetDeposits:output_type -> waverpc.ListAssetDepositsResponse - 91, // 170: waverpc.DaemonService.BoardAssetDeposit:output_type -> waverpc.AssetDeposit - 91, // 171: waverpc.DaemonService.ClaimAssetDeposit:output_type -> waverpc.AssetDeposit - 93, // 172: waverpc.DaemonService.NewAssetReceiveKeys:output_type -> waverpc.AssetReceiveKeys - 99, // 173: waverpc.DaemonService.ImportAssetProof:output_type -> waverpc.OwnedAsset - 98, // 174: waverpc.DaemonService.ListOwnedAssets:output_type -> waverpc.ListOwnedAssetsResponse - 96, // 175: waverpc.DaemonService.NewAssetFundingAddress:output_type -> waverpc.AssetFundingAddress - 101, // 176: waverpc.DaemonService.JoinNextRound:output_type -> waverpc.JoinNextRoundResponse - 104, // 177: waverpc.DaemonService.SweepBoardingUTXOs:output_type -> waverpc.SweepBoardingUTXOsResponse - 108, // 178: waverpc.DaemonService.ListBoardingSweeps:output_type -> waverpc.ListBoardingSweepsResponse - 115, // 179: waverpc.DaemonService.ListRounds:output_type -> waverpc.ListRoundsResponse - 114, // 180: waverpc.DaemonService.GetRound:output_type -> waverpc.GetRoundResponse - 117, // 181: waverpc.DaemonService.WatchRounds:output_type -> waverpc.WatchRoundsResponse - 120, // 182: waverpc.DaemonService.ListOORSessions:output_type -> waverpc.ListOORSessionsResponse - 122, // 183: waverpc.DaemonService.GetOORSession:output_type -> waverpc.GetOORSessionResponse - 124, // 184: waverpc.DaemonService.EstimateFee:output_type -> waverpc.EstimateFeeResponse - 127, // 185: waverpc.DaemonService.GetFeeHistory:output_type -> waverpc.GetFeeHistoryResponse - 130, // 186: waverpc.DaemonService.ListTransactions:output_type -> waverpc.ListTransactionsResponse - 132, // 187: waverpc.DaemonService.Unroll:output_type -> waverpc.UnrollResponse - 137, // 188: waverpc.DaemonService.GetUnrollStatus:output_type -> waverpc.GetUnrollStatusResponse - 139, // 189: waverpc.DaemonService.ArmVHTLCRecovery:output_type -> waverpc.ArmVHTLCRecoveryResponse - 141, // 190: waverpc.DaemonService.EscalateVHTLCRecovery:output_type -> waverpc.EscalateVHTLCRecoveryResponse - 143, // 191: waverpc.DaemonService.CancelVHTLCRecovery:output_type -> waverpc.CancelVHTLCRecoveryResponse - 145, // 192: waverpc.DaemonService.GetVHTLCRecoveryStatus:output_type -> waverpc.GetVHTLCRecoveryStatusResponse - 147, // 193: waverpc.DaemonService.ListVHTLCRecoveries:output_type -> waverpc.ListVHTLCRecoveriesResponse - 150, // 194: waverpc.DaemonService.SignOutSwapHtlcAck:output_type -> waverpc.SignOutSwapHtlcAckResponse - 152, // 195: waverpc.DaemonService.SignCreditAccountAuthorization:output_type -> waverpc.SignCreditAccountAuthorizationResponse - 155, // 196: waverpc.MacaroonService.BakeMacaroon:output_type -> waverpc.BakeMacaroonResponse - 158, // 197: waverpc.MacaroonService.ListPermissions:output_type -> waverpc.ListPermissionsResponse - 139, // [139:198] is the sub-list for method output_type - 80, // [80:139] is the sub-list for method input_type - 80, // [80:80] is the sub-list for extension type_name - 80, // [80:80] is the sub-list for extension extendee - 0, // [0:80] is the sub-list for field type_name + 54, // 19: waverpc.CustomOORInput.payout_signatures:type_name -> waverpc.TaprootScriptSignature + 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 } func init() { file_daemon_proto_init() } @@ -13746,7 +13867,7 @@ func file_daemon_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_daemon_proto_rawDesc), len(file_daemon_proto_rawDesc)), NumEnums: 12, - NumMessages: 152, + NumMessages: 153, NumExtensions: 0, NumServices: 2, }, diff --git a/waverpc/daemon.proto b/waverpc/daemon.proto index d1e1b754c..0ac018362 100644 --- a/waverpc/daemon.proto +++ b/waverpc/daemon.proto @@ -1237,6 +1237,12 @@ message CustomOORInput { // validates the policy/spend-path binding and adds its own signature before // assembling the final witness. repeated TaprootScriptSignature external_signatures = 6; + + // Preserve the exact funded multisig leaf on the checkpoint output. + bool preserve_source_owners = 7; + + // Independent co-owner signatures on the final Ark payout. + repeated TaprootScriptSignature payout_signatures = 8; } // TaprootScriptSignature carries one externally produced tapscript signature @@ -1331,11 +1337,17 @@ message SignOORCustomInputRequest { // checkpoint_psbt is the prepared checkpoint PSBT to sign. bytes checkpoint_psbt = 2; + + // Mutually exclusive with the legacy checkpoint-only signing fields. + CooperativeOORPackage cooperative_package = 3; } message SignOORCustomInputResponse { // signature is the daemon identity key's tapscript signature. TaprootScriptSignature signature = 1; + + // Final Ark-input signature, present only for cooperative_package. + TaprootScriptSignature payout_signature = 2; } message SignVTXOForfeitRequest { @@ -3379,3 +3391,12 @@ message DeriveSwapPreimageResponse { // The derived 32-byte preimage. Treat this response as secret. bytes preimage = 1; } + +// CooperativeOORPackage pairs the authorized intent with the exact unsigned +// packets. The wallet reconstructs both before releasing either signature. +message CooperativeOORPackage { + CustomOORInput custom_input = 1; + Output recipient = 2; + bytes checkpoint_psbt = 3; + bytes ark_psbt = 4; +}