-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathactor_test.go
More file actions
571 lines (476 loc) · 15.5 KB
/
Copy pathactor_test.go
File metadata and controls
571 lines (476 loc) · 15.5 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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
package fraud
import (
"context"
"fmt"
"sync"
"testing"
"time"
"github.com/btcsuite/btcd/txscript/v2"
"github.com/btcsuite/btcd/wire/v2"
"github.com/btcsuite/btclog/v2"
"github.com/lightninglabs/wavelength/baselib/actor"
"github.com/lightninglabs/wavelength/chainsource"
"github.com/lightninglabs/wavelength/lib/actormsg"
"github.com/lightninglabs/wavelength/vtxo"
fn "github.com/lightningnetwork/lnd/fn/v2"
"github.com/stretchr/testify/require"
)
const testTimeout = time.Second
// spendRef aliases the chainsource spend notification target.
type spendRef = actor.TellOnlyRef[chainsource.SpendEvent]
type fakeChainSourceRef struct {
mu sync.Mutex
spendReqs []*chainsource.RegisterSpendRequest
spendRefs map[wire.OutPoint]spendRef
unregisters []wire.OutPoint
}
// ID returns the fake actor ID.
func (f *fakeChainSourceRef) ID() string {
return "fake-chain"
}
// Tell is unused by these tests.
func (f *fakeChainSourceRef) Tell(context.Context,
chainsource.ChainSourceMsg) error {
return nil
}
// TryTell delegates to Tell, which is all this double needs: no test
// drives the non-blocking path through it.
func (f *fakeChainSourceRef) TryTell(ctx context.Context,
msg chainsource.ChainSourceMsg) error {
return f.Tell(ctx, msg)
}
// Ask records spend registration requests.
func (f *fakeChainSourceRef) Ask(_ context.Context,
msg chainsource.ChainSourceMsg,
) actor.Future[chainsource.ChainSourceResp] {
promise := actor.NewPromise[chainsource.ChainSourceResp]()
switch msg := msg.(type) {
case *chainsource.RegisterSpendRequest:
if msg.Outpoint == nil {
promise.Complete(
fn.Err[chainsource.ChainSourceResp](
fmt.Errorf("outpoint required"),
),
)
return promise.Future()
}
f.mu.Lock()
if f.spendRefs == nil {
f.spendRefs = make(map[wire.OutPoint]spendRef)
}
f.spendReqs = append(f.spendReqs, msg)
f.spendRefs[*msg.Outpoint] = msg.NotifyActor.UnwrapOr(nil)
f.mu.Unlock()
promise.Complete(
fn.Ok[chainsource.ChainSourceResp](
&chainsource.RegisterSpendResponse{},
),
)
case *chainsource.UnregisterSpendRequest:
if msg.Outpoint != nil {
f.mu.Lock()
f.unregisters = append(f.unregisters, *msg.Outpoint)
f.mu.Unlock()
}
promise.Complete(
fn.Ok[chainsource.ChainSourceResp](
&chainsource.UnregisterSpendResponse{},
),
)
default:
promise.Complete(
fn.Err[chainsource.ChainSourceResp](
fmt.Errorf("unexpected chainsource msg %T",
msg),
),
)
}
return promise.Future()
}
func (f *fakeChainSourceRef) spendWatchCount() int {
f.mu.Lock()
defer f.mu.Unlock()
return len(f.spendReqs)
}
func (f *fakeChainSourceRef) emitSpend(t *testing.T, outpoint wire.OutPoint) {
t.Helper()
f.mu.Lock()
ref := f.spendRefs[outpoint]
f.mu.Unlock()
require.NotNil(t, ref)
require.NoError(
t,
ref.Tell(
t.Context(), chainsource.SpendEvent{
Outpoint: outpoint,
SpendingTxid: testInput(99).Hash,
SpendingHeight: 33,
},
),
)
}
// fakeManagerRef stands in for the VTXO manager: it records the
// ForceUnrollRequests the fraud watcher sends and replies with a
// ForceUnrollResponse. A non-nil err makes the Ask fail so the fanout
// best-effort behavior can be exercised.
type fakeManagerRef struct {
mu sync.Mutex
requests []*actormsg.ForceUnrollRequest
err error
}
// ID returns the fake actor ID.
func (f *fakeManagerRef) ID() string {
return "fake-vtxo-manager"
}
// Tell is unused by these tests.
func (f *fakeManagerRef) Tell(context.Context, vtxo.ManagerMsg) error {
return nil
}
// TryTell delegates to Tell, which is all this double needs: no test
// drives the non-blocking path through it.
func (f *fakeManagerRef) TryTell(ctx context.Context,
msg vtxo.ManagerMsg) error {
return f.Tell(ctx, msg)
}
// Ask records force-unroll requests.
func (f *fakeManagerRef) Ask(_ context.Context,
msg vtxo.ManagerMsg) actor.Future[vtxo.ManagerResp] {
promise := actor.NewPromise[vtxo.ManagerResp]()
req, ok := msg.(*actormsg.ForceUnrollRequest)
if !ok {
promise.Complete(
fn.Err[vtxo.ManagerResp](
fmt.Errorf("unexpected manager msg %T", msg),
),
)
return promise.Future()
}
f.mu.Lock()
f.requests = append(f.requests, req)
f.mu.Unlock()
if f.err != nil {
promise.Complete(fn.Err[vtxo.ManagerResp](f.err))
return promise.Future()
}
promise.Complete(
fn.Ok[vtxo.ManagerResp](
&actormsg.ForceUnrollResponse{
Accepted: true,
},
),
)
return promise.Future()
}
func (f *fakeManagerRef) lastRequest(
t *testing.T) *actormsg.ForceUnrollRequest {
t.Helper()
f.mu.Lock()
defer f.mu.Unlock()
require.NotEmpty(t, f.requests)
return f.requests[len(f.requests)-1]
}
// requestCount returns the number of recorded force-unroll requests.
func (f *fakeManagerRef) requestCount() int {
f.mu.Lock()
defer f.mu.Unlock()
return len(f.requests)
}
// TestWatcherTriggersUnrollOnAncestorSpend verifies the passive watcher calls
// into unroll only after a watched ancestor materializes.
func TestWatcherTriggersUnrollOnAncestorSpend(t *testing.T) {
treePath, source := testLeafTree(t, 1)
target := testInput(2)
desc := testDescriptor(target, treePath)
chainRef := &fakeChainSourceRef{}
managerRef := &fakeManagerRef{}
watcher := NewWatcherActor(WatcherConfig{
ChainSource: chainRef,
VTXOManagerRef: managerRef,
Log: fn.None[btclog.Logger](),
})
t.Cleanup(watcher.Stop)
resp, err := watcher.Ref().Ask(t.Context(), &TrackVTXOsRequest{
VTXOs: []*vtxo.Descriptor{desc},
}).Await(t.Context()).Unpack()
require.NoError(t, err)
trackResp, ok := resp.(*TrackVTXOsResp)
require.True(t, ok)
require.Equal(t, 1, trackResp.Tracked)
require.Equal(t, 2, chainRef.spendWatchCount())
chainRef.emitSpend(t, source)
require.Eventually(t, func() bool {
return managerRef.requestCount() == 1
}, testTimeout, 10*time.Millisecond)
req := managerRef.lastRequest(t)
require.Equal(t, target, req.Outpoint)
require.Equal(t, actormsg.UnrollTriggerFraudSpend, req.Trigger)
untrackResp, err := watcher.Ref().Ask(
t.Context(), &UntrackRequest{TargetOutpoint: target},
).Await(t.Context()).Unpack()
require.NoError(t, err)
typedUntrack, ok := untrackResp.(*UntrackResp)
require.True(t, ok)
require.True(t, typedUntrack.Removed)
chainRef.mu.Lock()
require.Len(t, chainRef.unregisters, 2)
chainRef.mu.Unlock()
}
// testSweepScript is a stand-in for the operator's unilateral-CSV timeout
// script. Only its tap hash matters to the watcher.
var testSweepScript = []byte{0x51, 0xb2, 0x75}
// testSweepLeafHash returns the tap hash the watcher expects to see revealed
// by a legitimate operator sweep of testSweepScript.
func testSweepLeafHash() []byte {
hash := txscript.NewBaseTapLeaf(testSweepScript).TapHash()
return hash[:]
}
// emitSpendWithWitness delivers a spend whose input carries the given witness,
// so a test can control which taproot path the spend appears to take.
func (f *fakeChainSourceRef) emitSpendWithWitness(t *testing.T,
outpoint wire.OutPoint, witness [][]byte) {
t.Helper()
f.mu.Lock()
ref := f.spendRefs[outpoint]
f.mu.Unlock()
require.NotNil(t, ref)
spendingTx := wire.NewMsgTx(2)
spendingTx.AddTxIn(&wire.TxIn{
PreviousOutPoint: outpoint,
Witness: witness,
})
require.NoError(
t,
ref.Tell(
t.Context(), chainsource.SpendEvent{
Outpoint: outpoint,
SpendingTxid: spendingTx.TxHash(),
SpendingTx: spendingTx,
SpenderInputIndex: 0,
SpendingHeight: 33,
},
),
)
}
// sweepWitness is the witness shape of a taproot script-path spend revealing
// the operator's sweep leaf: signature, script, control block.
func sweepWitness(script []byte) [][]byte {
return [][]byte{{0x01}, script, {0xc0}}
}
// TestWatcherSkipsUnrollOnOperatorSweep verifies that a spend revealing the
// operator's committed timeout leaf does not escalate.
//
// The operator's batch sweep spends exactly the outputs the watcher monitors,
// so without this the sweep would drive a pointless unroll on every affected
// target.
func TestWatcherSkipsUnrollOnOperatorSweep(t *testing.T) {
treePath, _ := testLeafTree(t, 60)
treePath.SweepTapscriptRoot = testSweepLeafHash()
// The operator sweeps tree node outputs, not VTXO leaves: a leaf's
// taproot commits only the collaborative and owner-timeout paths. The
// node input is therefore what a sweep spends.
source := treePath.Root.Input
target := testInput(61)
desc := testDescriptor(target, treePath)
chainRef := &fakeChainSourceRef{}
managerRef := &fakeManagerRef{}
watcher := NewWatcherActor(WatcherConfig{
ChainSource: chainRef,
VTXOManagerRef: managerRef,
Log: fn.None[btclog.Logger](),
})
t.Cleanup(watcher.Stop)
_, err := watcher.Ref().Ask(t.Context(), &TrackVTXOsRequest{
VTXOs: []*vtxo.Descriptor{desc},
}).Await(t.Context()).Unpack()
require.NoError(t, err)
chainRef.emitSpendWithWitness(
t, source, sweepWitness(testSweepScript),
)
require.Never(t, func() bool {
return managerRef.requestCount() > 0
}, 300*time.Millisecond, 20*time.Millisecond)
}
// TestWatcherEscalatesHostileSpendRevealingOtherLeaf verifies that a spend
// which does NOT reveal the operator's sweep leaf still escalates, even though
// the operator's timeout path has matured.
//
// This is the case a height-based check gets wrong. Maturity says the operator
// COULD sweep; it does not say this transaction did. A sender materializing
// ancestry can win the race against a conflicting sweep, and suppressing there
// would guarantee inaction exactly when fraud response is needed.
func TestWatcherEscalatesHostileSpendRevealingOtherLeaf(t *testing.T) {
treePath, _ := testLeafTree(t, 70)
treePath.SweepTapscriptRoot = testSweepLeafHash()
source := treePath.Root.Input
target := testInput(71)
desc := testDescriptor(target, treePath)
chainRef := &fakeChainSourceRef{}
managerRef := &fakeManagerRef{}
watcher := NewWatcherActor(WatcherConfig{
ChainSource: chainRef,
VTXOManagerRef: managerRef,
Log: fn.None[btclog.Logger](),
})
t.Cleanup(watcher.Stop)
_, err := watcher.Ref().Ask(t.Context(), &TrackVTXOsRequest{
VTXOs: []*vtxo.Descriptor{desc},
}).Await(t.Context()).Unpack()
require.NoError(t, err)
// Same height a sweep would confirm at, but a different script.
chainRef.emitSpendWithWitness(
t, source,
sweepWitness(
[]byte{0x52, 0xb2, 0x75},
),
)
require.Eventually(t, func() bool {
return managerRef.requestCount() == 1
}, testTimeout, 10*time.Millisecond)
require.Equal(t, target, managerRef.lastRequest(t).Outpoint)
}
// TestWatcherEscalatesWithoutCommittedSweepLeaf verifies that a tree carrying
// no sweep script never attributes a spend to the operator. An incomplete
// watch plan must not silently disarm fraud defense.
func TestWatcherEscalatesWithoutCommittedSweepLeaf(t *testing.T) {
treePath, _ := testLeafTree(t, 80)
treePath.SweepTapscriptRoot = nil
source := treePath.Root.Input
target := testInput(81)
desc := testDescriptor(target, treePath)
chainRef := &fakeChainSourceRef{}
managerRef := &fakeManagerRef{}
watcher := NewWatcherActor(WatcherConfig{
ChainSource: chainRef,
VTXOManagerRef: managerRef,
Log: fn.None[btclog.Logger](),
})
t.Cleanup(watcher.Stop)
_, err := watcher.Ref().Ask(t.Context(), &TrackVTXOsRequest{
VTXOs: []*vtxo.Descriptor{desc},
}).Await(t.Context()).Unpack()
require.NoError(t, err)
chainRef.emitSpendWithWitness(
t, source, sweepWitness(testSweepScript),
)
require.Eventually(t, func() bool {
return managerRef.requestCount() == 1
}, testTimeout, 10*time.Millisecond)
}
// TestWatcherTracksOnlyLiveOORVTXOs verifies admission keeps passive fraud
// watches limited to live out-of-round VTXOs.
func TestWatcherTracksOnlyLiveOORVTXOs(t *testing.T) {
treePath, _ := testLeafTree(t, 10)
liveOOR := testDescriptor(testInput(20), treePath)
liveRound := testDescriptor(testInput(21), treePath)
liveRound.ChainDepth = 0
spentOOR := testDescriptor(testInput(22), treePath)
spentOOR.Status = vtxo.VTXOStatusSpent
chainRef := &fakeChainSourceRef{}
watcher := NewWatcherActor(WatcherConfig{
ChainSource: chainRef,
VTXOManagerRef: &fakeManagerRef{},
Log: fn.None[btclog.Logger](),
})
t.Cleanup(watcher.Stop)
resp, err := watcher.Ref().Ask(t.Context(), &TrackVTXOsRequest{
VTXOs: []*vtxo.Descriptor{
liveRound,
spentOOR,
liveOOR,
nil,
},
}).Await(t.Context()).Unpack()
require.NoError(t, err)
trackResp, ok := resp.(*TrackVTXOsResp)
require.True(t, ok)
require.Equal(t, 1, trackResp.Tracked)
require.Equal(t, 2, chainRef.spendWatchCount())
}
// TestWatcherRefcountsSharedWatchOutpoints verifies shared ancestry produces
// one chainsource watch per outpoint and unregisters only after all targets
// release interest.
func TestWatcherRefcountsSharedWatchOutpoints(t *testing.T) {
treePath, _ := testLeafTree(t, 30)
targetOne := testInput(31)
targetTwo := testInput(32)
chainRef := &fakeChainSourceRef{}
watcher := NewWatcherActor(WatcherConfig{
ChainSource: chainRef,
VTXOManagerRef: &fakeManagerRef{},
Log: fn.None[btclog.Logger](),
})
t.Cleanup(watcher.Stop)
resp, err := watcher.Ref().Ask(t.Context(), &TrackVTXOsRequest{
VTXOs: []*vtxo.Descriptor{
testDescriptor(targetOne, treePath),
testDescriptor(targetTwo, treePath),
},
}).Await(t.Context()).Unpack()
require.NoError(t, err)
trackResp, ok := resp.(*TrackVTXOsResp)
require.True(t, ok)
require.Equal(t, 2, trackResp.Tracked)
require.Equal(t, 2, chainRef.spendWatchCount())
_, err = watcher.Ref().Ask(
t.Context(), &UntrackRequest{TargetOutpoint: targetOne},
).Await(t.Context()).Unpack()
require.NoError(t, err)
chainRef.mu.Lock()
require.Empty(t, chainRef.unregisters)
chainRef.mu.Unlock()
_, err = watcher.Ref().Ask(
t.Context(), &UntrackRequest{TargetOutpoint: targetTwo},
).Await(t.Context()).Unpack()
require.NoError(t, err)
chainRef.mu.Lock()
require.Len(t, chainRef.unregisters, 2)
chainRef.mu.Unlock()
}
// TestWatcherBestEffortTrackKeepsValidDescriptors verifies one malformed
// descriptor does not roll back unrelated valid watch registrations.
func TestWatcherBestEffortTrackKeepsValidDescriptors(t *testing.T) {
treePath, _ := testLeafTree(t, 40)
good := testDescriptor(testInput(41), treePath)
bad := testDescriptor(testInput(42), treePath)
bad.Ancestry[0].TreePath = nil
chainRef := &fakeChainSourceRef{}
watcher := NewWatcherActor(WatcherConfig{
ChainSource: chainRef,
VTXOManagerRef: &fakeManagerRef{},
Log: fn.None[btclog.Logger](),
})
t.Cleanup(watcher.Stop)
_, err := watcher.Ref().Ask(t.Context(), &TrackVTXOsRequest{
VTXOs: []*vtxo.Descriptor{bad, good},
}).Await(t.Context()).Unpack()
require.Error(t, err)
require.Equal(t, 2, chainRef.spendWatchCount())
}
// TestWatcherSpendFanoutBestEffort verifies one unroll admission failure does
// not prevent other targets sharing the same watched outpoint from being
// attempted.
func TestWatcherSpendFanoutBestEffort(t *testing.T) {
treePath, source := testLeafTree(t, 50)
managerRef := &fakeManagerRef{err: fmt.Errorf("admission failed")}
chainRef := &fakeChainSourceRef{}
watcher := NewWatcherActor(WatcherConfig{
ChainSource: chainRef,
VTXOManagerRef: managerRef,
Log: fn.None[btclog.Logger](),
})
t.Cleanup(watcher.Stop)
_, err := watcher.Ref().Ask(t.Context(), &TrackVTXOsRequest{
VTXOs: []*vtxo.Descriptor{
testDescriptor(testInput(51), treePath),
testDescriptor(testInput(52), treePath),
},
}).Await(t.Context()).Unpack()
require.NoError(t, err)
_, err = watcher.Ref().Ask(t.Context(), &SpendObservedMsg{
Outpoint: source,
SpendingTxid: testInput(53).Hash,
Height: 33,
}).Await(t.Context()).Unpack()
require.Error(t, err)
require.Equal(t, 2, managerRef.requestCount())
}