diff --git a/db/AGENTS.md b/db/AGENTS.md index 144741a96..b4eea9cc5 100644 --- a/db/AGENTS.md +++ b/db/AGENTS.md @@ -165,7 +165,7 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/db.= 0), + PRIMARY KEY (outpoint_hash, outpoint_index), + FOREIGN KEY (outpoint_hash, outpoint_index) + REFERENCES vtxos (outpoint_hash, outpoint_index) ON DELETE CASCADE +); diff --git a/db/sqlc/models.go b/db/sqlc/models.go index 533d3b48d..4c7e5f3c1 100644 --- a/db/sqlc/models.go +++ b/db/sqlc/models.go @@ -644,6 +644,13 @@ type VtxoAncestryPath struct { CommitmentHeight int32 } +type VtxoManualExitOption struct { + OutpointHash []byte + OutpointIndex int32 + SweepScript []byte + FeeRateSatPerVbyte int64 +} + type WalletFeeSplit struct { Singleton int64 Candidate []byte diff --git a/db/sqlc/querier.go b/db/sqlc/querier.go index 7f0f5a370..c535aeb27 100644 --- a/db/sqlc/querier.go +++ b/db/sqlc/querier.go @@ -62,6 +62,7 @@ type Querier interface { DeleteActivityEventsByCanonicalID(ctx context.Context, canonicalID string) error DeleteAssetEngineProof(ctx context.Context, arg DeleteAssetEngineProofParams) error DeleteClientTreeTxids(ctx context.Context, arg DeleteClientTreeTxidsParams) error + DeleteManualExitOptions(ctx context.Context, arg DeleteManualExitOptionsParams) error DeleteOORPackageCheckpoints(ctx context.Context, sessionID []byte) error DeleteOrphanedPendingBoardIntents(ctx context.Context) error // A terminally failed intent is a durable record, not a sweepable orphan: @@ -143,6 +144,7 @@ type Querier interface { GetInternalKeyByID(ctx context.Context, id int64) (InternalKey, error) // Macaroon root key store queries. GetMacaroonRootKey(ctx context.Context, id []byte) (Macaroon, error) + GetManualExitOptions(ctx context.Context, arg GetManualExitOptionsParams) (GetManualExitOptionsRow, error) // A stored package may be a local transfer even if its registry row is gone. GetOORDiagnosticPackage(ctx context.Context, sessionID []byte) (GetOORDiagnosticPackageRow, error) GetOORDispatchAttemptByIdempotencyKey(ctx context.Context, idempotencyKey string) (OorDispatchAttempt, error) @@ -586,6 +588,7 @@ type Querier interface { // PullActivityEvents returns transition rows strictly after the cursor in // event_seq order, the resumable-subscribe replay primitive. PullActivityEvents(ctx context.Context, arg PullActivityEventsParams) ([]ActivityEvent, error) + PutManualExitOptions(ctx context.Context, arg PutManualExitOptionsParams) error // ReadCurrentActivityEvents bounds a replay page by a captured event ceiling, // while returning the current canonical projection for every selected event. // Removed internal activity has no replay rows and cannot reappear here. diff --git a/db/sqlc/queries/vtxo.sql b/db/sqlc/queries/vtxo.sql index c1911b4bc..c1f6b324b 100644 --- a/db/sqlc/queries/vtxo.sql +++ b/db/sqlc/queries/vtxo.sql @@ -183,3 +183,19 @@ WHERE (outpoint_hash, outpoint_index) > (sqlc.arg(through_hash), CAST(sqlc.arg(through_index) AS INTEGER)) ORDER BY outpoint_hash, outpoint_index LIMIT sqlc.arg(limit_count); + +-- name: PutManualExitOptions :exec +INSERT INTO vtxo_manual_exit_options ( + outpoint_hash, outpoint_index, sweep_script, fee_rate_sat_per_vbyte +) VALUES ($1, $2, $3, $4) +ON CONFLICT (outpoint_hash, outpoint_index) DO UPDATE SET + sweep_script = EXCLUDED.sweep_script, + fee_rate_sat_per_vbyte = EXCLUDED.fee_rate_sat_per_vbyte; + +-- name: GetManualExitOptions :one +SELECT sweep_script, fee_rate_sat_per_vbyte FROM vtxo_manual_exit_options +WHERE outpoint_hash = $1 AND outpoint_index = $2; + +-- name: DeleteManualExitOptions :exec +DELETE FROM vtxo_manual_exit_options +WHERE outpoint_hash = $1 AND outpoint_index = $2; diff --git a/db/sqlc/schemas/generated_schema.sql b/db/sqlc/schemas/generated_schema.sql index d6f335466..09c1c5afc 100644 --- a/db/sqlc/schemas/generated_schema.sql +++ b/db/sqlc/schemas/generated_schema.sql @@ -1937,6 +1937,16 @@ CREATE TABLE "vtxo_ancestry_paths" ( CHECK (path_order >= 0 AND path_order < 64) ); +CREATE TABLE vtxo_manual_exit_options ( + outpoint_hash BLOB NOT NULL, + outpoint_index INTEGER NOT NULL, + sweep_script BLOB NOT NULL, + fee_rate_sat_per_vbyte BIGINT NOT NULL CHECK (fee_rate_sat_per_vbyte >= 0), + PRIMARY KEY (outpoint_hash, outpoint_index), + FOREIGN KEY (outpoint_hash, outpoint_index) + REFERENCES vtxos (outpoint_hash, outpoint_index) ON DELETE CASCADE +); + CREATE TABLE vtxos ( -- outpoint_hash and outpoint_index form the VTXO outpoint (primary key). outpoint_hash BLOB NOT NULL, diff --git a/db/sqlc/vtxo.sql.go b/db/sqlc/vtxo.sql.go index f397a0df8..933018271 100644 --- a/db/sqlc/vtxo.sql.go +++ b/db/sqlc/vtxo.sql.go @@ -22,6 +22,21 @@ func (q *Queries) CountVTXOsByStatus(ctx context.Context, status int32) (int64, return count, err } +const DeleteManualExitOptions = `-- name: DeleteManualExitOptions :exec +DELETE FROM vtxo_manual_exit_options +WHERE outpoint_hash = $1 AND outpoint_index = $2 +` + +type DeleteManualExitOptionsParams struct { + OutpointHash []byte + OutpointIndex int32 +} + +func (q *Queries) DeleteManualExitOptions(ctx context.Context, arg DeleteManualExitOptionsParams) error { + _, err := q.db.ExecContext(ctx, DeleteManualExitOptions, arg.OutpointHash, arg.OutpointIndex) + return err +} + const DeleteVTXO = `-- name: DeleteVTXO :exec DELETE FROM vtxos WHERE outpoint_hash = $1 AND outpoint_index = $2 @@ -39,6 +54,28 @@ func (q *Queries) DeleteVTXO(ctx context.Context, arg DeleteVTXOParams) error { return err } +const GetManualExitOptions = `-- name: GetManualExitOptions :one +SELECT sweep_script, fee_rate_sat_per_vbyte FROM vtxo_manual_exit_options +WHERE outpoint_hash = $1 AND outpoint_index = $2 +` + +type GetManualExitOptionsParams struct { + OutpointHash []byte + OutpointIndex int32 +} + +type GetManualExitOptionsRow struct { + SweepScript []byte + FeeRateSatPerVbyte int64 +} + +func (q *Queries) GetManualExitOptions(ctx context.Context, arg GetManualExitOptionsParams) (GetManualExitOptionsRow, error) { + row := q.db.QueryRowContext(ctx, GetManualExitOptions, arg.OutpointHash, arg.OutpointIndex) + var i GetManualExitOptionsRow + err := row.Scan(&i.SweepScript, &i.FeeRateSatPerVbyte) + return i, err +} + const GetVTXOForfeitTx = `-- name: GetVTXOForfeitTx :one SELECT forfeit_tx, forfeit_round_id FROM vtxos WHERE outpoint_hash = $1 AND outpoint_index = $2 @@ -526,6 +563,32 @@ func (q *Queries) MarkVTXOForfeiting(ctx context.Context, arg MarkVTXOForfeiting return err } +const PutManualExitOptions = `-- name: PutManualExitOptions :exec +INSERT INTO vtxo_manual_exit_options ( + outpoint_hash, outpoint_index, sweep_script, fee_rate_sat_per_vbyte +) VALUES ($1, $2, $3, $4) +ON CONFLICT (outpoint_hash, outpoint_index) DO UPDATE SET + sweep_script = EXCLUDED.sweep_script, + fee_rate_sat_per_vbyte = EXCLUDED.fee_rate_sat_per_vbyte +` + +type PutManualExitOptionsParams struct { + OutpointHash []byte + OutpointIndex int32 + SweepScript []byte + FeeRateSatPerVbyte int64 +} + +func (q *Queries) PutManualExitOptions(ctx context.Context, arg PutManualExitOptionsParams) error { + _, err := q.db.ExecContext(ctx, PutManualExitOptions, + arg.OutpointHash, + arg.OutpointIndex, + arg.SweepScript, + arg.FeeRateSatPerVbyte, + ) + return err +} + const RepairVTXOCreatedHeight = `-- name: RepairVTXOCreatedHeight :execrows UPDATE vtxos SET created_height = $3, diff --git a/db/vtxo_manual_exit_test.go b/db/vtxo_manual_exit_test.go new file mode 100644 index 000000000..4af21eee5 --- /dev/null +++ b/db/vtxo_manual_exit_test.go @@ -0,0 +1,145 @@ +package db + +import ( + "os" + "testing" + + "github.com/btcsuite/btcd/chaincfg/v2" + "github.com/btcsuite/btclog/v2" + "github.com/lightninglabs/wavelength/lib/actormsg" + "github.com/lightninglabs/wavelength/lib/tree" + "github.com/lightninglabs/wavelength/round" + "github.com/lightninglabs/wavelength/vtxo" + "github.com/lightningnetwork/lnd/clock" + "github.com/stretchr/testify/require" +) + +// TestManualExitOptionsSurviveStatusReload checks the durable handoff before +// the exit registry sees the status transition, and a subsequent safe retry. +func TestManualExitOptionsSurviveStatusReload(t *testing.T) { + t.Parallel() + + store, rounds, _ := newVTXOStoreForTest(t) + ctx := t.Context() + roundID := testRoundIDDB("manual-exit-options") + testRound := createTestRound(t, roundID) + trees := make(map[round.SignerKey]*tree.Tree) + require.NoError( + t, + rounds.CommitState( + ctx, testRound, &round.InputSigSentState{ + RoundID: testRound.RoundID, + ClientTrees: trees, + }, + ), + ) + desc := createTestVTXODescriptor(t, roundID, 7) + require.NoError(t, store.SaveVTXO(ctx, desc)) + + options := &actormsg.ManualExitOptions{ + SweepScript: []byte{ + 0x51, + 0x20, + 0xde, + 0xad, + }, + FeeRateSatPerVByte: 7, + } + require.NoError( + t, store.UpdateVTXOStatusWithExitOptions( + ctx, desc.Outpoint, options, false, + ), + ) + saved, err := store.GetVTXO(ctx, desc.Outpoint) + require.NoError(t, err) + require.Equal(t, vtxo.VTXOStatusUnilateralExit, saved.Status) + require.Equal(t, options, saved.ManualExitOptions) + + require.NoError( + t, store.UpdateVTXOStatus( + ctx, desc.Outpoint, vtxo.VTXOStatusLive, + ), + ) + require.NoError( + t, store.UpdateVTXOStatus( + ctx, desc.Outpoint, vtxo.VTXOStatusUnilateralExit, + ), + ) + saved, err = store.GetVTXO(ctx, desc.Outpoint) + require.NoError(t, err) + require.Nil(t, saved.ManualExitOptions) +} + +// TestManualExitMigrationAfterFeeSplit preserves a pending signed split when +// upgrading from the public schema 33. +func TestManualExitMigrationAfterFeeSplit(t *testing.T) { + t.Parallel() + + ctx := t.Context() + database := NewTestDBWithVersion(t, 33) + candidate := []byte("pending signed split") + _, err := database.SaveWalletFeeSplit(ctx, candidate) + require.NoError(t, err) + + require.NoError(t, database.ExecuteMigrations(TargetLatest)) + saved, err := database.LoadWalletFeeSplit(ctx) + require.NoError(t, err) + require.Equal(t, candidate, saved) +} + +// TestManualExitMigrationFromMobile33 recreates the wallet schema used by +// early mobile builds and checks that upgrading supplies the missing journal. +func TestManualExitMigrationFromMobile33(t *testing.T) { + t.Parallel() + + ctx := t.Context() + database := NewTestSqliteDBWithVersion(t, 33) + // The original mobile migration has the same table and constraints. + migration, err := os.ReadFile( + "sqlc/migrations/000034_manual_exit_options.up.sql", + ) + require.NoError(t, err) + _, err = database.ExecContext(ctx, string(migration)) + require.NoError(t, err) + _, err = database.ExecContext(ctx, "DROP TABLE wallet_fee_split") + require.NoError(t, err) + + stores := NewStore( + database.DB, database.Queries, database.Backend(), + btclog.Disabled, + ) + clk := clock.NewDefaultClock() + rounds := stores.NewRoundStore(&chaincfg.RegressionNetParams, clk) + store := stores.NewVTXOStore(clk) + roundID := testRoundIDDB("manual-exit-migration") + testRound := createTestRound(t, roundID) + trees := make(map[round.SignerKey]*tree.Tree) + require.NoError( + t, + rounds.CommitState( + ctx, testRound, &round.InputSigSentState{ + RoundID: roundID, + ClientTrees: trees, + }, + ), + ) + desc := createTestVTXODescriptor(t, roundID, 17) + require.NoError(t, store.SaveVTXO(ctx, desc)) + options := &actormsg.ManualExitOptions{ + SweepScript: []byte{ + 0x51, + }, FeeRateSatPerVByte: 7, + } + require.NoError( + t, store.UpdateVTXOStatusWithExitOptions( + ctx, desc.Outpoint, options, false, + ), + ) + + require.NoError(t, database.ExecuteMigrations(TargetLatest)) + saved, err := store.GetVTXO(ctx, desc.Outpoint) + require.NoError(t, err) + require.Equal(t, options, saved.ManualExitOptions) + _, err = database.SaveWalletFeeSplit(ctx, []byte("new split")) + require.NoError(t, err) +} diff --git a/db/vtxo_store.go b/db/vtxo_store.go index 4b000e32e..eddb0de5a 100644 --- a/db/vtxo_store.go +++ b/db/vtxo_store.go @@ -19,6 +19,7 @@ import ( "github.com/lightninglabs/wavelength/arkrpc" "github.com/lightninglabs/wavelength/build" "github.com/lightninglabs/wavelength/db/sqlc" + "github.com/lightninglabs/wavelength/lib/actormsg" "github.com/lightninglabs/wavelength/lib/arkscript" "github.com/lightninglabs/wavelength/rpc/roundpb" "github.com/lightninglabs/wavelength/vtxo" @@ -211,6 +212,30 @@ func (s *VTXOPersistenceStore) GetVTXO(ctx context.Context, return fmt.Errorf("convert VTXO: %w", err) } + if desc.Status == vtxo.VTXOStatusUnilateralExit || + desc.Status == vtxo.VTXOStatusSpent { + + options, err := q.GetManualExitOptions( + ctx, sqlc.GetManualExitOptionsParams{ + OutpointHash: params.OutpointHash, + OutpointIndex: params.OutpointIndex, + }, + ) + switch { + case err == nil: + rate := options.FeeRateSatPerVbyte + opt := &actormsg.ManualExitOptions{ + SweepScript: options.SweepScript, + FeeRateSatPerVByte: rate, + } + desc.ManualExitOptions = opt + + case !errors.Is(err, sql.ErrNoRows): + return fmt.Errorf("load manual exit "+ + "options: %w", err) + } + } + result = desc return nil @@ -846,7 +871,77 @@ func (s *VTXOPersistenceStore) UpdateVTXOStatus( LastUpdateTime: s.clock.Now().Unix(), } - return q.UpdateVTXOStatus(ctx, params) + if err := q.UpdateVTXOStatus(ctx, params); err != nil { + return err + } + + return clearStaleManualExitOptions(ctx, q, status, outpoint) + }) +} + +// clearStaleManualExitOptions drops an earlier selection when the VTXO +// reopens or starts a new exit without custom terms. +func clearStaleManualExitOptions(ctx context.Context, q RoundStore, + status vtxo.VTXOStatus, outpoint wire.OutPoint) error { + + switch status { + case vtxo.VTXOStatusLive, vtxo.VTXOStatusExpired, + vtxo.VTXOStatusUnilateralExit: + return q.DeleteManualExitOptions( + ctx, sqlc.DeleteManualExitOptionsParams{ + OutpointHash: outpoint.Hash[:], + OutpointIndex: int32( + outpoint.Index, + ), + }, + ) + + default: + return nil + } +} + +// UpdateVTXOStatusWithExitOptions atomically binds customized exit terms to +// the VTXO lifecycle transition. Orphan recovery can reconstruct the same +// payout even if the daemon crashes before admitting the job to the registry. +func (s *VTXOPersistenceStore) UpdateVTXOStatusWithExitOptions( + ctx context.Context, outpoint wire.OutPoint, + options *actormsg.ManualExitOptions, releaseReservation bool) error { + + return s.db.ExecTx(ctx, WriteTxOption(), func(q RoundStore) error { + params := sqlc.UpdateVTXOStatusParams{ + OutpointHash: outpoint.Hash[:], OutpointIndex: int32( + outpoint.Index, + ), + Status: int32(vtxo.VTXOStatusUnilateralExit), + LastUpdateTime: s.clock.Now().Unix(), + } + if err := q.UpdateVTXOStatus(ctx, params); err != nil { + return err + } + + if err := q.PutManualExitOptions( + ctx, sqlc.PutManualExitOptionsParams{ + OutpointHash: params.OutpointHash, + OutpointIndex: params.OutpointIndex, + SweepScript: append( + []byte{}, options.SweepScript..., + ), + FeeRateSatPerVbyte: options.FeeRateSatPerVByte, + }, + ); err != nil { + return err + } + if !releaseReservation { + return nil + } + + return q.DeleteSpendingReservation( + ctx, sqlc.DeleteSpendingReservationParams{ + OutpointHash: params.OutpointHash, + OutpointIndex: params.OutpointIndex, + }, + ) }) } @@ -873,6 +968,12 @@ func (s *VTXOPersistenceStore) UpdateVTXOStatusReleasingReservation( return err } + if err := clearStaleManualExitOptions( + ctx, q, status, outpoint, + ); err != nil { + return err + } + return q.DeleteSpendingReservation( ctx, sqlc.DeleteSpendingReservationParams{ OutpointHash: outpoint.Hash[:], diff --git a/lib/actormsg/vtxo_admission.go b/lib/actormsg/vtxo_admission.go index b10df1cc7..e62737b40 100644 --- a/lib/actormsg/vtxo_admission.go +++ b/lib/actormsg/vtxo_admission.go @@ -451,6 +451,13 @@ type ExitPolicy struct { Ref ExitPolicyRef } +// ManualExitOptions configures the initial network fee rate and final payout +// script. An empty script or zero rate selects the respective wallet default. +type ManualExitOptions struct { + SweepScript []byte + FeeRateSatPerVByte int64 +} + // ForceUnrollRequest asks the VTXO manager to transition a specific VTXO // into UnilateralExitState and trigger unroll through the chain resolver // seam. This converges manual, critical-expiry, fraud, and vHTLC-recovery @@ -475,6 +482,9 @@ type ForceUnrollRequest struct { // vHTLC refund policy) to persist for this target. None selects the // standard VTXO timeout policy. ExitPolicy fn.Option[ExitPolicy] + + // ManualOptions are persisted with the normal Bitcoin exit transition. + ManualOptions *ManualExitOptions } // VTXOManagerMsg implements VTXOManagerMsg marker interface. diff --git a/rpc/wavewalletrpc/wallet.pb.go b/rpc/wavewalletrpc/wallet.pb.go index d80dc56aa..7e8691bab 100644 --- a/rpc/wavewalletrpc/wallet.pb.go +++ b/rpc/wavewalletrpc/wallet.pb.go @@ -4578,9 +4578,14 @@ type GetExitPlanRequest struct { Outpoints []string `protobuf:"bytes,1,rep,name=outpoints,proto3" json:"outpoints,omitempty"` // conf_target selects the fee-estimation target in blocks. Zero uses // the daemon's default unroll confirmation target. - ConfTarget uint32 `protobuf:"varint,2,opt,name=conf_target,json=confTarget,proto3" json:"conf_target,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + ConfTarget uint32 `protobuf:"varint,2,opt,name=conf_target,json=confTarget,proto3" json:"conf_target,omitempty"` + // sweep_address is an optional final payout address on the wallet's + // network. + SweepAddress string `protobuf:"bytes,3,opt,name=sweep_address,json=sweepAddress,proto3" json:"sweep_address,omitempty"` + // fee_rate_sat_per_vbyte overrides the automatic rate when positive. + FeeRateSatPerVbyte int64 `protobuf:"varint,4,opt,name=fee_rate_sat_per_vbyte,json=feeRateSatPerVbyte,proto3" json:"fee_rate_sat_per_vbyte,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *GetExitPlanRequest) Reset() { @@ -4627,6 +4632,20 @@ func (x *GetExitPlanRequest) GetConfTarget() uint32 { return 0 } +func (x *GetExitPlanRequest) GetSweepAddress() string { + if x != nil { + return x.SweepAddress + } + return "" +} + +func (x *GetExitPlanRequest) GetFeeRateSatPerVbyte() int64 { + if x != nil { + return x.FeeRateSatPerVbyte + } + return 0 +} + // ExitPlanEntry is the per-outpoint unilateral-exit readiness preview: the // backing-wallet fee requirements and, when an unroll job already exists, // its current state. @@ -4863,8 +4882,13 @@ type GetExitPlanResponse struct { // total_recommended_funding_sat is the summed recommended funding across // entries. TotalRecommendedFundingSat int64 `protobuf:"varint,5,opt,name=total_recommended_funding_sat,json=totalRecommendedFundingSat,proto3" json:"total_recommended_funding_sat,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // sweep_address echoes the validated final payout address, if supplied. + SweepAddress string `protobuf:"bytes,6,opt,name=sweep_address,json=sweepAddress,proto3" json:"sweep_address,omitempty"` + // total_estimated_fee_sat sums the estimated costs of individual exits. + // It can overestimate when several VTXOs share recovery transactions. + TotalEstimatedFeeSat *int64 `protobuf:"varint,7,opt,name=total_estimated_fee_sat,json=totalEstimatedFeeSat,proto3,oneof" json:"total_estimated_fee_sat,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *GetExitPlanResponse) Reset() { @@ -4932,6 +4956,20 @@ func (x *GetExitPlanResponse) GetTotalRecommendedFundingSat() int64 { return 0 } +func (x *GetExitPlanResponse) GetSweepAddress() string { + if x != nil { + return x.SweepAddress + } + return "" +} + +func (x *GetExitPlanResponse) GetTotalEstimatedFeeSat() int64 { + if x != nil && x.TotalEstimatedFeeSat != nil { + return *x.TotalEstimatedFeeSat + } + return 0 +} + // PreviewUnilateralExitResponse quotes a full recovery from its proof graphs // at the current fee estimate. The estimate assumes each package confirms at // the quoted rate. It does not authorize a fee or commit any wallet funds. @@ -4960,6 +4998,8 @@ type PreviewUnilateralExitResponse struct { AdditionalFundingSat int64 `protobuf:"varint,7,opt,name=additional_funding_sat,json=additionalFundingSat,proto3" json:"additional_funding_sat,omitempty"` // funding_action describes the estimated use of confirmed wallet coins. FundingAction UnilateralExitFundingAction `protobuf:"varint,8,opt,name=funding_action,json=fundingAction,proto3,enum=wavewalletrpc.UnilateralExitFundingAction" json:"funding_action,omitempty"` + // sweep_address echoes the validated custom destination, if supplied. + SweepAddress string `protobuf:"bytes,9,opt,name=sweep_address,json=sweepAddress,proto3" json:"sweep_address,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -5050,6 +5090,13 @@ func (x *PreviewUnilateralExitResponse) GetFundingAction() UnilateralExitFunding return UnilateralExitFundingAction_UNILATERAL_EXIT_FUNDING_ACTION_UNSPECIFIED } +func (x *PreviewUnilateralExitResponse) GetSweepAddress() string { + if x != nil { + return x.SweepAddress + } + return "" +} + // UnilateralExitTarget describes one selected coin and any existing job. type UnilateralExitTarget struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -5071,8 +5118,10 @@ type UnilateralExitTarget struct { // A cooperative round currently holds the coin. Manual recovery remains // available if the operator cannot complete the round. RoundCommitment string `protobuf:"bytes,8,opt,name=round_commitment,json=roundCommitment,proto3" json:"round_commitment,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // infeasibility_reason identifies an economic refusal. + InfeasibilityReason ExitInfeasibilityReason `protobuf:"varint,9,opt,name=infeasibility_reason,json=infeasibilityReason,proto3,enum=wavewalletrpc.ExitInfeasibilityReason" json:"infeasibility_reason,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *UnilateralExitTarget) Reset() { @@ -5161,6 +5210,13 @@ func (x *UnilateralExitTarget) GetRoundCommitment() string { return "" } +func (x *UnilateralExitTarget) GetInfeasibilityReason() ExitInfeasibilityReason { + if x != nil { + return x.InfeasibilityReason + } + return ExitInfeasibilityReason_EXIT_INFEASIBILITY_REASON_UNSPECIFIED +} + // SweepWalletRequest describes a backing-wallet sweep to preview or broadcast // via WalletService.SweepWallet. type SweepWalletRequest struct { @@ -5426,10 +5482,18 @@ type ExitRequest struct { // force_unroll_ack must be exactly "I_KNOW_WHAT_I_AM_DOING" to bypass // cooperative leave and start unilateral unroll. It cannot be combined // with onchain_address, and the server requires at least one confirmed - // local backing-wallet UTXO before admitting forced unroll. + // local backing-wallet UTXO before admitting forced unroll. To set an + // explicit fee rate or sweep address, use + // "I_KNOW_WHAT_I_AM_DOING_WITH_CUSTOM_EXIT_OPTIONS" so older daemons fail + // closed instead of ignoring the new fields. ForceUnrollAck string `protobuf:"bytes,3,opt,name=force_unroll_ack,json=forceUnrollAck,proto3" json:"force_unroll_ack,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // sweep_address overrides the final payout for a manual unilateral exit. + SweepAddress string `protobuf:"bytes,4,opt,name=sweep_address,json=sweepAddress,proto3" json:"sweep_address,omitempty"` + // fee_rate_sat_per_vbyte sets the initial unilateral broadcast rate. + // Zero uses automatic pricing. + FeeRateSatPerVbyte int64 `protobuf:"varint,5,opt,name=fee_rate_sat_per_vbyte,json=feeRateSatPerVbyte,proto3" json:"fee_rate_sat_per_vbyte,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExitRequest) Reset() { @@ -5483,6 +5547,20 @@ func (x *ExitRequest) GetForceUnrollAck() string { return "" } +func (x *ExitRequest) GetSweepAddress() string { + if x != nil { + return x.SweepAddress + } + return "" +} + +func (x *ExitRequest) GetFeeRateSatPerVbyte() int64 { + if x != nil { + return x.FeeRateSatPerVbyte + } + return 0 +} + // ExitResponse reports the exit path the daemon took and its per-path detail // for WalletService.Exit. type ExitResponse struct { @@ -6167,6 +6245,8 @@ type ExitStatusResponse struct { // current_height is the best block height the exit job has observed. Set // only on a detailed query against a live job. CurrentHeight int32 `protobuf:"varint,10,opt,name=current_height,json=currentHeight,proto3" json:"current_height,omitempty"` + // sweep_address is the persisted custom payout, empty for wallet funding. + SweepAddress string `protobuf:"bytes,11,opt,name=sweep_address,json=sweepAddress,proto3" json:"sweep_address,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -6271,6 +6351,13 @@ func (x *ExitStatusResponse) GetCurrentHeight() int32 { return 0 } +func (x *ExitStatusResponse) GetSweepAddress() string { + if x != nil { + return x.SweepAddress + } + return "" +} + // ExitSummaryRequest asks for the wallet-wide portfolio of in-progress exits. type ExitSummaryRequest struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -7625,11 +7712,13 @@ const file_wallet_proto_rawDesc = "" + "\x17estimated_total_fee_sat\x18\x01 \x01(\x03H\x00R\x14estimatedTotalFeeSat\x88\x01\x01\x122\n" + "\x15free_refresh_eligible\x18\x02 \x01(\bR\x13freeRefreshEligible\x12%\n" + "\x0eestimate_error\x18\x03 \x01(\tR\restimateErrorB\x1a\n" + - "\x18_estimated_total_fee_sat\"S\n" + + "\x18_estimated_total_fee_sat\"\xac\x01\n" + "\x12GetExitPlanRequest\x12\x1c\n" + "\toutpoints\x18\x01 \x03(\tR\toutpoints\x12\x1f\n" + "\vconf_target\x18\x02 \x01(\rR\n" + - "confTarget\"\x87\x06\n" + + "confTarget\x12#\n" + + "\rsweep_address\x18\x03 \x01(\tR\fsweepAddress\x122\n" + + "\x16fee_rate_sat_per_vbyte\x18\x04 \x01(\x03R\x12feeRateSatPerVbyte\"\x87\x06\n" + "\rExitPlanEntry\x12\x1a\n" + "\boutpoint\x18\x01 \x01(\tR\boutpoint\x12'\n" + "\x0ffunding_address\x18\x02 \x01(\tR\x0efundingAddress\x125\n" + @@ -7650,13 +7739,16 @@ const file_wallet_proto_rawDesc = "" + "last_error\x18\r \x01(\tR\tlastError\x12\x14\n" + "\x05error\x18\x0e \x01(\tR\x05error\x12Y\n" + "\x14infeasibility_reason\x18\x0f \x01(\x0e2&.wavewalletrpc.ExitInfeasibilityReasonR\x13infeasibilityReason\x12)\n" + - "\x10round_commitment\x18\x10 \x01(\tR\x0froundCommitment\"\x9c\x02\n" + + "\x10round_commitment\x18\x10 \x01(\tR\x0froundCommitment\"\x99\x03\n" + "\x13GetExitPlanResponse\x122\n" + "\x05plans\x18\x01 \x03(\v2\x1c.wavewalletrpc.ExitPlanEntryR\x05plans\x122\n" + "\x16fee_rate_sat_per_vbyte\x18\x02 \x01(\x03R\x12feeRateSatPerVbyte\x12\x1b\n" + "\tcan_start\x18\x03 \x01(\bR\bcanStart\x12=\n" + "\x1btotal_funding_shortfall_sat\x18\x04 \x01(\x03R\x18totalFundingShortfallSat\x12A\n" + - "\x1dtotal_recommended_funding_sat\x18\x05 \x01(\x03R\x1atotalRecommendedFundingSat\"\xe3\x03\n" + + "\x1dtotal_recommended_funding_sat\x18\x05 \x01(\x03R\x1atotalRecommendedFundingSat\x12#\n" + + "\rsweep_address\x18\x06 \x01(\tR\fsweepAddress\x12:\n" + + "\x17total_estimated_fee_sat\x18\a \x01(\x03H\x00R\x14totalEstimatedFeeSat\x88\x01\x01B\x1a\n" + + "\x18_total_estimated_fee_sat\"\x88\x04\n" + "\x1dPreviewUnilateralExitResponse\x12=\n" + "\aentries\x18\x01 \x03(\v2#.wavewalletrpc.UnilateralExitTargetR\aentries\x12.\n" + "\x13selected_amount_sat\x18\x02 \x01(\x03R\x11selectedAmountSat\x125\n" + @@ -7665,7 +7757,8 @@ const file_wallet_proto_rawDesc = "" + "\x19estimated_network_fee_sat\x18\x05 \x01(\x03R\x16estimatedNetworkFeeSat\x12$\n" + "\x0ewallet_fee_sat\x18\x06 \x01(\x03R\fwalletFeeSat\x124\n" + "\x16additional_funding_sat\x18\a \x01(\x03R\x14additionalFundingSat\x12Q\n" + - "\x0efunding_action\x18\b \x01(\x0e2*.wavewalletrpc.UnilateralExitFundingActionR\rfundingAction\"\xd2\x02\n" + + "\x0efunding_action\x18\b \x01(\x0e2*.wavewalletrpc.UnilateralExitFundingActionR\rfundingAction\x12#\n" + + "\rsweep_address\x18\t \x01(\tR\fsweepAddress\"\xad\x03\n" + "\x14UnilateralExitTarget\x12\x1a\n" + "\boutpoint\x18\x01 \x01(\tR\boutpoint\x12\x1d\n" + "\n" + @@ -7678,7 +7771,8 @@ const file_wallet_proto_rawDesc = "" + "\n" + "last_error\x18\x06 \x01(\tR\tlastError\x12'\n" + "\x0fadmission_error\x18\a \x01(\tR\x0eadmissionError\x12)\n" + - "\x10round_commitment\x18\b \x01(\tR\x0froundCommitment\"\xb8\x01\n" + + "\x10round_commitment\x18\b \x01(\tR\x0froundCommitment\x12Y\n" + + "\x14infeasibility_reason\x18\t \x01(\x0e2&.wavewalletrpc.ExitInfeasibilityReasonR\x13infeasibilityReason\"\xb8\x01\n" + "\x12SweepWalletRequest\x12/\n" + "\x13destination_address\x18\x01 \x01(\tR\x12destinationAddress\x12\x1c\n" + "\tbroadcast\x18\x02 \x01(\bR\tbroadcast\x122\n" + @@ -7697,11 +7791,13 @@ const file_wallet_proto_rawDesc = "" + "\x16fee_rate_sat_per_vbyte\x18\x05 \x01(\x03R\x12feeRateSatPerVbyte\x12#\n" + "\rcan_broadcast\x18\x06 \x01(\bR\fcanBroadcast\x12\x12\n" + "\x04txid\x18\a \x01(\tR\x04txid\x12%\n" + - "\x0efailure_reason\x18\b \x01(\tR\rfailureReason\"|\n" + + "\x0efailure_reason\x18\b \x01(\tR\rfailureReason\"\xd5\x01\n" + "\vExitRequest\x12\x1a\n" + "\boutpoint\x18\x01 \x01(\tR\boutpoint\x12'\n" + "\x0fonchain_address\x18\x02 \x01(\tR\x0eonchainAddress\x12(\n" + - "\x10force_unroll_ack\x18\x03 \x01(\tR\x0eforceUnrollAck\"\xc4\x01\n" + + "\x10force_unroll_ack\x18\x03 \x01(\tR\x0eforceUnrollAck\x12#\n" + + "\rsweep_address\x18\x04 \x01(\tR\fsweepAddress\x122\n" + + "\x16fee_rate_sat_per_vbyte\x18\x05 \x01(\x03R\x12feeRateSatPerVbyte\"\xc4\x01\n" + "\fExitResponse\x12\x18\n" + "\acreated\x18\x01 \x01(\bR\acreated\x12\x19\n" + "\bactor_id\x18\x02 \x01(\tR\aactorId\x12+\n" + @@ -7748,7 +7844,7 @@ const file_wallet_proto_rawDesc = "" + "\x11net_recovered_sat\x18\x05 \x01(\x03R\x0fnetRecoveredSat\x12+\n" + "\x12fee_rate_sat_vbyte\x18\x06 \x01(\x03R\x0ffeeRateSatVbyte\x12(\n" + "\x10sweep_fee_actual\x18\a \x01(\bR\x0esweepFeeActual\x12'\n" + - "\x10spent_so_far_sat\x18\b \x01(\x03R\rspentSoFarSat\"\xb5\x03\n" + + "\x10spent_so_far_sat\x18\b \x01(\x03R\rspentSoFarSat\"\xda\x03\n" + "\x12ExitStatusResponse\x12\x14\n" + "\x05found\x18\x01 \x01(\bR\x05found\x124\n" + "\x06status\x18\x02 \x01(\x0e2\x1c.wavewalletrpc.ExitJobStatusR\x06status\x12\x1d\n" + @@ -7762,7 +7858,8 @@ const file_wallet_proto_rawDesc = "" + "\x04fees\x18\b \x01(\v2\x17.wavewalletrpc.ExitFeesR\x04fees\x12;\n" + "\x1abest_case_blocks_remaining\x18\t \x01(\x05R\x17bestCaseBlocksRemaining\x12%\n" + "\x0ecurrent_height\x18\n" + - " \x01(\x05R\rcurrentHeight\"\x14\n" + + " \x01(\x05R\rcurrentHeight\x12#\n" + + "\rsweep_address\x18\v \x01(\tR\fsweepAddress\"\x14\n" + "\x12ExitSummaryRequest\"\xe9\x01\n" + "\x0fExitSummaryItem\x12\x1a\n" + "\boutpoint\x18\x01 \x01(\tR\boutpoint\x124\n" + @@ -8078,78 +8175,79 @@ var file_wallet_proto_depIdxs = []int32{ 59, // 33: wavewalletrpc.PreviewUnilateralExitResponse.entries:type_name -> wavewalletrpc.UnilateralExitTarget 7, // 34: wavewalletrpc.PreviewUnilateralExitResponse.funding_action:type_name -> wavewalletrpc.UnilateralExitFundingAction 9, // 35: wavewalletrpc.UnilateralExitTarget.exit_status:type_name -> wavewalletrpc.ExitJobStatus - 61, // 36: wavewalletrpc.SweepWalletResponse.inputs:type_name -> wavewalletrpc.WalletSweepInput - 5, // 37: wavewalletrpc.ExitResponse.mode:type_name -> wavewalletrpc.ExitMode - 8, // 38: wavewalletrpc.ExitBatchInputResult.outcome:type_name -> wavewalletrpc.ExitBatchOutcome - 66, // 39: wavewalletrpc.ExitBatchResponse.results:type_name -> wavewalletrpc.ExitBatchInputResult - 9, // 40: wavewalletrpc.ExitStatusResponse.status:type_name -> wavewalletrpc.ExitJobStatus - 69, // 41: wavewalletrpc.ExitStatusResponse.progress:type_name -> wavewalletrpc.ExitProgress - 70, // 42: wavewalletrpc.ExitStatusResponse.csv:type_name -> wavewalletrpc.ExitCSV - 71, // 43: wavewalletrpc.ExitStatusResponse.fees:type_name -> wavewalletrpc.ExitFees - 9, // 44: wavewalletrpc.ExitSummaryItem.status:type_name -> wavewalletrpc.ExitJobStatus - 74, // 45: wavewalletrpc.ExitSummaryResponse.exits:type_name -> wavewalletrpc.ExitSummaryItem - 0, // 46: wavewalletrpc.SubscribeWalletRequest.kinds:type_name -> wavewalletrpc.EntryKind - 79, // 47: wavewalletrpc.SubscribeWalletResponse.entry:type_name -> wavewalletrpc.WalletEntry - 78, // 48: wavewalletrpc.SubscribeWalletResponse.gap:type_name -> wavewalletrpc.SubscribeGap - 0, // 49: wavewalletrpc.WalletEntry.kind:type_name -> wavewalletrpc.EntryKind - 1, // 50: wavewalletrpc.WalletEntry.status:type_name -> wavewalletrpc.EntryStatus - 80, // 51: wavewalletrpc.WalletEntry.request:type_name -> wavewalletrpc.WalletEntryRequest - 85, // 52: wavewalletrpc.WalletEntry.progress:type_name -> wavewalletrpc.WalletEntryProgress - 11, // 53: wavewalletrpc.WalletEntry.failure_code:type_name -> wavewalletrpc.EntryFailureCode - 81, // 54: wavewalletrpc.WalletEntryRequest.lightning_invoice:type_name -> wavewalletrpc.LightningInvoiceRequest - 82, // 55: wavewalletrpc.WalletEntryRequest.onchain_address:type_name -> wavewalletrpc.OnchainAddressRequest - 83, // 56: wavewalletrpc.WalletEntryRequest.ark_address:type_name -> wavewalletrpc.ArkAddressRequest - 10, // 57: wavewalletrpc.WalletEntryProgress.phase:type_name -> wavewalletrpc.WalletEntryPhase - 84, // 58: wavewalletrpc.WalletEntryProgress.batch_window:type_name -> wavewalletrpc.ScheduledBatchWindow - 12, // 59: wavewalletrpc.WalletService.Create:input_type -> wavewalletrpc.CreateRequest - 14, // 60: wavewalletrpc.WalletService.Unlock:input_type -> wavewalletrpc.UnlockRequest - 16, // 61: wavewalletrpc.WalletService.PrepareSend:input_type -> wavewalletrpc.PrepareSendRequest - 18, // 62: wavewalletrpc.WalletService.Send:input_type -> wavewalletrpc.SendRequest - 20, // 63: wavewalletrpc.WalletService.Recv:input_type -> wavewalletrpc.RecvRequest - 21, // 64: wavewalletrpc.WalletService.LookupRecv:input_type -> wavewalletrpc.LookupRecvRequest - 25, // 65: wavewalletrpc.WalletService.List:input_type -> wavewalletrpc.ListRequest - 37, // 66: wavewalletrpc.WalletService.Deposit:input_type -> wavewalletrpc.DepositRequest - 39, // 67: wavewalletrpc.WalletService.Balance:input_type -> wavewalletrpc.BalanceRequest - 41, // 68: wavewalletrpc.WalletService.Status:input_type -> wavewalletrpc.StatusRequest - 52, // 69: wavewalletrpc.WalletService.Refresh:input_type -> wavewalletrpc.RefreshRequest - 55, // 70: wavewalletrpc.WalletService.GetExitPlan:input_type -> wavewalletrpc.GetExitPlanRequest - 55, // 71: wavewalletrpc.WalletService.PreviewUnilateralExit:input_type -> wavewalletrpc.GetExitPlanRequest - 43, // 72: wavewalletrpc.WalletService.ExportExit:input_type -> wavewalletrpc.ExportExitRequest - 45, // 73: wavewalletrpc.WalletService.ExportExits:input_type -> wavewalletrpc.ExportExitsRequest - 60, // 74: wavewalletrpc.WalletService.SweepWallet:input_type -> wavewalletrpc.SweepWalletRequest - 63, // 75: wavewalletrpc.WalletService.Exit:input_type -> wavewalletrpc.ExitRequest - 65, // 76: wavewalletrpc.WalletService.ExitBatch:input_type -> wavewalletrpc.ExitBatchRequest - 68, // 77: wavewalletrpc.WalletService.ExitStatus:input_type -> wavewalletrpc.ExitStatusRequest - 73, // 78: wavewalletrpc.WalletService.ExitSummary:input_type -> wavewalletrpc.ExitSummaryRequest - 76, // 79: wavewalletrpc.WalletService.SubscribeWallet:input_type -> wavewalletrpc.SubscribeWalletRequest - 32, // 80: wavewalletrpc.WalletInspectionService.InspectActivity:input_type -> wavewalletrpc.InspectActivityRequest - 13, // 81: wavewalletrpc.WalletService.Create:output_type -> wavewalletrpc.CreateResponse - 15, // 82: wavewalletrpc.WalletService.Unlock:output_type -> wavewalletrpc.UnlockResponse - 17, // 83: wavewalletrpc.WalletService.PrepareSend:output_type -> wavewalletrpc.PrepareSendResponse - 19, // 84: wavewalletrpc.WalletService.Send:output_type -> wavewalletrpc.SendResponse - 22, // 85: wavewalletrpc.WalletService.Recv:output_type -> wavewalletrpc.RecvResponse - 22, // 86: wavewalletrpc.WalletService.LookupRecv:output_type -> wavewalletrpc.RecvResponse - 26, // 87: wavewalletrpc.WalletService.List:output_type -> wavewalletrpc.ListResponse - 38, // 88: wavewalletrpc.WalletService.Deposit:output_type -> wavewalletrpc.DepositResponse - 40, // 89: wavewalletrpc.WalletService.Balance:output_type -> wavewalletrpc.BalanceResponse - 42, // 90: wavewalletrpc.WalletService.Status:output_type -> wavewalletrpc.StatusResponse - 53, // 91: wavewalletrpc.WalletService.Refresh:output_type -> wavewalletrpc.RefreshResponse - 57, // 92: wavewalletrpc.WalletService.GetExitPlan:output_type -> wavewalletrpc.GetExitPlanResponse - 58, // 93: wavewalletrpc.WalletService.PreviewUnilateralExit:output_type -> wavewalletrpc.PreviewUnilateralExitResponse - 44, // 94: wavewalletrpc.WalletService.ExportExit:output_type -> wavewalletrpc.ExportExitResponse - 46, // 95: wavewalletrpc.WalletService.ExportExits:output_type -> wavewalletrpc.ExportExitsResponse - 62, // 96: wavewalletrpc.WalletService.SweepWallet:output_type -> wavewalletrpc.SweepWalletResponse - 64, // 97: wavewalletrpc.WalletService.Exit:output_type -> wavewalletrpc.ExitResponse - 67, // 98: wavewalletrpc.WalletService.ExitBatch:output_type -> wavewalletrpc.ExitBatchResponse - 72, // 99: wavewalletrpc.WalletService.ExitStatus:output_type -> wavewalletrpc.ExitStatusResponse - 75, // 100: wavewalletrpc.WalletService.ExitSummary:output_type -> wavewalletrpc.ExitSummaryResponse - 77, // 101: wavewalletrpc.WalletService.SubscribeWallet:output_type -> wavewalletrpc.SubscribeWalletResponse - 33, // 102: wavewalletrpc.WalletInspectionService.InspectActivity:output_type -> wavewalletrpc.InspectActivityResponse - 81, // [81:103] is the sub-list for method output_type - 59, // [59:81] is the sub-list for method input_type - 59, // [59:59] is the sub-list for extension type_name - 59, // [59:59] is the sub-list for extension extendee - 0, // [0:59] is the sub-list for field type_name + 6, // 36: wavewalletrpc.UnilateralExitTarget.infeasibility_reason:type_name -> wavewalletrpc.ExitInfeasibilityReason + 61, // 37: wavewalletrpc.SweepWalletResponse.inputs:type_name -> wavewalletrpc.WalletSweepInput + 5, // 38: wavewalletrpc.ExitResponse.mode:type_name -> wavewalletrpc.ExitMode + 8, // 39: wavewalletrpc.ExitBatchInputResult.outcome:type_name -> wavewalletrpc.ExitBatchOutcome + 66, // 40: wavewalletrpc.ExitBatchResponse.results:type_name -> wavewalletrpc.ExitBatchInputResult + 9, // 41: wavewalletrpc.ExitStatusResponse.status:type_name -> wavewalletrpc.ExitJobStatus + 69, // 42: wavewalletrpc.ExitStatusResponse.progress:type_name -> wavewalletrpc.ExitProgress + 70, // 43: wavewalletrpc.ExitStatusResponse.csv:type_name -> wavewalletrpc.ExitCSV + 71, // 44: wavewalletrpc.ExitStatusResponse.fees:type_name -> wavewalletrpc.ExitFees + 9, // 45: wavewalletrpc.ExitSummaryItem.status:type_name -> wavewalletrpc.ExitJobStatus + 74, // 46: wavewalletrpc.ExitSummaryResponse.exits:type_name -> wavewalletrpc.ExitSummaryItem + 0, // 47: wavewalletrpc.SubscribeWalletRequest.kinds:type_name -> wavewalletrpc.EntryKind + 79, // 48: wavewalletrpc.SubscribeWalletResponse.entry:type_name -> wavewalletrpc.WalletEntry + 78, // 49: wavewalletrpc.SubscribeWalletResponse.gap:type_name -> wavewalletrpc.SubscribeGap + 0, // 50: wavewalletrpc.WalletEntry.kind:type_name -> wavewalletrpc.EntryKind + 1, // 51: wavewalletrpc.WalletEntry.status:type_name -> wavewalletrpc.EntryStatus + 80, // 52: wavewalletrpc.WalletEntry.request:type_name -> wavewalletrpc.WalletEntryRequest + 85, // 53: wavewalletrpc.WalletEntry.progress:type_name -> wavewalletrpc.WalletEntryProgress + 11, // 54: wavewalletrpc.WalletEntry.failure_code:type_name -> wavewalletrpc.EntryFailureCode + 81, // 55: wavewalletrpc.WalletEntryRequest.lightning_invoice:type_name -> wavewalletrpc.LightningInvoiceRequest + 82, // 56: wavewalletrpc.WalletEntryRequest.onchain_address:type_name -> wavewalletrpc.OnchainAddressRequest + 83, // 57: wavewalletrpc.WalletEntryRequest.ark_address:type_name -> wavewalletrpc.ArkAddressRequest + 10, // 58: wavewalletrpc.WalletEntryProgress.phase:type_name -> wavewalletrpc.WalletEntryPhase + 84, // 59: wavewalletrpc.WalletEntryProgress.batch_window:type_name -> wavewalletrpc.ScheduledBatchWindow + 12, // 60: wavewalletrpc.WalletService.Create:input_type -> wavewalletrpc.CreateRequest + 14, // 61: wavewalletrpc.WalletService.Unlock:input_type -> wavewalletrpc.UnlockRequest + 16, // 62: wavewalletrpc.WalletService.PrepareSend:input_type -> wavewalletrpc.PrepareSendRequest + 18, // 63: wavewalletrpc.WalletService.Send:input_type -> wavewalletrpc.SendRequest + 20, // 64: wavewalletrpc.WalletService.Recv:input_type -> wavewalletrpc.RecvRequest + 21, // 65: wavewalletrpc.WalletService.LookupRecv:input_type -> wavewalletrpc.LookupRecvRequest + 25, // 66: wavewalletrpc.WalletService.List:input_type -> wavewalletrpc.ListRequest + 37, // 67: wavewalletrpc.WalletService.Deposit:input_type -> wavewalletrpc.DepositRequest + 39, // 68: wavewalletrpc.WalletService.Balance:input_type -> wavewalletrpc.BalanceRequest + 41, // 69: wavewalletrpc.WalletService.Status:input_type -> wavewalletrpc.StatusRequest + 52, // 70: wavewalletrpc.WalletService.Refresh:input_type -> wavewalletrpc.RefreshRequest + 55, // 71: wavewalletrpc.WalletService.GetExitPlan:input_type -> wavewalletrpc.GetExitPlanRequest + 55, // 72: wavewalletrpc.WalletService.PreviewUnilateralExit:input_type -> wavewalletrpc.GetExitPlanRequest + 43, // 73: wavewalletrpc.WalletService.ExportExit:input_type -> wavewalletrpc.ExportExitRequest + 45, // 74: wavewalletrpc.WalletService.ExportExits:input_type -> wavewalletrpc.ExportExitsRequest + 60, // 75: wavewalletrpc.WalletService.SweepWallet:input_type -> wavewalletrpc.SweepWalletRequest + 63, // 76: wavewalletrpc.WalletService.Exit:input_type -> wavewalletrpc.ExitRequest + 65, // 77: wavewalletrpc.WalletService.ExitBatch:input_type -> wavewalletrpc.ExitBatchRequest + 68, // 78: wavewalletrpc.WalletService.ExitStatus:input_type -> wavewalletrpc.ExitStatusRequest + 73, // 79: wavewalletrpc.WalletService.ExitSummary:input_type -> wavewalletrpc.ExitSummaryRequest + 76, // 80: wavewalletrpc.WalletService.SubscribeWallet:input_type -> wavewalletrpc.SubscribeWalletRequest + 32, // 81: wavewalletrpc.WalletInspectionService.InspectActivity:input_type -> wavewalletrpc.InspectActivityRequest + 13, // 82: wavewalletrpc.WalletService.Create:output_type -> wavewalletrpc.CreateResponse + 15, // 83: wavewalletrpc.WalletService.Unlock:output_type -> wavewalletrpc.UnlockResponse + 17, // 84: wavewalletrpc.WalletService.PrepareSend:output_type -> wavewalletrpc.PrepareSendResponse + 19, // 85: wavewalletrpc.WalletService.Send:output_type -> wavewalletrpc.SendResponse + 22, // 86: wavewalletrpc.WalletService.Recv:output_type -> wavewalletrpc.RecvResponse + 22, // 87: wavewalletrpc.WalletService.LookupRecv:output_type -> wavewalletrpc.RecvResponse + 26, // 88: wavewalletrpc.WalletService.List:output_type -> wavewalletrpc.ListResponse + 38, // 89: wavewalletrpc.WalletService.Deposit:output_type -> wavewalletrpc.DepositResponse + 40, // 90: wavewalletrpc.WalletService.Balance:output_type -> wavewalletrpc.BalanceResponse + 42, // 91: wavewalletrpc.WalletService.Status:output_type -> wavewalletrpc.StatusResponse + 53, // 92: wavewalletrpc.WalletService.Refresh:output_type -> wavewalletrpc.RefreshResponse + 57, // 93: wavewalletrpc.WalletService.GetExitPlan:output_type -> wavewalletrpc.GetExitPlanResponse + 58, // 94: wavewalletrpc.WalletService.PreviewUnilateralExit:output_type -> wavewalletrpc.PreviewUnilateralExitResponse + 44, // 95: wavewalletrpc.WalletService.ExportExit:output_type -> wavewalletrpc.ExportExitResponse + 46, // 96: wavewalletrpc.WalletService.ExportExits:output_type -> wavewalletrpc.ExportExitsResponse + 62, // 97: wavewalletrpc.WalletService.SweepWallet:output_type -> wavewalletrpc.SweepWalletResponse + 64, // 98: wavewalletrpc.WalletService.Exit:output_type -> wavewalletrpc.ExitResponse + 67, // 99: wavewalletrpc.WalletService.ExitBatch:output_type -> wavewalletrpc.ExitBatchResponse + 72, // 100: wavewalletrpc.WalletService.ExitStatus:output_type -> wavewalletrpc.ExitStatusResponse + 75, // 101: wavewalletrpc.WalletService.ExitSummary:output_type -> wavewalletrpc.ExitSummaryResponse + 77, // 102: wavewalletrpc.WalletService.SubscribeWallet:output_type -> wavewalletrpc.SubscribeWalletResponse + 33, // 103: wavewalletrpc.WalletInspectionService.InspectActivity:output_type -> wavewalletrpc.InspectActivityResponse + 82, // [82:104] is the sub-list for method output_type + 60, // [60:82] is the sub-list for method input_type + 60, // [60:60] is the sub-list for extension type_name + 60, // [60:60] is the sub-list for extension extendee + 0, // [0:60] is the sub-list for field type_name } func init() { file_wallet_proto_init() } @@ -8167,6 +8265,7 @@ func file_wallet_proto_init() { (*ListResponse_Onchain)(nil), } file_wallet_proto_msgTypes[42].OneofWrappers = []any{} + file_wallet_proto_msgTypes[45].OneofWrappers = []any{} file_wallet_proto_msgTypes[65].OneofWrappers = []any{ (*SubscribeWalletResponse_Entry)(nil), (*SubscribeWalletResponse_Gap)(nil), diff --git a/rpc/wavewalletrpc/wallet.proto b/rpc/wavewalletrpc/wallet.proto index d11ed1cfa..a0c9c2b6a 100644 --- a/rpc/wavewalletrpc/wallet.proto +++ b/rpc/wavewalletrpc/wallet.proto @@ -1252,6 +1252,13 @@ message GetExitPlanRequest { // conf_target selects the fee-estimation target in blocks. Zero uses // the daemon's default unroll confirmation target. uint32 conf_target = 2; + + // sweep_address is an optional final payout address on the wallet's + // network. + string sweep_address = 3; + + // fee_rate_sat_per_vbyte overrides the automatic rate when positive. + int64 fee_rate_sat_per_vbyte = 4; } // ExitPlanEntry is the per-outpoint unilateral-exit readiness preview: the @@ -1405,6 +1412,13 @@ message GetExitPlanResponse { // total_recommended_funding_sat is the summed recommended funding across // entries. int64 total_recommended_funding_sat = 5; + + // sweep_address echoes the validated final payout address, if supplied. + string sweep_address = 6; + + // total_estimated_fee_sat sums the estimated costs of individual exits. + // It can overestimate when several VTXOs share recovery transactions. + optional int64 total_estimated_fee_sat = 7; } // PreviewUnilateralExitResponse quotes a full recovery from its proof graphs @@ -1441,6 +1455,9 @@ message PreviewUnilateralExitResponse { // funding_action describes the estimated use of confirmed wallet coins. UnilateralExitFundingAction funding_action = 8; + + // sweep_address echoes the validated custom destination, if supplied. + string sweep_address = 9; } // UnilateralExitTarget describes one selected coin and any existing job. @@ -1470,6 +1487,9 @@ message UnilateralExitTarget { // A cooperative round currently holds the coin. Manual recovery remains // available if the operator cannot complete the round. string round_commitment = 8; + + // infeasibility_reason identifies an economic refusal. + ExitInfeasibilityReason infeasibility_reason = 9; } // UnilateralExitFundingAction describes the initial funding requirement. @@ -1568,8 +1588,18 @@ message ExitRequest { // force_unroll_ack must be exactly "I_KNOW_WHAT_I_AM_DOING" to bypass // cooperative leave and start unilateral unroll. It cannot be combined // with onchain_address, and the server requires at least one confirmed - // local backing-wallet UTXO before admitting forced unroll. + // local backing-wallet UTXO before admitting forced unroll. To set an + // explicit fee rate or sweep address, use + // "I_KNOW_WHAT_I_AM_DOING_WITH_CUSTOM_EXIT_OPTIONS" so older daemons fail + // closed instead of ignoring the new fields. string force_unroll_ack = 3; + + // sweep_address overrides the final payout for a manual unilateral exit. + string sweep_address = 4; + + // fee_rate_sat_per_vbyte sets the initial unilateral broadcast rate. + // Zero uses automatic pricing. + int64 fee_rate_sat_per_vbyte = 5; } // ExitResponse reports the exit path the daemon took and its per-path detail @@ -1818,6 +1848,9 @@ message ExitStatusResponse { // current_height is the best block height the exit job has observed. Set // only on a detailed query against a live job. int32 current_height = 10; + + // sweep_address is the persisted custom payout, empty for wallet funding. + string sweep_address = 11; } // ExitSummaryRequest asks for the wallet-wide portfolio of in-progress exits. diff --git a/sdk/wavewalletdk/client.go b/sdk/wavewalletdk/client.go index 0a590eafb..89c99c1cc 100644 --- a/sdk/wavewalletdk/client.go +++ b/sdk/wavewalletdk/client.go @@ -679,10 +679,23 @@ func (c *Client) Exit(ctx context.Context, req ExitRequest) (*ExitResult, "force_unroll_ack") } + sweepAddress := strings.TrimSpace(req.SweepAddress) + if sweepAddress != "" || req.FeeRateSatPerVByte != 0 { + // The versioned acknowledgement makes older daemons fail closed + // rather than admitting an exit with the default destination. + if ack != "I_KNOW_WHAT_I_AM_DOING" { + return nil, fmt.Errorf("custom exit options require " + + "unilateral acknowledgement") + } + ack += "_WITH_CUSTOM_EXIT_OPTIONS" + } + resp, err := c.wallet.Exit(ctx, &wavewalletrpc.ExitRequest{ - Outpoint: req.Outpoint, - OnchainAddress: dest, - ForceUnrollAck: ack, + Outpoint: req.Outpoint, + OnchainAddress: dest, + ForceUnrollAck: ack, + SweepAddress: sweepAddress, + FeeRateSatPerVbyte: req.FeeRateSatPerVByte, }) if err != nil { return nil, fmt.Errorf("exit: %w", err) @@ -767,8 +780,10 @@ func (c *Client) GetExitPlan(ctx context.Context, req GetExitPlanRequest) ( resp, err := c.wallet.GetExitPlan( ctx, &wavewalletrpc.GetExitPlanRequest{ - Outpoints: req.Outpoints, - ConfTarget: req.ConfTarget, + Outpoints: req.Outpoints, + ConfTarget: req.ConfTarget, + SweepAddress: strings.TrimSpace(req.SweepAddress), + FeeRateSatPerVbyte: req.FeeRateSatPerVByte, }, ) if err != nil { diff --git a/sdk/wavewalletdk/client_exit_test.go b/sdk/wavewalletdk/client_exit_test.go index 07fd4946f..749b28742 100644 --- a/sdk/wavewalletdk/client_exit_test.go +++ b/sdk/wavewalletdk/client_exit_test.go @@ -214,3 +214,40 @@ func TestExitRejectsEmptyOutpoint(t *testing.T) { require.Nil(t, res) require.Zero(t, wallet.exitCalls) } + +// TestManualExitOptionsUseVersionedAck ensures a consumer with an older +// daemon cannot admit the default payout by silently ignoring the new fields. +func TestManualExitOptionsUseVersionedAck(t *testing.T) { + t.Parallel() + + wallet := &stubWalletClient{ + exit: func(_ context.Context, _ *wavewalletrpc.ExitRequest) ( + *wavewalletrpc.ExitResponse, error) { + + mode := wavewalletrpc.ExitMode_EXIT_MODE_UNILATERAL + + return &wavewalletrpc.ExitResponse{ + Mode: mode, + Created: true, + }, nil + }, + } + client := newExitTestClient(wallet) + _, err := client.Exit(t.Context(), ExitRequest{ + Outpoint: testExitOutpoint, SweepAddress: testExitDestination, + FeeRateSatPerVByte: 7, + }) + require.Error(t, err) + require.Zero(t, wallet.exitCalls) + _, err = client.Exit(t.Context(), ExitRequest{ + Outpoint: testExitOutpoint, ForceUnrollAck: testForceUnrollAck, + SweepAddress: testExitDestination, FeeRateSatPerVByte: 7, + }) + require.NoError(t, err) + require.Equal( + t, testForceUnrollAck+"_WITH_CUSTOM_EXIT_OPTIONS", + wallet.lastExit.GetForceUnrollAck(), + ) + require.Equal(t, testExitDestination, wallet.lastExit.GetSweepAddress()) + require.EqualValues(t, 7, wallet.lastExit.GetFeeRateSatPerVbyte()) +} diff --git a/sdk/wavewalletdk/convert.go b/sdk/wavewalletdk/convert.go index 89b4eb91c..2c72537d8 100644 --- a/sdk/wavewalletdk/convert.go +++ b/sdk/wavewalletdk/convert.go @@ -236,9 +236,10 @@ func exitStatusResultFromProto( Status: exitJobStatusFromProto( resp.GetStatus(), ), - SweepTxid: resp.GetSweepTxid(), - LastError: resp.GetLastError(), - PhaseDetail: resp.GetPhaseDetail(), + SweepTxid: resp.GetSweepTxid(), + SweepAddress: resp.GetSweepAddress(), + LastError: resp.GetLastError(), + PhaseDetail: resp.GetPhaseDetail(), Progress: exitProgressFromProto( resp.GetProgress(), ), @@ -347,6 +348,8 @@ func exitPlanFromProto( } return &GetExitPlanResult{ + SweepAddress: r.GetSweepAddress(), + TotalEstimatedFeeSat: r.TotalEstimatedFeeSat, Plans: plans, FeeRateSatPerVByte: r.GetFeeRateSatPerVbyte(), CanStart: r.GetCanStart(), diff --git a/sdk/wavewalletdk/types.go b/sdk/wavewalletdk/types.go index 96f6f3d0c..ea23c66ac 100644 --- a/sdk/wavewalletdk/types.go +++ b/sdk/wavewalletdk/types.go @@ -517,6 +517,14 @@ type ExitRequest struct { // cooperative leave and start unilateral unroll. Cannot be combined // with Destination; the server rejects the pair with InvalidArgument. ForceUnrollAck string + + // SweepAddress is the optional final destination of the unilateral + // sweep. + SweepAddress string + + // FeeRateSatPerVByte is the initial unilateral fee rate, or zero for + // automatic. + FeeRateSatPerVByte int64 } // ExitPath identifies which branch of the Exit decision tree the @@ -609,7 +617,9 @@ type ExitStatusResult struct { Found bool Status ExitJobStatus SweepTxid string - LastError string + // SweepAddress is the durable custom payout for a detailed status read. + SweepAddress string + LastError string // PhaseDetail is a one-line human description of the current phase. // Empty on a coarse (non-detailed) query. @@ -700,6 +710,12 @@ type ExitSummaryEntry struct { type GetExitPlanRequest struct { Outpoints []string ConfTarget uint32 + + // SweepAddress validates and quotes a custom final destination. + SweepAddress string + + // FeeRateSatPerVByte overrides the automatic rate when positive. + FeeRateSatPerVByte int64 } // ExitPlanEntry describes how to fund the backing wallet before Exit for a @@ -757,6 +773,12 @@ const ( // GetExitPlanResult describes the combined backing-wallet funding plan for // every previewed outpoint plus aggregate totals. type GetExitPlanResult struct { + // SweepAddress is the canonical destination acknowledged by the daemon. + SweepAddress string + + // TotalEstimatedFeeSat is nil when the full selection could not be + // quoted. + TotalEstimatedFeeSat *int64 Plans []ExitPlanEntry FeeRateSatPerVByte int64 CanStart bool diff --git a/sdk/wavewalletdk/unilateral_exit_preview.go b/sdk/wavewalletdk/unilateral_exit_preview.go index e41e76161..6ab9bbe2c 100644 --- a/sdk/wavewalletdk/unilateral_exit_preview.go +++ b/sdk/wavewalletdk/unilateral_exit_preview.go @@ -44,6 +44,9 @@ type UnilateralExitPreview struct { // Entries retains request order and reports the outcome of each // selected outpoint. Entries []UnilateralExitTarget + + // SweepAddress is the validated custom destination, if requested. + SweepAddress string } // UnilateralExitTarget reports the selected coin's deadline and current job. @@ -73,6 +76,9 @@ type UnilateralExitTarget struct { // dust. AdmissionError string + // InfeasibilityReason identifies an economic refusal. + InfeasibilityReason ExitInfeasibilityReason + // RoundCommitment warns that a cooperative round holds this VTXO. // Manual recovery remains available. RoundCommitment string @@ -88,8 +94,10 @@ func (c *Client) PreviewUnilateralExit(ctx context.Context, } resp, err := c.wallet.PreviewUnilateralExit( ctx, &wavewalletrpc.GetExitPlanRequest{ - Outpoints: req.Outpoints, - ConfTarget: req.ConfTarget, + Outpoints: req.Outpoints, + ConfTarget: req.ConfTarget, + SweepAddress: req.SweepAddress, + FeeRateSatPerVbyte: req.FeeRateSatPerVByte, }, ) if err != nil { @@ -103,6 +111,7 @@ func (c *Client) PreviewUnilateralExit(ctx context.Context, EstimatedNetworkFeeSat: resp.GetEstimatedNetworkFeeSat(), WalletFeeSat: resp.GetWalletFeeSat(), AdditionalFundingSat: resp.GetAdditionalFundingSat(), + SweepAddress: resp.GetSweepAddress(), FundingAction: strings.ToLower( strings.TrimPrefix( resp.GetFundingAction().String(), @@ -119,9 +128,12 @@ func (c *Client) PreviewUnilateralExit(ctx context.Context, ExitStatus: exitJobStatusFromProto( entry.GetExitStatus(), ), - SweepTxid: entry.GetSweepTxid(), - LastError: entry.GetLastError(), - AdmissionError: entry.GetAdmissionError(), + SweepTxid: entry.GetSweepTxid(), + LastError: entry.GetLastError(), + AdmissionError: entry.GetAdmissionError(), + InfeasibilityReason: exitInfeasibilityReasonFromProto( + entry.GetInfeasibilityReason(), + ), RoundCommitment: entry.GetRoundCommitment(), }) } diff --git a/sdk/wavewalletdk/unilateral_exit_preview_test.go b/sdk/wavewalletdk/unilateral_exit_preview_test.go index af08a2cb5..09e375209 100644 --- a/sdk/wavewalletdk/unilateral_exit_preview_test.go +++ b/sdk/wavewalletdk/unilateral_exit_preview_test.go @@ -31,6 +31,8 @@ func (s *previewWalletClient) PreviewUnilateralExit(_ context.Context, return &wavewalletrpc.PreviewUnilateralExitResponse{ SelectedAmountSat: 20_000, AdditionalFundingSat: 10_000, + FeeRateSatPerVbyte: req.GetFeeRateSatPerVbyte(), + SweepAddress: req.GetSweepAddress(), Entries: []*wavewalletrpc.UnilateralExitTarget{ { Outpoint: "a:0", @@ -47,11 +49,23 @@ func TestPreviewUnilateralExit(t *testing.T) { t.Parallel() wallet := &previewWalletClient{} client := newExitTestClient(wallet) - req := GetExitPlanRequest{Outpoints: []string{"a:0"}, ConfTarget: 2} + req := GetExitPlanRequest{ + Outpoints: []string{ + "a:0", + }, ConfTarget: 2, + SweepAddress: "bcrt1qexample", FeeRateSatPerVByte: 7, + } preview, err := client.PreviewUnilateralExit(t.Context(), req) require.NoError(t, err) require.Equal(t, req.Outpoints, wallet.request.GetOutpoints()) require.EqualValues(t, 2, wallet.request.GetConfTarget()) + require.Equal(t, req.SweepAddress, wallet.request.GetSweepAddress()) + require.Equal( + t, req.FeeRateSatPerVByte, + wallet.request.GetFeeRateSatPerVbyte(), + ) + require.Equal(t, req.SweepAddress, preview.SweepAddress) + require.Equal(t, req.FeeRateSatPerVByte, preview.FeeRateSatPerVByte) require.EqualValues(t, 20_000, preview.SelectedAmountSat) require.EqualValues(t, 10_000, preview.AdditionalFundingSat) require.Len(t, preview.Entries, 1) diff --git a/swapwallet/admin.go b/swapwallet/admin.go index 6d3989623..ca55b56db 100644 --- a/swapwallet/admin.go +++ b/swapwallet/admin.go @@ -143,6 +143,13 @@ func (s *Service) exit(ctx context.Context, req *wavewalletrpc.ExitRequest) ( return s.forceUnroll(ctx, req, ack) } + if req.GetSweepAddress() != "" || req.GetFeeRateSatPerVbyte() != 0 { + return nil, status.Error( + codes.InvalidArgument, "custom sweep address and "+ + "fee rate require unilateral exit", + ) + } + return s.cooperativeExit(ctx, req) } @@ -219,19 +226,48 @@ func (s *Service) forceUnroll(ctx context.Context, "to the given address instead", ) } - if ack != forceUnrollAck { + custom := req.GetSweepAddress() != "" || + req.GetFeeRateSatPerVbyte() != 0 + requiredAck := forceUnrollAck + if custom { + requiredAck += "_WITH_CUSTOM_EXIT_OPTIONS" + } + if ack != requiredAck { return nil, status.Errorf(codes.InvalidArgument, - "force_unroll_ack must be exactly %q", forceUnrollAck) + "force_unroll_ack must be exactly %q", requiredAck) } if err := s.requireLocalUnrollBalance(ctx); err != nil { return nil, err } - resp, err := s.deps.RPCServer.Unroll( - ctx, &waverpc.UnrollRequest{ - Outpoint: req.GetOutpoint(), - }, + var ( + resp *waverpc.UnrollResponse + err error ) + if custom { + server, ok := s.deps.RPCServer.(interface { + UnrollWithOptions(context.Context, string, + waved.ManualExitTerms) ( + *waverpc.UnrollResponse, + error, + ) + }) + if !ok { + return nil, status.Error( + codes.Unimplemented, "custom unilateral "+ + "exit options are unavailable", + ) + } + resp, err = server.UnrollWithOptions(ctx, req.GetOutpoint(), + waved.ManualExitTerms{ + SweepAddress: req.GetSweepAddress(), + FeeRateSatPerVByte: req.GetFeeRateSatPerVbyte(), + }) + } else { + resp, err = s.deps.RPCServer.Unroll(ctx, &waverpc.UnrollRequest{ + Outpoint: req.GetOutpoint(), + }) + } if err != nil { return nil, status.Errorf(status.Code(err), "exit: %v", err) } @@ -306,6 +342,10 @@ func (s *Service) getExitPlan(ctx context.Context, ctx, &waved.ExitPlanRequest{ Outpoints: req.GetOutpoints(), ConfTarget: req.GetConfTarget(), + ManualTerms: waved.ManualExitTerms{ + SweepAddress: req.GetSweepAddress(), + FeeRateSatPerVByte: req.GetFeeRateSatPerVbyte(), + }, }, ) if err != nil { @@ -345,6 +385,8 @@ func (s *Service) getExitPlan(ctx context.Context, CanStart: resp.CanStart, TotalFundingShortfallSat: resp.TotalFundingShortfallSat, TotalRecommendedFundingSat: resp.TotalRecommendedFundingSat, + SweepAddress: resp.SweepAddress, + TotalEstimatedFeeSat: resp.TotalEstimatedFeeSat, }, nil } @@ -360,6 +402,10 @@ func (s *Service) PreviewUnilateralExit(ctx context.Context, ctx, &waved.ExitPlanRequest{ Outpoints: req.GetOutpoints(), ConfTarget: req.GetConfTarget(), + ManualTerms: waved.ManualExitTerms{ + SweepAddress: req.GetSweepAddress(), + FeeRateSatPerVByte: req.GetFeeRateSatPerVbyte(), + }, }, ) if err != nil { @@ -372,6 +418,7 @@ func (s *Service) PreviewUnilateralExit(ctx context.Context, EstimatedNetworkFeeSat: int64(preview.Quote.NetworkFee), WalletFeeSat: int64(preview.Quote.WalletFee), AdditionalFundingSat: int64(preview.Quote.Deposit), + SweepAddress: preview.SweepAddress, } switch { case preview.Quote.Transactions == 0: @@ -399,6 +446,9 @@ func (s *Service) PreviewUnilateralExit(ctx context.Context, SweepTxid: entry.Status.GetSweepTxid(), LastError: entry.Status.GetLastError(), AdmissionError: entry.AdmissionError, + InfeasibilityReason: infeasibilityReasonFromUnroll( + entry.InfeasibilityReason, + ), RoundCommitment: errorString( entry.RoundCommitment, ), @@ -482,11 +532,12 @@ func (s *Service) exitStatus(ctx context.Context, } return &wavewalletrpc.ExitStatusResponse{ - Found: resp.GetFound(), - Status: exitStatusFromDaemon(resp.GetStatus()), - SweepTxid: resp.GetSweepTxid(), - LastError: resp.GetLastError(), - PhaseDetail: resp.GetPhaseDetail(), + Found: resp.GetFound(), + Status: exitStatusFromDaemon(resp.GetStatus()), + SweepTxid: resp.GetSweepTxid(), + SweepAddress: resp.GetSweepAddress(), + LastError: resp.GetLastError(), + PhaseDetail: resp.GetPhaseDetail(), Progress: exitProgressFromDaemon( resp.GetProgress(), ), diff --git a/txconfirm/actor.go b/txconfirm/actor.go index 2b90cdfa8..082350580 100644 --- a/txconfirm/actor.go +++ b/txconfirm/actor.go @@ -1747,11 +1747,12 @@ func (a *TxBroadcasterActor) newTrackedTx(ctx context.Context, ConfirmationPkScript: append( []byte(nil), confirmationPkScript..., ), - Label: req.Label, - HeightHint: heightHint, - TargetConfs: targetConfs, - ParentFee: req.ParentFee, - RetryUntilAccepted: req.RetryUntilAccepted, + Label: req.Label, + HeightHint: heightHint, + TargetConfs: targetConfs, + ParentFee: req.ParentFee, + RetryUntilAccepted: req.RetryUntilAccepted, + InitialFeeRateSatPerVByte: req.InitialFeeRateSatPerVByte, } fsm := newTrackedTxStateMachine(fsmLog, data) @@ -2036,7 +2037,7 @@ func (a *TxBroadcasterActor) broadcastTrackedTxOpts(ctx context.Context, // regardless of its outcome (including an early FSM-advance failure // below), so clear it on every exit path: a failed forced bump must not // silently pin the operator's rate onto later interval-paced bumps. - targetFeeRate := int64(0) + targetFeeRate := entry.data.InitialFeeRateSatPerVByte if isFeeBump { targetFeeRate = entry.pendingTargetFeeRate defer func() { diff --git a/txconfirm/actor_test.go b/txconfirm/actor_test.go index 74b7324a7..a1a07dad4 100644 --- a/txconfirm/actor_test.go +++ b/txconfirm/actor_test.go @@ -3187,3 +3187,36 @@ func TestInitialConfirmedAsyncDeliveryRetainsSubscriber(t *testing.T) { "completed via the async path — handleTerminalNotify"+ "Result probably evicted it on completion") } + +// TestManualPackageUsesInitialFeeRate checks the actual child fee under a +// new anchor publication with an explicit rate. +func TestManualPackageUsesInitialFeeRate(t *testing.T) { + chain := newFakeChainSourceRef(100) + coin := makeWalletUTXO(t) + ref, _ := newTestActor(t, Config{ + ChainSource: chain, + Wallet: &fakeWallet{utxos: []*walletcore.Utxo{coin}}, + }) + tx := makeTestTx(true) + const customRate = 7 + resp := mustEnsure(t, ref.Ref(), &EnsureConfirmedReq{ + Tx: tx, + Subscriber: actor.NewChannelTellOnlyRef[Notification]( + "manual", 4, + ), + InitialFeeRateSatPerVByte: customRate, + }) + require.Equal(t, TxStateAwaitingConfirmation, resp.State) + require.Equal(t, 1, chain.packageCallCount()) + + chain.mu.Lock() + child := chain.packageCalls[0].Child.Copy() + chain.mu.Unlock() + + require.Len(t, child.TxOut, 1) + pkgVBytes := (EstimateWeight(tx) + EstimateWeight(child) + 3) / 4 + require.GreaterOrEqual( + t, int64(coin.Amount)-child.TxOut[0].Value, + pkgVBytes*customRate, + ) +} diff --git a/txconfirm/fsm_types.go b/txconfirm/fsm_types.go index 05bc925cd..57dc7ae69 100644 --- a/txconfirm/fsm_types.go +++ b/txconfirm/fsm_types.go @@ -78,6 +78,9 @@ type trackedTxData struct { // RetryUntilAccepted is the caller's initial-broadcast retry contract. RetryUntilAccepted bool + // InitialFeeRateSatPerVByte is the requested first-publication rate. + InitialFeeRateSatPerVByte int64 + // ParentFee is the absolute miner fee, in satoshis, that the tracked // transaction already pays on its own. It is used only for a funded- // anchor parent, where the CPFP child subtracts it so a fee bump lands diff --git a/txconfirm/messages.go b/txconfirm/messages.go index 5cc9accef..c77e230fd 100644 --- a/txconfirm/messages.go +++ b/txconfirm/messages.go @@ -147,6 +147,11 @@ type EnsureConfirmedReq struct { // agree. RetryUntilAccepted bool + // InitialFeeRateSatPerVByte sets the first publication rate for an + // anchor package. Zero uses the estimator. An existing txid keeps its + // rate because the package may already be broadcast for another exit. + InitialFeeRateSatPerVByte int64 + // ParentFee is the absolute miner fee, in satoshis, that Tx already // pays. It is used only for a funded-anchor parent so a later CPFP fee // bump subtracts the parent's own fee and lands the combined fee on the diff --git a/unroll/actor.go b/unroll/actor.go index a8ce884b7..c14e8ad24 100644 --- a/unroll/actor.go +++ b/unroll/actor.go @@ -1205,12 +1205,18 @@ func (b *behavior) ensureNodeConfirmed(ctx context.Context, return err } + var initialFeeRate int64 + if b.desc != nil && b.desc.ManualExitOptions != nil { + initialFeeRate = b.desc.ManualExitOptions.FeeRateSatPerVByte + } + resp, err := b.cfg.TxConfirmRef.Ask(ctx, &txconfirm.EnsureConfirmedReq{ - Tx: node.Tx, - ConfirmationPkScript: pkScript, - Label: "unroll-node-" + txid.String(), - HeightHint: heightHint, - Subscriber: b.notificationRef(), + Tx: node.Tx, + InitialFeeRateSatPerVByte: initialFeeRate, + ConfirmationPkScript: pkScript, + Label: "unroll-node-" + txid.String(), + HeightHint: heightHint, + Subscriber: b.notificationRef(), }).Await(ctx).Unpack() if err != nil { return err @@ -3089,7 +3095,18 @@ func (b *behavior) emitExitCostIfCompleted(ctx context.Context, phase Phase, sink := b.cfg.LedgerSink.UnsafeFromSome() if !b.exitCostNotified { - msg, err := b.exitCostMsg(job) + ownWallet, err := b.exitPaysWallet(ctx) + if err != nil { + b.log.WarnS( + ctx, + "Deferring exit accounting; payout ownership "+ + "lookup failed", + err, + ) + + return false + } + msg, err := b.exitCostMsg(job, ownWallet) if err != nil { b.log.ErrorS(ctx, "Unbuildable unroll exit cost on "+ "completed actor", err) @@ -3107,11 +3124,35 @@ func (b *behavior) emitExitCostIfCompleted(ctx context.Context, phase Phase, } b.exitCostNotified = true + if !ownWallet { + b.proceedsRecorded = true + } } return b.recordExitProceedsUTXO(ctx, notifyCtx, sink, job) } +// exitPaysWallet preserves the default wallet-owned sweep and checks whether +// an explicitly chosen destination is also owned before crediting proceeds. +func (b *behavior) exitPaysWallet(ctx context.Context) (bool, error) { + if b.desc == nil || b.desc.ManualExitOptions == nil || + len(b.desc.ManualExitOptions.SweepScript) == 0 { + return true, nil + } + if b.cfg.OwnedWalletScripts.IsNone() { + return false, nil + } + + script, err := safeTxOutPkScript(b.sweepTx, 0) + if err != nil { + return false, err + } + + return b.cfg.OwnedWalletScripts.UnsafeFromSome().IsOwnedWalletScript( + ctx, script, + ) +} + // recordExitProceedsUTXO records the sweep output the exit paid into the // wallet UTXO audit log. It carries its own once-flag rather than sharing the // exit cost's, so a transient failure here retries only this message and does @@ -3245,7 +3286,9 @@ func (b *behavior) exitProceedsMsg(ctx context.Context, job *JobState) ( // exitCostMsg derives the ledger event from the proof target output and the // persisted final sweep transaction. -func (b *behavior) exitCostMsg(job *JobState) (*ledger.ExitCostMsg, error) { +func (b *behavior) exitCostMsg(job *JobState, ownWallet bool) ( + *ledger.ExitCostMsg, error) { + if b.proof == nil { return nil, fmt.Errorf("missing proof") } @@ -3288,34 +3331,13 @@ func (b *behavior) exitCostMsg(job *JobState) (*ledger.ExitCostMsg, error) { target := b.proof.TargetOutpoint() - // DestinationOwnWallet is a literal rather than a comparison of - // safeTxOutPkScript(b.sweepTx, 0) against the wallet script, because - // nothing durable carries that script: buildSweepTx derives it from - // SweepWallet.NewWalletPkScript at build time and the checkpoint keeps - // only the sweep tx, so a restart-resumed unroll has nothing to - // compare against. Adding it would be a checkpoint format change. - // - // The invariant the literal stands on: every sweep this package builds - // pays a script the wallet handed out. buildSweepTx (unroll/sweep.go) - // sources DestinationPkScript from SweepWallet.NewWalletPkScript, and - // the one exit-spend policy in this package, - // StandardVTXOExitSpendPolicy, writes that script verbatim into the - // output it adds. So the exited value landed back in the client's own - // wallet rather than leaving for a counterparty, and the ledger books - // the send leg as an internal move into wallet_balance instead of an - // outflow. A future exit-spend policy that pays a caller-supplied - // destination must revisit this. - // - // The flag says only that the value came home; which output it came - // home to is exitProceedsMsg's question, and that one is answered - // from the owned-script registry rather than from this invariant. return &ledger.ExitCostMsg{ OutpointHash: target.Hash, OutpointIndex: target.Index, AmountSat: targetOutput.Value, ExitCostSat: exitCost, BlockHeight: height, - DestinationOwnWallet: true, + DestinationOwnWallet: ownWallet, }, nil } diff --git a/unroll/exit_plan.go b/unroll/exit_plan.go index dcdc7590f..81fa69d1e 100644 --- a/unroll/exit_plan.go +++ b/unroll/exit_plan.go @@ -2,6 +2,9 @@ package unroll import ( "github.com/btcsuite/btcd/btcutil/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/btcsuite/btcwallet/wallet/txrules" + "github.com/lightninglabs/wavelength/lib/actormsg" "github.com/lightninglabs/wavelength/txconfirm" "github.com/lightninglabs/wavelength/vtxo" ) @@ -45,6 +48,15 @@ type ExitFundingPlan struct { func PlanExitFunding(desc *vtxo.Descriptor, mat *LineageMaterial, feeRate btcutil.Amount, wallet ExitFundingSnapshot) ExitFundingPlan { + return PlanExitFundingWithOptions(desc, mat, feeRate, wallet, nil) +} + +// PlanExitFundingWithOptions uses the same fee model with the chosen final +// payout script's dust threshold. +func PlanExitFundingWithOptions(desc *vtxo.Descriptor, mat *LineageMaterial, + feeRate btcutil.Amount, wallet ExitFundingSnapshot, + options *actormsg.ManualExitOptions) ExitFundingPlan { + numTxs, numPaths, vbytes := recoveryEstimate(desc, mat) var ( amount btcutil.Amount @@ -66,6 +78,24 @@ func PlanExitFunding(desc *vtxo.Descriptor, mat *LineageMaterial, AssetClaim: assetClaim, }) + if options != nil && len(options.SweepScript) != 0 && + isDustExitPayout( + options.SweepScript, feasibility.NetRecoveredSat, + ) { + + feasibility.Feasible = false + feasibility.Reason = ExitSweepBelowDust + } + // A deposit cannot fix dust or an exit that costs more than the coin. + // Preserve the cost estimate so callers can explain the blocked exit. + if feasibility.Reason == ExitSweepBelowDust || + feasibility.Reason == ExitUneconomical { + return ExitFundingPlan{ + Feasibility: feasibility, + RequiredConfirmations: RequiredFeeInputConfirmations, + } + } + recommended := RecommendedExitFeeInputAmount(feasibility) return ExitFundingPlan{ @@ -139,3 +169,14 @@ func ceilDivAmount(a, b btcutil.Amount) btcutil.Amount { return (a + b - 1) / b } + +// isDustExitPayout checks the payout against the exact script's standard relay +// floor. +func isDustExitPayout(script []byte, amount btcutil.Amount) bool { + return txrules.IsDustOutput( + wire.NewTxOut( + int64(amount), script, + ), + txrules.DefaultRelayFeePerKb, + ) +} diff --git a/unroll/exit_plan_test.go b/unroll/exit_plan_test.go index 4ac33aaca..1edfc274a 100644 --- a/unroll/exit_plan_test.go +++ b/unroll/exit_plan_test.go @@ -74,6 +74,48 @@ func TestPlanExitFundingShortfallCoversBalance(t *testing.T) { require.EqualValues(t, 610, plan.FundingShortfallSat) } +// TestPlanExitFundingRejectsDepositsForStructuralBlocks checks that an +// empty wallet cannot turn a dust or uneconomical exit into a funding request. +func TestPlanExitFundingRejectsDepositsForStructuralBlocks(t *testing.T) { + t.Parallel() + + tests := []struct { + amount btcutil.Amount + reason ExitInfeasibilityReason + }{ + { + 1_200, + ExitSweepBelowDust, + }, + { + 2_000, + ExitUneconomical, + }, + } + for _, tc := range tests { + t.Run(tc.reason.String(), func(t *testing.T) { + t.Parallel() + + plan := PlanExitFunding( + testExitPlanDescriptor(tc.amount, 2), nil, 6, + ExitFundingSnapshot{}, + ) + + require.False(t, plan.Feasibility.Feasible) + require.Equal(t, tc.reason, plan.Feasibility.Reason) + require.Equal( + t, 2, plan.Feasibility.RequiredWalletInputs, + ) + require.Positive( + t, plan.Feasibility.TotalRecoveryCostSat, + ) + require.Zero(t, plan.FundingShortfallSat) + require.Zero(t, plan.RecommendedTotalFundingSat) + require.Zero(t, plan.RecommendedUTXOAmountSat) + }) + } +} + func testExitPlanDescriptor(amount btcutil.Amount, paths int) *vtxo.Descriptor { desc := &vtxo.Descriptor{ Amount: amount, diff --git a/unroll/manual_exit_test.go b/unroll/manual_exit_test.go new file mode 100644 index 000000000..6b120cc85 --- /dev/null +++ b/unroll/manual_exit_test.go @@ -0,0 +1,68 @@ +package unroll + +import ( + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/lightninglabs/wavelength/lib/actormsg" + "github.com/stretchr/testify/require" +) + +// TestManualSweepSignsRequestedPayout checks the signed Bitcoin output and +// verifies that the requested rate overrides the chain estimator. +func TestManualSweepSignsRequestedPayout(t *testing.T) { + t.Parallel() + + proof, desc, wallet := signedSweepFixture(t) + key, err := btcec.NewPrivateKey() + require.NoError(t, err) + destination, err := txscript.PayToTaprootScript(key.PubKey()) + require.NoError(t, err) + const feeRate = 7 + desc.ManualExitOptions = &actormsg.ManualExitOptions{ + SweepScript: destination, FeeRateSatPerVByte: feeRate, + } + + sweep, err := buildSweepTx( + t.Context(), wallet, &fakeChainSourceRef{}, proof, desc, 100, 2, + 104, NewStandardVTXOExitSpendPolicy(desc), + ) + require.NoError(t, err) + target, err := proof.TargetOutput() + require.NoError(t, err) + require.Len(t, sweep.TxOut, 1) + require.Equal(t, destination, sweep.TxOut[0].PkScript) + require.EqualValues( + t, feeRate*estimatedSweepVBytes, + target.Value-sweep.TxOut[0].Value, + ) + require.NotEmpty(t, sweep.TxIn[0].Witness) +} + +// TestManualExternalSweepDoesNotCreditWallet checks the completion ledger +// classifies the payout from its actual destination. +func TestManualExternalSweepDoesNotCreditWallet(t *testing.T) { + t.Parallel() + + proof, desc, wallet := signedSweepFixture(t) + key, err := btcec.NewPrivateKey() + require.NoError(t, err) + destination, err := txscript.PayToTaprootScript(key.PubKey()) + require.NoError(t, err) + desc.ManualExitOptions = &actormsg.ManualExitOptions{ + SweepScript: destination, FeeRateSatPerVByte: 7, + } + tx, err := buildSweepTx( + t.Context(), wallet, &fakeChainSourceRef{}, proof, desc, 100, 2, + 104, NewStandardVTXOExitSpendPolicy(desc), + ) + require.NoError(t, err) + b := &behavior{proof: proof, desc: desc, sweepTx: tx} + + owned, err := b.exitPaysWallet(t.Context()) + require.NoError(t, err) + msg, err := b.exitCostMsg(&JobState{}, owned) + require.NoError(t, err) + require.False(t, msg.DestinationOwnWallet) +} diff --git a/unroll/sweep.go b/unroll/sweep.go index 77a7ee9ed..c6b7194ca 100644 --- a/unroll/sweep.go +++ b/unroll/sweep.go @@ -393,19 +393,33 @@ func buildSweepTx(ctx context.Context, wallet SweepWallet, return nil, err } - feeRate, err := estimateSweepFeeRate( - ctx, chainSource, maxFeeRate, fallbackFeeRate, + var ( + feeRate int64 + sweepPkScript []byte ) - if err != nil { - return nil, fmt.Errorf("estimate fee: %w", err) + if options := desc.ManualExitOptions; options != nil && + policy.Kind() == StandardVTXOTimeoutExitPolicyKind { + + feeRate = options.FeeRateSatPerVByte + sweepPkScript = options.SweepScript + } + if feeRate == 0 { + feeRate, err = estimateSweepFeeRate( + ctx, chainSource, maxFeeRate, fallbackFeeRate, + ) + if err != nil { + return nil, fmt.Errorf("estimate fee: %w", err) + } } // The actor supplies a wallet that retains one destination across // unsigned deferrals. Once signed, the staged transaction retains it // across restart and broadcast retries. - sweepPkScript, err := wallet.NewWalletPkScript(ctx) - if err != nil { - return nil, fmt.Errorf("sweep pkscript: %w", err) + if len(sweepPkScript) == 0 { + sweepPkScript, err = wallet.NewWalletPkScript(ctx) + if err != nil { + return nil, fmt.Errorf("sweep pkscript: %w", err) + } } if len(sweepPkScript) == 0 { diff --git a/vtxo/actor.go b/vtxo/actor.go index ce65e002f..85ff2b938 100644 --- a/vtxo/actor.go +++ b/vtxo/actor.go @@ -1149,6 +1149,21 @@ func (a *VTXOActor) processStatusUpdate(ctx context.Context, ) switch { + case m.ManualExitOptions != nil: + store, ok := a.cfg.Store.(interface { + UpdateVTXOStatusWithExitOptions(context.Context, + wire.OutPoint, *actormsg.ManualExitOptions, + bool) error + }) + if !ok { + return fmt.Errorf("VTXO store cannot persist manual " + + "exit options") + } + err = store.UpdateVTXOStatusWithExitOptions( + ctx, m.Outpoint, m.ManualExitOptions, + m.ReleaseSpendReservation, + ) + case isForfeitingWithTx: err = a.cfg.Store.MarkForfeiting( ctx, m.Outpoint, m.RoundID, m.ForfeitTx, diff --git a/vtxo/events.go b/vtxo/events.go index f7d5de8cc..a92833db6 100644 --- a/vtxo/events.go +++ b/vtxo/events.go @@ -161,6 +161,9 @@ type ForceUnrollEvent struct { // persist for this target. None selects the standard VTXO timeout // policy. ExitPolicy fn.Option[actormsg.ExitPolicy] + + // ManualOptions are persisted before publishing the exit notification. + ManualOptions *actormsg.ManualExitOptions } // VTXOActorMsg implements actormsg.VTXOActorMsg marker interface. diff --git a/vtxo/interfaces.go b/vtxo/interfaces.go index ad42085fc..cc1a1fdec 100644 --- a/vtxo/interfaces.go +++ b/vtxo/interfaces.go @@ -11,6 +11,7 @@ import ( "github.com/btcsuite/btcwallet/waddrmgr" "github.com/lightninglabs/wavelength/arkrpc" "github.com/lightninglabs/wavelength/baselib/protofsm" + "github.com/lightninglabs/wavelength/lib/actormsg" "github.com/lightninglabs/wavelength/lib/types" "github.com/lightninglabs/wavelength/round" fn "github.com/lightningnetwork/lnd/fn/v2" @@ -364,6 +365,10 @@ const MaxTaprootAssetRefBytes = 512 // is the canonical representation persisted to storage and passed between // actors. type Descriptor struct { + // ManualExitOptions is present when an admitted exit has a custom + // payout script or fee rate. + ManualExitOptions *actormsg.ManualExitOptions + // Outpoint identifies the VTXO's location in the virtual transaction // tree. Outpoint wire.OutPoint diff --git a/vtxo/manager.go b/vtxo/manager.go index 03048beb9..066804830 100644 --- a/vtxo/manager.go +++ b/vtxo/manager.go @@ -1129,9 +1129,10 @@ func (m *Manager) handleForceUnroll(ctx context.Context, } resp, err := actorRef.Ask(ctx, &ForceUnrollEvent{ - Reason: reason, - Trigger: req.Trigger, - ExitPolicy: req.ExitPolicy, + Reason: reason, + Trigger: req.Trigger, + ExitPolicy: req.ExitPolicy, + ManualOptions: req.ManualOptions, }).Await(ctx).Unpack() if err != nil { return fn.Err[ManagerResp]( diff --git a/vtxo/outbox_messages.go b/vtxo/outbox_messages.go index fbe1c3f94..555a2e3ac 100644 --- a/vtxo/outbox_messages.go +++ b/vtxo/outbox_messages.go @@ -167,6 +167,10 @@ type VTXOStatusUpdate struct { // same transaction as the status update. Set on transitions that move // the VTXO out of SpendingState so the row never outlives the spend. ReleaseSpendReservation bool + + // ManualExitOptions binds the requested payout and fee to this status + // transition before the exit registry can start work. + ManualExitOptions *actormsg.ManualExitOptions } func (m *VTXOStatusUpdate) vtxoOutMsgSealed() {} diff --git a/vtxo/transitions.go b/vtxo/transitions.go index ae1dc7f0f..2cbcdbb9b 100644 --- a/vtxo/transitions.go +++ b/vtxo/transitions.go @@ -274,8 +274,9 @@ func (s *LiveState) handleForceUnroll(_ context.Context, ExitPolicy: evt.ExitPolicy, }, &VTXOStatusUpdate{ - Outpoint: s.VTXO.Outpoint, - NewStatus: VTXOStatusUnilateralExit, + Outpoint: s.VTXO.Outpoint, + NewStatus: VTXOStatusUnilateralExit, + ManualExitOptions: evt.ManualOptions, }, } @@ -852,8 +853,9 @@ func (s *PendingForfeitState) ProcessEvent(ctx context.Context, event VTXOEvent, ExitPolicy: evt.ExitPolicy, }, &VTXOStatusUpdate{ - Outpoint: s.VTXO.Outpoint, - NewStatus: VTXOStatusUnilateralExit, + Outpoint: s.VTXO.Outpoint, + NewStatus: VTXOStatusUnilateralExit, + ManualExitOptions: evt.ManualOptions, }, } @@ -1257,8 +1259,9 @@ func (s *ForfeitingState) ProcessEvent(ctx context.Context, event VTXOEvent, ExitPolicy: evt.ExitPolicy, }, &VTXOStatusUpdate{ - Outpoint: s.VTXO.Outpoint, - NewStatus: VTXOStatusUnilateralExit, + Outpoint: s.VTXO.Outpoint, + NewStatus: VTXOStatusUnilateralExit, + ManualExitOptions: evt.ManualOptions, }, } @@ -1510,8 +1513,9 @@ func (s *SpendingState) ProcessEvent(_ context.Context, event VTXOEvent, ExitPolicy: evt.ExitPolicy, }, &VTXOStatusUpdate{ - Outpoint: s.VTXO.Outpoint, - NewStatus: VTXOStatusUnilateralExit, + Outpoint: s.VTXO.Outpoint, + NewStatus: VTXOStatusUnilateralExit, + ManualExitOptions: evt.ManualOptions, ReleaseSpendReservation: true, }, diff --git a/waved/manual_exit_terms.go b/waved/manual_exit_terms.go new file mode 100644 index 000000000..004613f22 --- /dev/null +++ b/waved/manual_exit_terms.go @@ -0,0 +1,131 @@ +package waved + +import ( + "context" + "errors" + "strings" + + btcaddr "github.com/btcsuite/btcd/address/v2" + "github.com/btcsuite/btcd/txscript/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/lib/actormsg" + "github.com/lightninglabs/wavelength/lib/arkscript" + "github.com/lightninglabs/wavelength/txconfirm" + "github.com/lightninglabs/wavelength/vtxo" + "github.com/lightninglabs/wavelength/waverpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// ManualExitTerms are the user-selected final payout and initial fee rate. +type ManualExitTerms struct { + SweepAddress string + FeeRateSatPerVByte int64 +} + +// validateManualExitTerms validates the rate and turns a network address into +// the exact script that will be persisted with the VTXO. +func (r *RPCServer) validateManualExitTerms(terms ManualExitTerms) (string, + *actormsg.ManualExitOptions, error) { + + address := strings.TrimSpace(terms.SweepAddress) + rate := terms.FeeRateSatPerVByte + if address == "" && rate == 0 { + return "", nil, nil + } + + maxRate := r.server.unrollMaxFeeRate() + if maxRate == 0 { + maxRate = txconfirm.DefaultMaxFeeRateSatPerVByte + } + if rate < 0 || rate > maxRate { + return "", nil, status.Errorf(codes.InvalidArgument, "fee "+ + "rate must be between 1 and %d sat/vB, or 0 for "+ + "automatic", maxRate) + } + options := &actormsg.ManualExitOptions{FeeRateSatPerVByte: rate} + if address == "" { + return "", options, nil + } + if r.server.chainParams == nil { + return "", nil, status.Error( + codes.Unavailable, "wallet network not initialized", + ) + } + destination, err := btcaddr.DecodeAddress(address, r.server.chainParams) + if err != nil || !destination.IsForNet(r.server.chainParams) { + return "", nil, status.Error( + codes.InvalidArgument, + "Enter a valid Bitcoin address for this network.", + ) + } + + script, err := txscript.PayToAddrScript(destination) + if err != nil || len(script) > 34 { + return "", nil, status.Error( + codes.InvalidArgument, + "Use a standard Bitcoin address for the exit.", + ) + } + options.SweepScript = script + + return destination.EncodeAddress(), options, nil +} + +// validateManualExitTarget limits overrides to standard Bitcoin timeout jobs. +// Specialized recovery paths may require different signing and payout rules. +func validateManualExitTarget(desc *vtxo.Descriptor, + options *actormsg.ManualExitOptions) error { + + if options == nil { + return nil + } + if desc == nil { + return status.Error( + codes.NotFound, "Exit funds were not found.", + ) + } + template, err := arkscript.DecodePolicyTemplate(desc.PolicyTemplate) + if err != nil || !arkscript.IsStandardVTXOTemplate(template) || + desc.TaprootAssetRoot != nil { + return status.Error( + codes.FailedPrecondition, + "Custom exit options require a standard bitcoin VTXO.", + ) + } + + return nil +} + +// stampExitSweepAddress reads the chosen payout from the exit's durable VTXO. +func (r *RPCServer) stampExitSweepAddress(ctx context.Context, + resp *waverpc.GetUnrollStatusResponse, outpoint wire.OutPoint) error { + + if r.server.vtxoStore == nil || r.server.chainParams == nil { + return nil + } + desc, err := r.server.vtxoStore.GetVTXO(ctx, outpoint) + if errors.Is(err, vtxo.ErrVTXONotFound) { + return nil + } + if err != nil { + return status.Errorf(codes.Unavailable, "read exit payout: %v", + err) + } + if desc == nil || desc.ManualExitOptions == nil || + len(desc.ManualExitOptions.SweepScript) == 0 { + return nil + } + + _, addresses, _, err := txscript.ExtractPkScriptAddrs( + desc.ManualExitOptions.SweepScript, r.server.chainParams, + ) + if err != nil || len(addresses) != 1 { + return status.Error( + codes.Internal, "cannot decode persisted exit payout", + ) + } + resp.SweepAddress = addresses[0].EncodeAddress() + + return nil +} diff --git a/waved/rpc_exit_plan.go b/waved/rpc_exit_plan.go index e7e5986bf..a82f51a9f 100644 --- a/waved/rpc_exit_plan.go +++ b/waved/rpc_exit_plan.go @@ -6,10 +6,12 @@ import ( "errors" "fmt" "log/slog" + "slices" "github.com/btcsuite/btcd/btcutil/v2" "github.com/btcsuite/btcd/chainhash/v2" "github.com/lightninglabs/wavelength/db" + "github.com/lightninglabs/wavelength/lib/actormsg" "github.com/lightninglabs/wavelength/unroll" "github.com/lightninglabs/wavelength/vtxo" "github.com/lightninglabs/wavelength/wallet" @@ -25,8 +27,9 @@ const ( // ExitPlanRequest asks the daemon to preview unilateral-exit funding // readiness for a slice of VTXO outpoints. type ExitPlanRequest struct { - Outpoints []string - ConfTarget uint32 + Outpoints []string + ConfTarget uint32 + ManualTerms ManualExitTerms } // ExitPlanEntry describes the unroll CPFP fee-input readiness for a single @@ -71,6 +74,8 @@ type ExitPlanEntry struct { // ExitPlanResponse describes the combined unroll CPFP fee-input readiness for // every previewed outpoint plus aggregate totals. type ExitPlanResponse struct { + SweepAddress string + TotalEstimatedFeeSat *int64 Plans []ExitPlanEntry FeeRateSatPerVByte int64 CanStart bool @@ -140,10 +145,17 @@ func (r *RPCServer) GetExitPlan(ctx context.Context, req *ExitPlanRequest) ( // The fee estimate and wallet snapshot are wallet-wide, so compute // them once and reuse them for every previewed outpoint. - feeRate, err := r.estimateWalletFeeRate(ctx, req.ConfTarget) + address, options, err := r.validateManualExitTerms(req.ManualTerms) if err != nil { - return nil, status.Errorf(codes.Internal, "estimate fee: %v", - err) + return nil, err + } + feeRate := req.ManualTerms.FeeRateSatPerVByte + if feeRate == 0 { + feeRate, err = r.estimateWalletFeeRate(ctx, req.ConfTarget) + if err != nil { + return nil, status.Errorf(codes.Internal, + "estimate fee: %v", err) + } } walletSnapshot, err := r.walletExitFundingSnapshot(ctx) @@ -154,6 +166,7 @@ func (r *RPCServer) GetExitPlan(ctx context.Context, req *ExitPlanRequest) ( resp := &ExitPlanResponse{ FeeRateSatPerVByte: feeRate, + SweepAddress: address, } resp.Plans = make([]ExitPlanEntry, 0, len(req.Outpoints)) @@ -169,8 +182,12 @@ func (r *RPCServer) GetExitPlan(ctx context.Context, req *ExitPlanRequest) ( // error. It is only meaningful once at least one entry succeeds. canStart := true sawEntry := false + var totalFee int64 for _, raw := range req.Outpoints { - entry, verdict := r.exitPlanEntry(ctx, raw, feeRate, remaining) + entry, verdict := r.exitPlanEntryWithOptions( + ctx, raw, feeRate, remaining, options, + ) + totalFee += int64(verdict.TotalRecoveryCostSat) resp.Plans = append(resp.Plans, entry) if entry.Err != nil { continue @@ -196,6 +213,13 @@ func (r *RPCServer) GetExitPlan(ctx context.Context, req *ExitPlanRequest) ( } resp.CanStart = sawEntry && canStart + if sawEntry && + !slices.ContainsFunc(resp.Plans, func(e ExitPlanEntry) bool { + return e.Err != nil + }) { + + resp.TotalEstimatedFeeSat = &totalFee + } // Summarize the aggregate readiness verdict on exit. r.server.log.DebugS(ctx, "GetExitPlan computed", @@ -214,6 +238,17 @@ func (r *RPCServer) exitPlanEntry(ctx context.Context, raw string, feeRate int64, walletSnapshot unroll.ExitFundingSnapshot) ( ExitPlanEntry, unroll.ExitFeasibility) { + return r.exitPlanEntryWithOptions( + ctx, raw, feeRate, walletSnapshot, nil, + ) +} + +// exitPlanEntryWithOptions prices a target with the requested payout and rate. +func (r *RPCServer) exitPlanEntryWithOptions(ctx context.Context, raw string, + feeRate int64, walletSnapshot unroll.ExitFundingSnapshot, + options *actormsg.ManualExitOptions) (ExitPlanEntry, + unroll.ExitFeasibility) { + entry := ExitPlanEntry{Outpoint: raw} // verdict is the feasibility breakdown the caller uses to decrement the @@ -243,8 +278,13 @@ func (r *RPCServer) exitPlanEntry(ctx context.Context, raw string, } mat := r.resolveExitLineage(ctx, outpoint, desc) - plan := unroll.PlanExitFunding( - desc, mat, btcutil.Amount(feeRate), walletSnapshot, + if err := validateManualExitTarget(desc, options); err != nil { + entry.Err = err + + return entry, verdict + } + plan := unroll.PlanExitFundingWithOptions( + desc, mat, btcutil.Amount(feeRate), walletSnapshot, options, ) verdict = plan.Feasibility if verdict.RequiredWalletInputs == 0 { @@ -312,10 +352,8 @@ func (r *RPCServer) exitPlanEntry(ctx context.Context, raw string, ) } - // Only allocate a funding address when the outpoint is NOT feasible - // (there is a shortfall). When feasible, no address is needed so the - // preview must not persist one. - if !verdict.Feasible { + // Allocate an address only when a deposit can unblock this exit. + if plan.FundingShortfallSat > 0 { fundingAddress, err := r.server.exitPlanFundingAddress( ctx, outpoint.String(), true, ) diff --git a/waved/rpc_exit_plan_test.go b/waved/rpc_exit_plan_test.go index 07fb3b511..43651cf6d 100644 --- a/waved/rpc_exit_plan_test.go +++ b/waved/rpc_exit_plan_test.go @@ -17,30 +17,6 @@ import ( "google.golang.org/grpc/status" ) -// exitFundingShortfallForTest recomputes the funding shortfall from the -// exported feasibility verdict fields, mirroring the unexported -// unroll.exitFundingShortfall so the waved entry mapping can be asserted -// without a live wallet/DB. For a wallet that covers both the required -// distinct fee inputs and the CPFP balance the result is zero. -func exitFundingShortfallForTest(v unroll.ExitFeasibility) int64 { - recommended := unroll.RecommendedExitFeeInputAmount(v) - - missingInputs := 0 - if v.WalletUsableInputs < v.RequiredWalletInputs { - missingInputs = v.RequiredWalletInputs - v.WalletUsableInputs - } - inputShortfall := int64(recommended) * int64(missingInputs) - - var balanceShortfall int64 - if v.WalletConfirmedSat < v.CPFPFeeTotalSat { - balanceShortfall = int64( - v.CPFPFeeTotalSat - v.WalletConfirmedSat, - ) - } - - return max(inputShortfall, balanceShortfall) -} - func newReadyExitPlanRPCServer() *RPCServer { walletReady := make(chan struct{}) close(walletReady) @@ -193,92 +169,48 @@ func TestExitPlanBatchSharedSupplyDecrements(t *testing.T) { require.Equal(t, unroll.ExitWalletTooFewInputs, second.Reason) } -// TestExitPlanEntrySurfacesStructuralInfeasibility locks the #894 fix: when a -// VTXO fails the dust or uneconomical gate against a well-funded wallet, the -// entry must report can_start=false with a ZERO funding shortfall (no amount -// of wallet funding fixes it) AND carry the structural reason on -// InfeasibilityReason, rather than leaving the caller with a silent -// can_start=false and an empty error. It mirrors the exact verdict->entry -// mapping exitPlanEntry performs. +// TestExitPlanEntrySurfacesStructuralInfeasibility drives the RPC's real +// per-VTXO planner with an empty fee wallet. Neither structural block should +// allocate an address or ask the caller to fund the wallet. func TestExitPlanEntrySurfacesStructuralInfeasibility(t *testing.T) { t.Parallel() - // A well-funded wallet so the block can never be a funding gap: any - // infeasibility must be structural (dust or uneconomical). - const ( - feeRate = btcutil.Amount(50) - walletConfirmed = btcutil.Amount(10_000_000) - walletInputs = 10 - ) - tests := []struct { - name string - in unroll.ExitFeasibilityInput - wantReason unroll.ExitInfeasibilityReason + amount btcutil.Amount + reason unroll.ExitInfeasibilityReason }{ { - // A 1-sat VTXO: after any sweep fee the swept output is - // far below dust, so the sweep can never relay. - name: "sub-dust vtxo", - in: unroll.ExitFeasibilityInput{ - NumRecoveryTxs: 1, - NumAncestryPaths: 1, - VTXOAmountSat: 1, - FeeRateSatPerVByte: feeRate, - WalletConfirmedSat: walletConfirmed, - WalletUsableInputs: walletInputs, - }, - wantReason: unroll.ExitSweepBelowDust, + 1_200, + unroll.ExitSweepBelowDust, }, { - // A deep lineage on a small (but above-dust-net) VTXO - // at a high fee rate: CPFP fees dwarf the coin's value. - name: "uneconomical vtxo", - in: unroll.ExitFeasibilityInput{ - NumRecoveryTxs: 50, - NumAncestryPaths: 1, - VTXOAmountSat: 20_000, - FeeRateSatPerVByte: feeRate, - WalletConfirmedSat: walletConfirmed, - WalletUsableInputs: walletInputs, - }, - wantReason: unroll.ExitUneconomical, + 2_000, + unroll.ExitUneconomical, }, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + t.Run(tc.reason.String(), func(t *testing.T) { t.Parallel() - verdict := unroll.AssessExitFeasibility(tc.in) - - // The well-funded wallet covers both the required - // distinct fee inputs and the CPFP balance, so the - // funding shortfall is zero: the block is purely - // structural (dust/uneconomical), not a funding gap. - require.GreaterOrEqual( - t, verdict.WalletUsableInputs, - verdict.RequiredWalletInputs, - ) - require.GreaterOrEqual( - t, int64(verdict.WalletConfirmedSat), - int64(verdict.CPFPFeeTotalSat), - ) - shortfall := exitFundingShortfallForTest(verdict) - - // Mirror the exact verdict->entry mapping exitPlanEntry - // performs. - entry := ExitPlanEntry{ - CanStart: verdict.Feasible, - InfeasibilityReason: verdict.Reason, - FundingShortfallSat: shortfall, + rpc, store := newLeaveAdmissionServer(t) + desc := newRefreshEstimateVTXO(t, 0x60, tc.amount, 900) + desc.Ancestry = []vtxo.Ancestry{ + recoveryTestFragment(desc.CommitmentTxID, 0), } + require.NoError(t, store.SaveVTXO(t.Context(), desc)) + entry, verdict := rpc.exitPlanEntry( + t.Context(), desc.Outpoint.String(), 6, + unroll.ExitFundingSnapshot{}, + ) + require.NoError(t, entry.Err) require.False(t, entry.CanStart) + require.Equal(t, tc.reason, entry.InfeasibilityReason) + require.Positive(t, verdict.TotalRecoveryCostSat) require.Zero(t, entry.FundingShortfallSat) - require.Equal( - t, tc.wantReason, entry.InfeasibilityReason, - ) + require.Zero(t, entry.RecommendedUTXOAmountSat) + require.Zero(t, entry.RecommendedTotalFundingSat) + require.Empty(t, entry.FundingAddress) }) } } @@ -325,7 +257,7 @@ func TestPreviewUnilateralExitCommittedTarget(t *testing.T) { t, store, 0x61, vtxo.VTXOStatusPendingForfeit, ) var entry WalletExitPreviewEntry - entry.setFundingEligibility(desc, nil, 1) + entry.setFundingEligibility(desc, nil, 1, nil) require.Empty(t, entry.AdmissionError) require.ErrorIs(t, entry.RoundCommitment, vtxo.ErrForfeitInFlight) } @@ -486,6 +418,44 @@ func TestExitPlanRoundCommitmentScope(t *testing.T) { } } +// TestManualExitTermsRespectNetworkAndLimits tests the terms used by both +// preview and admission before either can act on a VTXO. +func TestManualExitTermsRespectNetworkAndLimits(t *testing.T) { + t.Parallel() + + rpc := newReadyExitPlanRPCServer() + regtest, err := btcaddr.NewAddressWitnessPubKeyHash( + make([]byte, 20), &chaincfg.RegressionNetParams, + ) + require.NoError(t, err) + mainnet, err := btcaddr.NewAddressWitnessPubKeyHash( + make([]byte, 20), &chaincfg.MainNetParams, + ) + require.NoError(t, err) + address, options, err := rpc.validateManualExitTerms(ManualExitTerms{ + SweepAddress: regtest.EncodeAddress(), FeeRateSatPerVByte: 7, + }) + require.NoError(t, err) + require.Equal(t, regtest.EncodeAddress(), address) + require.NotEmpty(t, options.SweepScript) + require.EqualValues(t, 7, options.FeeRateSatPerVByte) + + for _, terms := range []ManualExitTerms{ + { + SweepAddress: mainnet.EncodeAddress(), + }, + { + FeeRateSatPerVByte: -1, + }, + { + FeeRateSatPerVByte: 101, + }, + } { + _, _, err := rpc.validateManualExitTerms(terms) + require.Equal(t, codes.InvalidArgument, status.Code(err)) + } +} + // TestPreviewUnilateralExitUnknownTargets retains refused entries in request // order and avoids consulting the wallet when none can contribute a proof. func TestPreviewUnilateralExitUnknownTargets(t *testing.T) { @@ -504,12 +474,22 @@ func TestPreviewUnilateralExitUnknownTargets(t *testing.T) { first, second := wire.OutPoint{Index: 7}, wire.OutPoint{Index: 8} outpoints := []string{first.String(), second.String()} + destination, err := btcaddr.NewAddressWitnessPubKeyHash( + make([]byte, 20), &chaincfg.RegressionNetParams, + ) + require.NoError(t, err) + terms := ManualExitTerms{ + SweepAddress: destination.EncodeAddress(), + FeeRateSatPerVByte: 7, + } preview, err := r.PreviewUnilateralExit( t.Context(), &ExitPlanRequest{ - Outpoints: outpoints, + Outpoints: outpoints, ManualTerms: terms, }, ) require.NoError(t, err) + require.Equal(t, terms.SweepAddress, preview.SweepAddress) + require.Equal(t, terms.FeeRateSatPerVByte, preview.FeeRate) require.Len(t, preview.Entries, len(outpoints)) for i, entry := range preview.Entries { require.Equal(t, outpoints[i], entry.Outpoint) diff --git a/waved/rpc_server.go b/waved/rpc_server.go index 2a9e1a0c4..2d452fd40 100644 --- a/waved/rpc_server.go +++ b/waved/rpc_server.go @@ -5254,6 +5254,14 @@ func (r *RPCServer) resolveOutputPkScript(ctx context.Context, func (r *RPCServer) Unroll(ctx context.Context, req *waverpc.UnrollRequest) ( *waverpc.UnrollResponse, error) { + return r.UnrollWithOptions(ctx, req.GetOutpoint(), ManualExitTerms{}) +} + +// UnrollWithOptions starts a unilateral exit without discarding its reviewed +// payout or initial fee rate. The VTXO actor persists both with its transition. +func (r *RPCServer) UnrollWithOptions(ctx context.Context, target string, + terms ManualExitTerms) (*waverpc.UnrollResponse, error) { + if err := r.requireWalletReady(); err != nil { return nil, err } @@ -5263,11 +5271,15 @@ func (r *RPCServer) Unroll(ctx context.Context, req *waverpc.UnrollRequest) ( "not initialized") } - outpoint, err := parseOutpointString(req.Outpoint) + outpoint, err := parseOutpointString(target) if err != nil { return nil, status.Errorf(codes.InvalidArgument, "invalid "+ "outpoint: %v", err) } + _, options, err := r.validateManualExitTerms(terms) + if err != nil { + return nil, err + } // Detach admission from the RPC stream: a CLI/RPC disconnect must // not cancel the unilateral-exit handoff once the user has asked @@ -5323,11 +5335,27 @@ func (r *RPCServer) Unroll(ctx context.Context, req *waverpc.UnrollRequest) ( // that the wallet cannot fund (insufficient balance or too few // distinct CPFP fee inputs). Failing closed here keeps the VTXO out // of an exit state the user can't easily back out of. - if err := r.preflightUnrollFeasibility( - admissionCtx, desc, - ); err != nil { + if err := validateManualExitTarget(desc, options); err != nil { return nil, err } + if options == nil { + if err := r.preflightUnrollFeasibility( + admissionCtx, desc, + ); err != nil { + return nil, err + } + } else { + verdict, err := r.assessUnrollFeasibilityWithOptions( + admissionCtx, desc, options, + ) + if err != nil { + return nil, status.Errorf(codes.Internal, "preflight "+ + "exit: %v", err) + } + if !verdict.Feasible { + return nil, unrollInfeasibleError(verdict) + } + } // Route through the VTXO manager which tells the VTXO actor to // transition to UnilateralExitState. The actor's outbox handler @@ -5343,7 +5371,8 @@ func (r *RPCServer) Unroll(ctx context.Context, req *waverpc.UnrollRequest) ( // hand-typed unroll then records as the expiry safety // net, so the job's persisted provenance names a // trigger that never fired. - Trigger: actormsg.UnrollTriggerManual, + Trigger: actormsg.UnrollTriggerManual, + ManualOptions: options, }, ).Await(admissionCtx).Unpack() if askErr != nil { @@ -5423,6 +5452,14 @@ func (r *RPCServer) preflightUnrollFeasibility(ctx context.Context, func (r *RPCServer) assessUnrollFeasibility(ctx context.Context, desc *vtxo.Descriptor) (unroll.ExitFeasibility, error) { + return r.assessUnrollFeasibilityWithOptions(ctx, desc, nil) +} + +// assessUnrollFeasibilityWithOptions checks the same terms the planner quotes. +func (r *RPCServer) assessUnrollFeasibilityWithOptions(ctx context.Context, + desc *vtxo.Descriptor, options *actormsg.ManualExitOptions) ( + unroll.ExitFeasibility, error) { + walletSnapshot, err := r.walletExitFundingSnapshot(ctx) if err != nil { return unroll.ExitFeasibility{}, fmt.Errorf("wallet "+ @@ -5430,8 +5467,15 @@ func (r *RPCServer) assessUnrollFeasibility(ctx context.Context, } mat := r.resolveExitLineage(ctx, desc.Outpoint, desc) - plan := unroll.PlanExitFunding( - desc, mat, r.estimateUnrollFeeRate(ctx), walletSnapshot, + var rate btcutil.Amount + if options != nil { + rate = btcutil.Amount(options.FeeRateSatPerVByte) + } + if rate == 0 { + rate = r.estimateUnrollFeeRate(ctx) + } + plan := unroll.PlanExitFundingWithOptions( + desc, mat, rate, walletSnapshot, options, ) return plan.Feasibility, nil @@ -5618,6 +5662,13 @@ func (r *RPCServer) GetUnrollStatus(ctx context.Context, } if found { r.stampConfirmedExitCost(ctx, resp, outpoint) + if req.Detailed { + if err := r.stampExitSweepAddress( + ctx, resp, outpoint, + ); err != nil { + return nil, err + } + } return resp, nil } @@ -5666,6 +5717,11 @@ func (r *RPCServer) GetUnrollStatus(ctx context.Context, // persisted descriptor and a human phase line, which keeps a completed // or failed exit inspectable via this same endpoint. if req.Detailed { + if err := r.stampExitSweepAddress( + ctx, resp, outpoint, + ); err != nil { + return nil, err + } resp.PhaseDetail = unrollPhaseDetail(resp.Status, nil) r.enrichExitFees(ctx, resp, outpoint, fn.None[int64](), nil) } @@ -5939,9 +5995,15 @@ func (r *RPCServer) enrichExitFees(ctx context.Context, return } - feeRate, err := r.estimateWalletFeeRate(ctx, 0) - if err != nil { - return + var feeRate int64 + if desc.ManualExitOptions != nil { + feeRate = desc.ManualExitOptions.FeeRateSatPerVByte + } + if feeRate == 0 { + feeRate, err = r.estimateWalletFeeRate(ctx, 0) + if err != nil { + return + } } // Resolve the lineage material so the CPFP estimate sizes the OOR diff --git a/waved/rpc_wallet_exit_preview.go b/waved/rpc_wallet_exit_preview.go index ef423cba3..0b20fe734 100644 --- a/waved/rpc_wallet_exit_preview.go +++ b/waved/rpc_wallet_exit_preview.go @@ -7,6 +7,7 @@ import ( "github.com/btcsuite/btcd/btcutil/v2" "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/lib/actormsg" "github.com/lightninglabs/wavelength/unroll" "github.com/lightninglabs/wavelength/vtxo" "github.com/lightninglabs/wavelength/wallet" @@ -29,6 +30,9 @@ type WalletExitPreview struct { // byte. FeeRate int64 + // SweepAddress is the validated custom destination, if requested. + SweepAddress string + // Quote prices the union of the selected targets' proof transactions. Quote unroll.WalletExitQuote } @@ -53,6 +57,9 @@ type WalletExitPreviewEntry struct { // dust. AdmissionError string + // InfeasibilityReason identifies an economic refusal for display. + InfeasibilityReason unroll.ExitInfeasibilityReason + // RoundCommitment warns that a cooperative round holds this VTXO. // Manual recovery remains available. RoundCommitment error @@ -77,10 +84,17 @@ func (r *RPCServer) PreviewUnilateralExit(ctx context.Context, codes.Unavailable, "VTXO store not initialized", ) } - rate, err := r.estimateWalletFeeRate(ctx, req.ConfTarget) + address, options, err := r.validateManualExitTerms(req.ManualTerms) if err != nil { return nil, err } + rate := req.ManualTerms.FeeRateSatPerVByte + if rate == 0 { + rate, err = r.estimateWalletFeeRate(ctx, req.ConfTarget) + if err != nil { + return nil, err + } + } resolver := unroll.DescriptorLineageResolver{ VTXOStore: r.server.vtxoStore, } @@ -90,7 +104,9 @@ func (r *RPCServer) PreviewUnilateralExit(ctx context.Context, // Preserve the selection order in the RPC even though the funding // simulation orders targets by their batch expiry. - result := &WalletExitPreview{FeeRate: rate} + result := &WalletExitPreview{ + FeeRate: rate, SweepAddress: address, + } seen := make(map[wire.OutPoint]bool) var targets []unroll.WalletExitTarget for _, raw := range req.Outpoints { @@ -139,6 +155,11 @@ func (r *RPCServer) PreviewUnilateralExit(ctx context.Context, continue } + if err := validateManualExitTarget(desc, options); err != nil { + entry.AdmissionError = status.Convert(err).Message() + + continue + } mat, err := resolver.ResolveLineage(ctx, op) if err != nil { if ctx.Err() != nil { @@ -157,7 +178,9 @@ func (r *RPCServer) PreviewUnilateralExit(ctx context.Context, continue } - entry.setFundingEligibility(desc, mat, btcutil.Amount(rate)) + entry.setFundingEligibility( + desc, mat, btcutil.Amount(rate), options, + ) if entry.AdmissionError != "" { continue } @@ -200,15 +223,17 @@ func (r *RPCServer) PreviewUnilateralExit(ctx context.Context, // setFundingEligibility keeps a live cooperative round visible to the caller // while preserving the manual recovery path when the operator is unavailable. func (e *WalletExitPreviewEntry) setFundingEligibility(desc *vtxo.Descriptor, - mat *unroll.LineageMaterial, rate btcutil.Amount) { + mat *unroll.LineageMaterial, rate btcutil.Amount, + options *actormsg.ManualExitOptions) { e.RoundCommitment = exitPlanRoundCommitment(desc) - verdict := unroll.PlanExitFunding( - desc, mat, rate, unroll.ExitFundingSnapshot{}, + verdict := unroll.PlanExitFundingWithOptions( + desc, mat, rate, unroll.ExitFundingSnapshot{}, options, ).Feasibility if verdict.Reason == unroll.ExitSweepBelowDust || verdict.Reason == unroll.ExitUneconomical { + e.InfeasibilityReason = verdict.Reason e.AdmissionError = unrollInfeasibleError(verdict).Error() } } diff --git a/waverpc/daemon.pb.go b/waverpc/daemon.pb.go index b5d132dbe..f3825dc95 100644 --- a/waverpc/daemon.pb.go +++ b/waverpc/daemon.pb.go @@ -11185,7 +11185,9 @@ type GetUnrollStatusResponse struct { // estimates in fees, this is the settled figure, so it is set (on both // plain and detailed queries) only once the job is COMPLETED, and reads // zero for exits predating exit-cost accounting. - ExitCostSat int64 `protobuf:"varint,11,opt,name=exit_cost_sat,json=exitCostSat,proto3" json:"exit_cost_sat,omitempty"` + ExitCostSat int64 `protobuf:"varint,11,opt,name=exit_cost_sat,json=exitCostSat,proto3" json:"exit_cost_sat,omitempty"` + // sweep_address is the persisted custom payout, empty for wallet funding. + SweepAddress string `protobuf:"bytes,12,opt,name=sweep_address,json=sweepAddress,proto3" json:"sweep_address,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -11297,6 +11299,13 @@ func (x *GetUnrollStatusResponse) GetExitCostSat() int64 { return 0 } +func (x *GetUnrollStatusResponse) GetSweepAddress() string { + if x != nil { + return x.SweepAddress + } + return "" +} + type ArmVHTLCRecoveryRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // request_id is the caller-owned idempotency key. Retrying the same @@ -13668,7 +13677,7 @@ const file_daemon_proto_rawDesc = "" + "\x11net_recovered_sat\x18\x05 \x01(\x03R\x0fnetRecoveredSat\x12+\n" + "\x12fee_rate_sat_vbyte\x18\x06 \x01(\x03R\x0ffeeRateSatVbyte\x12(\n" + "\x10sweep_fee_actual\x18\a \x01(\bR\x0esweepFeeActual\x12'\n" + - "\x10spent_so_far_sat\x18\b \x01(\x03R\rspentSoFarSat\"\xce\x03\n" + + "\x10spent_so_far_sat\x18\b \x01(\x03R\rspentSoFarSat\"\xf3\x03\n" + "\x17GetUnrollStatusResponse\x12\x14\n" + "\x05found\x18\x01 \x01(\bR\x05found\x120\n" + "\x06status\x18\x02 \x01(\x0e2\x18.waverpc.UnrollJobStatusR\x06status\x12\x1d\n" + @@ -13683,7 +13692,8 @@ const file_daemon_proto_rawDesc = "" + "\x1abest_case_blocks_remaining\x18\t \x01(\x05R\x17bestCaseBlocksRemaining\x12%\n" + "\x0ecurrent_height\x18\n" + " \x01(\x05R\rcurrentHeight\x12\"\n" + - "\rexit_cost_sat\x18\v \x01(\x03R\vexitCostSat\"\xd4\x06\n" + + "\rexit_cost_sat\x18\v \x01(\x03R\vexitCostSat\x12#\n" + + "\rsweep_address\x18\f \x01(\tR\fsweepAddress\"\xd4\x06\n" + "\x17ArmVHTLCRecoveryRequest\x12\x1d\n" + "\n" + "request_id\x18\x01 \x01(\tR\trequestId\x12\x17\n" + diff --git a/waverpc/daemon.proto b/waverpc/daemon.proto index 2921fedab..b8320a2e8 100644 --- a/waverpc/daemon.proto +++ b/waverpc/daemon.proto @@ -3148,6 +3148,9 @@ message GetUnrollStatusResponse { // plain and detailed queries) only once the job is COMPLETED, and reads // zero for exits predating exit-cost accounting. int64 exit_cost_sat = 11; + + // sweep_address is the persisted custom payout, empty for wallet funding. + string sweep_address = 12; } // VHTLCRecoveryDirection records which side owns a recovery job.