-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathmanager_test.go
More file actions
431 lines (339 loc) · 11.8 KB
/
manager_test.go
File metadata and controls
431 lines (339 loc) · 11.8 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
package deposit
import (
"context"
"encoding/hex"
"testing"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/lightninglabs/lndclient"
"github.com/lightninglabs/loop/staticaddr/address"
"github.com/lightninglabs/loop/staticaddr/script"
"github.com/lightninglabs/loop/swap"
"github.com/lightninglabs/loop/swapserverrpc"
"github.com/lightninglabs/loop/test"
"github.com/lightningnetwork/lnd/chainntnfs"
"github.com/lightningnetwork/lnd/input"
"github.com/lightningnetwork/lnd/lnrpc/chainrpc"
"github.com/lightningnetwork/lnd/lnwallet"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
)
var (
defaultServerPubkeyBytes, _ = hex.DecodeString("021c97a90a411ff2b10dc2a8e32de2f29d2fa49d41bfbb52bd416e460db0747d0d")
defaultServerPubkey, _ = btcec.ParsePubKey(defaultServerPubkeyBytes)
defaultExpiry = uint32(100)
defaultDepositConfirmations = uint32(3)
)
type mockStaticAddressClient struct {
mock.Mock
}
func (m *mockStaticAddressClient) ServerStaticAddressLoopIn(ctx context.Context,
in *swapserverrpc.ServerStaticAddressLoopInRequest,
opts ...grpc.CallOption) (
*swapserverrpc.ServerStaticAddressLoopInResponse, error) {
args := m.Called(ctx, in, opts)
return args.Get(0).(*swapserverrpc.ServerStaticAddressLoopInResponse),
args.Error(1)
}
func (m *mockStaticAddressClient) PushStaticAddressSweeplessSigs(ctx context.Context,
in *swapserverrpc.PushStaticAddressSweeplessSigsRequest,
opts ...grpc.CallOption) (
*swapserverrpc.PushStaticAddressSweeplessSigsResponse, error) {
args := m.Called(ctx, in, opts)
return args.Get(0).(*swapserverrpc.PushStaticAddressSweeplessSigsResponse),
args.Error(1)
}
func (m *mockStaticAddressClient) PushStaticAddressHtlcSigs(ctx context.Context,
in *swapserverrpc.PushStaticAddressHtlcSigsRequest,
opts ...grpc.CallOption) (
*swapserverrpc.PushStaticAddressHtlcSigsResponse, error) {
args := m.Called(ctx, in, opts)
return args.Get(0).(*swapserverrpc.PushStaticAddressHtlcSigsResponse),
args.Error(1)
}
func (m *mockStaticAddressClient) ServerWithdrawDeposits(ctx context.Context,
in *swapserverrpc.ServerWithdrawRequest,
opts ...grpc.CallOption) (*swapserverrpc.ServerWithdrawResponse,
error) {
args := m.Called(ctx, in, opts)
return args.Get(0).(*swapserverrpc.ServerWithdrawResponse),
args.Error(1)
}
func (m *mockStaticAddressClient) ServerPsbtWithdrawDeposits(ctx context.Context,
in *swapserverrpc.ServerPsbtWithdrawRequest,
opts ...grpc.CallOption) (*swapserverrpc.ServerPsbtWithdrawResponse,
error) {
args := m.Called(ctx, in, opts)
return args.Get(0).(*swapserverrpc.ServerPsbtWithdrawResponse),
args.Error(1)
}
func (m *mockStaticAddressClient) ServerNewAddress(ctx context.Context,
in *swapserverrpc.ServerNewAddressRequest, opts ...grpc.CallOption) (
*swapserverrpc.ServerNewAddressResponse, error) {
args := m.Called(ctx, in, opts)
return args.Get(0).(*swapserverrpc.ServerNewAddressResponse),
args.Error(1)
}
type mockAddressManager struct {
mock.Mock
}
func (m *mockAddressManager) GetStaticAddressParameters(ctx context.Context) (
*address.Parameters, error) {
args := m.Called(ctx)
return args.Get(0).(*address.Parameters),
args.Error(1)
}
func (m *mockAddressManager) GetStaticAddress(ctx context.Context) (
*script.StaticAddress, error) {
args := m.Called(ctx)
return args.Get(0).(*script.StaticAddress),
args.Error(1)
}
func (m *mockAddressManager) ListUnspent(ctx context.Context,
minConfs, maxConfs int32) ([]*lnwallet.Utxo, error) {
args := m.Called(ctx, minConfs, maxConfs)
return args.Get(0).([]*lnwallet.Utxo),
args.Error(1)
}
func (m *mockAddressManager) GetTaprootAddress(clientPubkey,
serverPubkey *btcec.PublicKey, expiry int64) (*btcutil.AddressTaproot,
error) {
args := m.Called(clientPubkey, serverPubkey, expiry)
return args.Get(0).(*btcutil.AddressTaproot),
args.Error(1)
}
type mockStore struct {
mock.Mock
}
func (s *mockStore) CreateDeposit(ctx context.Context, deposit *Deposit) error {
args := s.Called(ctx, deposit)
return args.Error(0)
}
func (s *mockStore) UpdateDeposit(ctx context.Context, deposit *Deposit) error {
args := s.Called(ctx, deposit)
return args.Error(0)
}
func (s *mockStore) GetDeposit(ctx context.Context, depositID ID) (*Deposit,
error) {
args := s.Called(ctx, depositID)
return args.Get(0).(*Deposit), args.Error(1)
}
func (s *mockStore) DepositForOutpoint(ctx context.Context,
outpoint string) (*Deposit, error) {
args := s.Called(ctx, outpoint)
return args.Get(0).(*Deposit), args.Error(1)
}
func (s *mockStore) AllDeposits(ctx context.Context) ([]*Deposit, error) {
args := s.Called(ctx)
return args.Get(0).([]*Deposit), args.Error(1)
}
type MockChainNotifier struct {
mock.Mock
}
func (m *MockChainNotifier) RawClientWithMacAuth(
ctx context.Context) (context.Context, time.Duration,
chainrpc.ChainNotifierClient) {
return ctx, 0, nil
}
func (m *MockChainNotifier) RegisterConfirmationsNtfn(ctx context.Context,
txid *chainhash.Hash, pkScript []byte, numConfs, heightHint int32,
_ ...lndclient.NotifierOption) (chan *chainntnfs.TxConfirmation,
chan error, error) {
args := m.Called(ctx, txid, pkScript, numConfs, heightHint)
return args.Get(0).(chan *chainntnfs.TxConfirmation),
args.Get(1).(chan error), args.Error(2)
}
func (m *MockChainNotifier) RegisterBlockEpochNtfn(ctx context.Context) (
chan int32, chan error, error) {
args := m.Called(ctx)
return args.Get(0).(chan int32), args.Get(1).(chan error), args.Error(2)
}
func (m *MockChainNotifier) RegisterSpendNtfn(ctx context.Context,
outpoint *wire.OutPoint, pkScript []byte, heightHint int32,
_ ...lndclient.NotifierOption) (chan *chainntnfs.SpendDetail,
chan error, error) {
args := m.Called(ctx, pkScript, heightHint)
return args.Get(0).(chan *chainntnfs.SpendDetail),
args.Get(1).(chan error), args.Error(2)
}
// TestManager checks that the manager processes the right channel notifications
// while a deposit is expiring.
func TestManager(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
// Create the test context with required mocks.
testContext := newManagerTestContext(t)
// Start the deposit manager.
initChan := make(chan struct{})
runErrChan := make(chan error, 1)
go func() {
runErrChan <- testContext.manager.Run(ctx, initChan)
}()
// Ensure that the manager has been initialized.
select {
case <-initChan:
case err := <-runErrChan:
require.NoError(t, err, "manager failed to start")
case <-time.After(test.Timeout):
t.Fatal("manager timed out starting")
}
// Notify about the last block before the expiry.
testContext.blockChan <- int32(
defaultDepositConfirmations + defaultExpiry - 1,
)
// Ensure that the deposit state machine didn't sign for the expiry tx.
select {
case <-testContext.mockLnd.SignOutputRawChannel:
t.Fatal("received unexpected sign request")
case <-time.After(test.Timeout / 10):
}
// Mine the expiry tx height.
testContext.blockChan <- int32(
defaultDepositConfirmations + defaultExpiry,
)
// Ensure that the deposit state machine signed the expiry tx.
select {
case <-testContext.mockLnd.SignOutputRawChannel:
case <-time.After(test.Timeout):
t.Fatal("did not receive sign request")
}
// Ensure that the signed expiry transaction is published.
var expiryTx *wire.MsgTx
select {
case expiryTx = <-testContext.mockLnd.TxPublishChannel:
case <-time.After(test.Timeout):
t.Fatal("did not receive published expiry tx")
}
// Ensure that the deposit is waiting for a confirmation notification.
testContext.confChan <- &chainntnfs.TxConfirmation{
BlockHeight: defaultDepositConfirmations + defaultExpiry + 3,
Tx: expiryTx,
}
// Ensure that the manager observed the finalization and removed the
// deposit from its active set.
require.Eventually(t, func() bool {
testContext.manager.mu.Lock()
defer testContext.manager.mu.Unlock()
return len(testContext.manager.activeDeposits) == 0
}, test.Timeout, 10*time.Millisecond)
cancel()
select {
case err := <-runErrChan:
require.ErrorIs(t, err, context.Canceled)
case <-time.After(test.Timeout):
t.Fatal("manager did not stop")
}
}
// ManagerTestContext is a helper struct that contains all the necessary
// components to test the reservation manager.
type ManagerTestContext struct {
manager *Manager
context test.Context
mockLnd *test.LndMockServices
mockStaticAddressClient *mockStaticAddressClient
mockAddressManager *mockAddressManager
confChan chan *chainntnfs.TxConfirmation
confErrChan chan error
blockChan chan int32
blockErrChan chan error
}
// newManagerTestContext creates a new test context for the reservation manager.
func newManagerTestContext(t *testing.T) *ManagerTestContext {
mockLnd := test.NewMockLnd()
lndContext := test.NewContext(t, mockLnd)
mockStaticAddressClient := new(mockStaticAddressClient)
mockAddressManager := new(mockAddressManager)
mockStore := new(mockStore)
mockChainNotifier := new(MockChainNotifier)
confChan := make(chan *chainntnfs.TxConfirmation)
confErrChan := make(chan error)
blockChan := make(chan int32)
blockErrChan := make(chan error)
ID, err := GetRandomDepositID()
utxo := &lnwallet.Utxo{
AddressType: lnwallet.TaprootPubkey,
Value: btcutil.Amount(100000),
Confirmations: int64(defaultDepositConfirmations),
PkScript: []byte("pkscript"),
OutPoint: wire.OutPoint{
Hash: chainhash.Hash{},
Index: 0xffffffff,
},
}
require.NoError(t, err)
storedDeposits := []*Deposit{
{
ID: ID,
state: Deposited,
OutPoint: utxo.OutPoint,
Value: utxo.Value,
ConfirmationHeight: 3,
TimeOutSweepPkScript: []byte{0x42, 0x21, 0x69},
},
}
mockStore.On(
"AllDeposits", mock.Anything,
).Return(storedDeposits, nil)
mockStore.On(
"UpdateDeposit", mock.Anything, mock.Anything,
).Return(nil)
mockAddressManager.On(
"GetStaticAddressParameters", mock.Anything,
).Return(&address.Parameters{
Expiry: defaultExpiry,
}, nil)
mockAddressManager.On(
"ListUnspent", mock.Anything, mock.Anything, mock.Anything,
).Return([]*lnwallet.Utxo{utxo}, nil)
// Define the expected return values for the mocks.
mockChainNotifier.On(
"RegisterConfirmationsNtfn", mock.Anything, mock.Anything,
mock.Anything, mock.Anything, mock.Anything,
).Return(confChan, confErrChan, nil)
mockChainNotifier.On("RegisterBlockEpochNtfn", mock.Anything).Return(
blockChan, blockErrChan, nil,
)
cfg := &ManagerConfig{
AddressManager: mockAddressManager,
Store: mockStore,
WalletKit: mockLnd.WalletKit,
ChainNotifier: mockChainNotifier,
Signer: mockLnd.Signer,
}
manager := NewManager(cfg)
testContext := &ManagerTestContext{
manager: manager,
context: lndContext,
mockLnd: mockLnd,
mockStaticAddressClient: mockStaticAddressClient,
mockAddressManager: mockAddressManager,
confChan: confChan,
confErrChan: confErrChan,
blockChan: blockChan,
blockErrChan: blockErrChan,
}
staticAddress := generateStaticAddress(
context.Background(), testContext,
)
mockAddressManager.On(
"GetStaticAddress", mock.Anything,
).Return(staticAddress, nil)
return testContext
}
func generateStaticAddress(ctx context.Context,
t *ManagerTestContext) *script.StaticAddress {
keyDescriptor, err := t.mockLnd.WalletKit.DeriveNextKey(
ctx, swap.StaticAddressKeyFamily,
)
require.NoError(t.context.T, err)
staticAddress, err := script.NewStaticAddress(
input.MuSig2Version100RC2, int64(defaultExpiry),
keyDescriptor.PubKey, defaultServerPubkey,
)
require.NoError(t.context.T, err)
return staticAddress
}