-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathrpc_exit_plan_test.go
More file actions
470 lines (409 loc) · 13.9 KB
/
Copy pathrpc_exit_plan_test.go
File metadata and controls
470 lines (409 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
package waved
import (
"testing"
btcaddr "github.com/btcsuite/btcd/address/v2"
"github.com/btcsuite/btcd/btcutil/v2"
"github.com/btcsuite/btcd/chaincfg/v2"
"github.com/lightninglabs/wavelength/db"
"github.com/lightninglabs/wavelength/unroll"
"github.com/lightninglabs/wavelength/vtxo"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"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)
return &RPCServer{
server: &Server{
walletReady: walletReady,
chainParams: &chaincfg.RegressionNetParams,
chainBackend: nil,
},
}
}
func TestGetExitPlanRejectsEmptyOutpoints(t *testing.T) {
t.Parallel()
r := newReadyExitPlanRPCServer()
_, err := r.GetExitPlan(t.Context(), &ExitPlanRequest{})
require.Error(t, err)
require.Equal(t, codes.InvalidArgument, status.Code(err))
}
func TestGetExitPlanRejectsUninitializedStore(t *testing.T) {
t.Parallel()
// The VTXO store check is request-wide: a nil store fails the whole
// call rather than producing per-outpoint errors.
r := newReadyExitPlanRPCServer()
_, err := r.GetExitPlan(t.Context(), &ExitPlanRequest{
Outpoints: []string{"not-an-outpoint"},
})
require.Error(t, err)
require.Equal(t, codes.Unavailable, status.Code(err))
}
func TestSweepWalletRejectsMissingDestination(t *testing.T) {
t.Parallel()
r := newReadyExitPlanRPCServer()
_, err := r.SweepWallet(t.Context(), &SweepWalletRequest{})
require.Error(t, err)
require.Equal(t, codes.InvalidArgument, status.Code(err))
}
func TestSweepWalletRejectsNegativeFeeRate(t *testing.T) {
t.Parallel()
addr, err := btcaddr.NewAddressWitnessPubKeyHash(
make([]byte, 20), &chaincfg.RegressionNetParams,
)
require.NoError(t, err)
r := newReadyExitPlanRPCServer()
_, err = r.SweepWallet(t.Context(), &SweepWalletRequest{
DestinationAddress: addr.String(),
FeeRateSatPerVByte: -1,
})
require.Error(t, err)
require.Equal(t, codes.InvalidArgument, status.Code(err))
}
// Note: the preview math, dust boundary, fee-cap, and network-validation
// coverage for the wallet sweep moved into the wallet package alongside the
// handler that now owns that logic (wallet/wallet_sweep_actor_test.go). The
// remaining tests here exercise the RPC shim's request-surface validation.
// TestClaimExitFunding verifies that a feasible exit's reserved inputs and
// fee budget are subtracted from the running wallet snapshot, clamping at
// zero.
func TestClaimExitFunding(t *testing.T) {
t.Parallel()
t.Run("decrements inputs and balance", func(t *testing.T) {
t.Parallel()
got := claimExitFunding(
unroll.ExitFundingSnapshot{
WalletConfirmedSat: 30_000,
WalletUsableInputs: 3,
},
unroll.ExitFeasibility{
RequiredWalletInputs: 1,
CPFPFeeTotalSat: 6_000,
},
)
require.Equal(t, 2, got.WalletUsableInputs)
require.Equal(
t, btcutil.Amount(24_000), got.WalletConfirmedSat,
)
})
t.Run("clamps at zero", func(t *testing.T) {
t.Parallel()
got := claimExitFunding(
unroll.ExitFundingSnapshot{
WalletConfirmedSat: 1_000,
WalletUsableInputs: 1,
},
unroll.ExitFeasibility{
RequiredWalletInputs: 2,
CPFPFeeTotalSat: 5_000,
},
)
require.Equal(t, 0, got.WalletUsableInputs)
require.Equal(t, btcutil.Amount(0), got.WalletConfirmedSat)
})
}
// TestExitPlanBatchSharedSupplyDecrements locks the multi-outpoint accounting
// fix: two VTXOs that each need one fee input, against a wallet holding
// exactly one usable input, must NOT both report ready. The first exit claims
// the only input, so the second -- assessed against the decremented wallet --
// is left short. Without the running allocation both would independently see
// the full wallet and falsely report can_start with zero shortfall.
func TestExitPlanBatchSharedSupplyDecrements(t *testing.T) {
t.Parallel()
const feeRate = btcutil.Amount(10)
snapshot := unroll.ExitFundingSnapshot{
WalletConfirmedSat: 1_000_000,
WalletUsableInputs: 1,
}
feasInput := func(
s unroll.ExitFundingSnapshot) unroll.ExitFeasibilityInput {
return unroll.ExitFeasibilityInput{
NumRecoveryTxs: 1,
NumAncestryPaths: 1,
VTXOAmountSat: 1_000_000,
FeeRateSatPerVByte: feeRate,
WalletConfirmedSat: s.WalletConfirmedSat,
WalletUsableInputs: s.WalletUsableInputs,
}
}
// First exit sees the single usable input and is feasible.
first := unroll.AssessExitFeasibility(feasInput(snapshot))
require.True(t, first.Feasible)
require.Equal(t, 1, first.RequiredWalletInputs)
// It claims that input, leaving the running wallet with none.
remaining := claimExitFunding(snapshot, first)
require.Equal(t, 0, remaining.WalletUsableInputs)
// The second exit, assessed against the shrunken wallet, cannot fund a
// distinct CPFP input and is infeasible.
second := unroll.AssessExitFeasibility(feasInput(remaining))
require.False(t, second.Feasible)
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.
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
}{
{
// 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,
},
{
// 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,
},
}
for _, tc := range tests {
t.Run(tc.name, 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,
}
require.False(t, entry.CanStart)
require.Zero(t, entry.FundingShortfallSat)
require.Equal(
t, tc.wantReason, entry.InfeasibilityReason,
)
})
}
}
// exitPlanCommittedFixture persists a VTXO in the given lifecycle status with
// a one-fragment ancestry, which is the minimum that makes the funding
// estimate price the exit at all. Without it recoveryEstimate returns zero
// required inputs and exitPlanEntry short-circuits on "no unilateral-exit
// ancestry" before the commitment advisory is ever reached.
func exitPlanCommittedFixture(t *testing.T, store *db.VTXOPersistenceStore,
hashByte byte, vtxoStatus vtxo.VTXOStatus) *vtxo.Descriptor {
t.Helper()
// A single-fragment ancestry: enough for the estimate to require
// real CPFP funding, shallow enough to stay economical against a
// 50k VTXO. The tree path must be non-nil because the ancestry row
// stores it NOT NULL.
desc := newRefreshEstimateVTXO(t, hashByte, 50_000, 900)
desc.Ancestry = []vtxo.Ancestry{
recoveryTestFragment(desc.CommitmentTxID, 0),
}
require.NoError(t, store.SaveVTXO(t.Context(), desc))
// SaveVTXO inserts at a fixed status and ignores desc.Status, so the
// lifecycle state under test has to be applied as an update.
desc.Status = vtxoStatus
require.NoError(
t,
store.UpdateVTXOStatus(
t.Context(), desc.Outpoint, vtxoStatus,
),
)
return desc
}
// TestExitPlanEntryWarnsCommittedVTXO asserts the exit preview reports a VTXO
// committed to a cooperative round as an advisory alongside a full pricing,
// rather than failing the entry.
//
// Previewing it as unconditionally ready is what escalated wavelength#577
// into a near miss: a user whose cooperative leave was already in flight was
// told can_start=true, shortfall=0, and reached for --force-unroll-ack. But
// refusing the entry outright is wrong in the other direction, because Unroll
// has no commitment check and performs that exit — and it is the only lever
// that recovers the coin when the operator is unreachable and the commitment
// never confirms. An error would tell exactly that user their recovery is
// impossible while withholding the funding figures it needs.
func TestExitPlanEntryWarnsCommittedVTXO(t *testing.T) {
t.Parallel()
for _, committed := range []vtxo.VTXOStatus{
vtxo.VTXOStatusPendingForfeit, vtxo.VTXOStatusForfeiting,
} {
t.Run(committed.String(), func(t *testing.T) {
t.Parallel()
r, store := newLeaveAdmissionServer(t)
desc := exitPlanCommittedFixture(
t, store, 0x61, committed,
)
// A wallet that comfortably covers the CPFP funding,
// so the only thing lowering the verdict is the round
// commitment itself.
entry, verdict := r.exitPlanEntry(
t.Context(), desc.Outpoint.String(), 1,
unroll.ExitFundingSnapshot{
WalletConfirmedSat: 1_000_000,
WalletUsableInputs: 4,
},
)
// The entry is answered, not failed: Err means the
// preview could not price the coin at all.
require.NoError(t, entry.Err)
// The warning survives, and names what holds the coin.
require.Error(t, entry.RoundCommitment)
require.ErrorIs(
t, entry.RoundCommitment,
vtxo.ErrForfeitInFlight,
)
require.Contains(
t, entry.RoundCommitment.Error(),
desc.Outpoint.String(),
)
// The verdict is lowered so no caller reads the coin
// as ready, and the reason says why.
require.False(t, entry.CanStart)
require.Equal(
t, unroll.ExitRoundCommitted,
entry.InfeasibilityReason,
)
// The funding figures the recovery path needs are
// still there. The underlying funding assessment is
// untouched, which is what keeps the preview
// consistent with what Unroll will do.
require.True(t, verdict.Feasible)
require.Positive(t, entry.RequiredFeeUTXOCount)
require.Positive(t, entry.RecommendedTotalFundingSat)
require.Positive(t, entry.RecommendedUTXOAmountSat)
})
}
}
// TestExitPlanEntryUncommittedKeepsFeasibleVerdict is the control for the
// test above: the same fixture in a live state must still preview as ready,
// so the lowered verdict is attributable to the commitment and nothing else.
func TestExitPlanEntryUncommittedKeepsFeasibleVerdict(t *testing.T) {
t.Parallel()
r, store := newLeaveAdmissionServer(t)
desc := exitPlanCommittedFixture(
t, store, 0x62, vtxo.VTXOStatusLive,
)
entry, _ := r.exitPlanEntry(
t.Context(), desc.Outpoint.String(), 1,
unroll.ExitFundingSnapshot{
WalletConfirmedSat: 1_000_000,
WalletUsableInputs: 4,
},
)
require.NoError(t, entry.Err)
require.NoError(t, entry.RoundCommitment)
require.True(t, entry.CanStart)
require.Equal(t, unroll.ExitFeasible, entry.InfeasibilityReason)
}
// TestExitPlanRoundCommitmentScope asserts the preview only blocks on a round
// commitment. A VTXO already exiting must still get a real preview, since its
// exit job status is the answer the caller wants.
func TestExitPlanRoundCommitmentScope(t *testing.T) {
t.Parallel()
tests := []struct {
status vtxo.VTXOStatus
blocked bool
}{
{
vtxo.VTXOStatusLive,
false,
},
{
vtxo.VTXOStatusExpired,
false,
},
{
vtxo.VTXOStatusPendingForfeit,
true,
},
{
vtxo.VTXOStatusForfeiting,
true,
},
{
vtxo.VTXOStatusUnilateralExit,
false,
},
{
vtxo.VTXOStatusSpending,
false,
},
{
vtxo.VTXOStatusForfeited,
false,
},
}
for _, test := range tests {
t.Run(test.status.String(), func(t *testing.T) {
t.Parallel()
err := exitPlanRoundCommitment(&vtxo.Descriptor{
Status: test.status,
})
if !test.blocked {
require.NoError(t, err)
return
}
require.ErrorIs(t, err, vtxo.ErrForfeitInFlight)
})
}
}