-
Notifications
You must be signed in to change notification settings - Fork 18
/
lspd_node.go
534 lines (459 loc) · 14.1 KB
/
lspd_node.go
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
package itest
import (
"bufio"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"syscall"
"time"
"github.com/breez/lntest"
"github.com/breez/lspd/config"
"github.com/breez/lspd/lightning"
"github.com/breez/lspd/notifications"
lspd "github.com/breez/lspd/rpc"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/decred/dcrd/dcrec/secp256k1/v4"
ecies "github.com/ecies/go/v2"
"github.com/stretchr/testify/assert"
"github.com/tv42/zbase32"
"google.golang.org/grpc/metadata"
"google.golang.org/protobuf/proto"
)
var (
lspdExecutable = flag.String(
"lspdexec", "", "full path to lpsd plugin binary",
)
)
var (
lspBaseFeeMsat uint32 = 1000
lspFeeRatePpm uint32 = 1
lspCltvDelta uint16 = 144
)
type LspNode interface {
Start()
Stop() error
Harness() *lntest.TestHarness
PublicKey() *btcec.PublicKey
EciesPublicKey() *ecies.PublicKey
Rpc() lspd.ChannelOpenerClient
NotificationsRpc() notifications.NotificationsClient
NodeId() []byte
LightningNode() lntest.LightningNode
PostgresBackend() *PostgresContainer
}
type lspBase struct {
harness *lntest.TestHarness
conf *config.NodeConfig
name string
binary string
env []string
scriptFilePath string
logFilePath string
grpcAddress string
pubkey *secp256k1.PublicKey
eciesPubkey *ecies.PublicKey
postgresBackend *PostgresContainer
isInitialized bool
runtime *lspBaseRuntime
cleanups []*lntest.Cleanup
}
type lspBaseRuntime struct {
node lntest.LightningNode
cmd *exec.Cmd
logFile *os.File
cleanups []*lntest.Cleanup
}
func newLspd(h *lntest.TestHarness, mem *mempoolApi, name string, nodeConfig *config.NodeConfig, lnd *config.LndConfig, cln *config.ClnConfig, envExt ...string) (*lspBase, error) {
scriptDir := h.GetDirectory(fmt.Sprintf("lspd-%s", name))
log.Printf("%s: Creating LSPD in dir %s", name, scriptDir)
pgLogfile := filepath.Join(scriptDir, "postgres.log")
h.RegisterLogfile(pgLogfile, fmt.Sprintf("%s-postgres", name))
postgresBackend, err := NewPostgresContainer(pgLogfile)
if err != nil {
return nil, err
}
lspdBinary, err := getLspdBinary()
if err != nil {
return nil, err
}
lspdPort, err := lntest.GetPort()
if err != nil {
return nil, err
}
lspdPrivateKeyBytes, err := GenerateRandomBytes(32)
if err != nil {
return nil, err
}
_, publ := btcec.PrivKeyFromBytes(lspdPrivateKeyBytes)
eciesPubl := ecies.NewPrivateKeyFromBytes(lspdPrivateKeyBytes).PublicKey
host := "localhost"
grpcAddress := fmt.Sprintf("%s:%d", host, lspdPort)
minConfs := uint32(1)
conf := &config.NodeConfig{
Name: name,
LspdPrivateKey: hex.EncodeToString(lspdPrivateKeyBytes),
Tokens: []string{"hello"},
Host: "host:port",
PublicChannelAmount: 1000183,
TargetConf: 6,
MinConfs: &minConfs,
MinHtlcMsat: 600,
BaseFeeMsat: 1000,
FeeRate: 0.000001,
TimeLockDelta: 144,
ChannelFeePermyriad: 40,
ChannelMinimumFeeMsat: 2000000,
AdditionalChannelCapacity: 100000,
MaxInactiveDuration: 3888000,
MinPaymentSizeMsat: 600,
MaxPaymentSizeMsat: 4000000000,
Lnd: lnd,
Cln: cln,
}
if nodeConfig != nil {
if nodeConfig.MinConfs != nil {
conf.MinConfs = nodeConfig.MinConfs
}
if nodeConfig.LegacyOnionTokens != nil {
conf.LegacyOnionTokens = nodeConfig.LegacyOnionTokens
}
}
env := []string{
fmt.Sprintf("DATABASE_URL=%s", postgresBackend.ConnectionString()),
"AUTO_MIGRATE_DATABASE=true",
fmt.Sprintf("LISTEN_ADDRESS=%s", grpcAddress),
fmt.Sprintf("MEMPOOL_API_BASE_URL=%s", mem.Address()),
"MEMPOOL_PRIORITY=economy",
}
env = append(env, envExt...)
scriptFilePath := filepath.Join(scriptDir, "start-lspd.sh")
logFilePath := filepath.Join(scriptDir, "lspd.log")
h.RegisterLogfile(logFilePath, fmt.Sprintf("lspd-%s", name))
l := &lspBase{
harness: h,
conf: conf,
name: name,
env: env,
binary: lspdBinary,
scriptFilePath: scriptFilePath,
logFilePath: logFilePath,
grpcAddress: grpcAddress,
pubkey: publ,
eciesPubkey: eciesPubl,
postgresBackend: postgresBackend,
}
h.AddStoppable(l)
h.AddCleanable(l)
return l, nil
}
func (l *lspBase) StopRuntime() {
if l.runtime != nil {
lntest.PerformCleanup(l.runtime.cleanups)
}
l.runtime = nil
}
func (l *lspBase) Stop() error {
l.StopRuntime()
lntest.PerformCleanup(l.cleanups)
return nil
}
func (l *lspBase) Cleanup() error {
return l.postgresBackend.Cleanup(context.Background())
}
func (l *lspBase) Start(
node lntest.LightningNode,
confFunc func(*config.NodeConfig),
) {
var runtimeCleanups []*lntest.Cleanup
wasInitialized := l.isInitialized
node.Start()
runtimeCleanups = append(runtimeCleanups, &lntest.Cleanup{
Name: fmt.Sprintf("%s: lsp lightning node", l.name),
Fn: node.Stop,
})
if !wasInitialized {
l.initialize(runtimeCleanups, confFunc)
}
cmd := exec.CommandContext(l.harness.Ctx, l.scriptFilePath)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
logFile, err := os.Create(l.logFilePath)
if err != nil {
lntest.PerformCleanup(runtimeCleanups)
lntest.PerformCleanup(l.cleanups)
l.harness.T.Fatalf("failed create lsp logfile: %v", err)
}
runtimeCleanups = append(runtimeCleanups, &lntest.Cleanup{
Name: fmt.Sprintf("%s: logfile", l.name),
Fn: logFile.Close,
})
cmd.Stdout = logFile
cmd.Stderr = logFile
log.Printf("%s: starting lspd %s", l.name, l.scriptFilePath)
err = cmd.Start()
if err != nil {
lntest.PerformCleanup(runtimeCleanups)
lntest.PerformCleanup(l.cleanups)
l.harness.T.Fatalf("failed start lspd: %v", err)
}
runtimeCleanups = append(runtimeCleanups, &lntest.Cleanup{
Name: fmt.Sprintf("%s: cmd", l.name),
Fn: func() error {
proc := cmd.Process
if proc == nil {
return nil
}
syscall.Kill(-proc.Pid, syscall.SIGINT)
log.Printf("About to wait for lspd to exit")
status, err := proc.Wait()
if err != nil {
log.Printf("waiting for lspd process error: %v, status: %v", err, status)
}
err = cmd.Wait()
if err != nil {
log.Printf("waiting for lspd cmd error: %v", err)
}
return nil
},
})
if !wasInitialized {
<-time.After(time.Second * 2)
tx, err := l.postgresBackend.Pool().Begin(l.harness.Ctx)
defer tx.Rollback(l.harness.Ctx)
if err != nil {
lntest.PerformCleanup(runtimeCleanups)
lntest.PerformCleanup(l.cleanups)
l.harness.T.Fatalf("failed to begin postgres tx: %v", err)
}
_, err = tx.Exec(
l.harness.Ctx,
`DELETE FROM new_channel_params`,
)
if err != nil {
lntest.PerformCleanup(runtimeCleanups)
lntest.PerformCleanup(l.cleanups)
l.harness.T.Fatalf("failed to delete new_channel_params: %v", err)
}
_, err = tx.Exec(
l.harness.Ctx,
`INSERT INTO new_channel_params (validity, params, token)
VALUES
(3600, '{"min_msat": "1000000", "proportional": 7500, "max_idle_time": 4320, "max_client_to_self_delay": 432}', 'hello'),
(259200, '{"min_msat": "1100000", "proportional": 7500, "max_idle_time": 4320, "max_client_to_self_delay": 432}', 'hello');`,
)
if err != nil {
lntest.PerformCleanup(runtimeCleanups)
lntest.PerformCleanup(l.cleanups)
l.harness.T.Fatalf("failed to insert new_channel_params: %v", err)
}
err = tx.Commit(l.harness.Ctx)
if err != nil {
lntest.PerformCleanup(runtimeCleanups)
lntest.PerformCleanup(l.cleanups)
l.harness.T.Fatalf("failed to commit tx: %v", err)
}
}
l.runtime = &lspBaseRuntime{
node: node,
cmd: cmd,
logFile: logFile,
cleanups: runtimeCleanups,
}
}
func (l *lspBase) initialize(runtimeCleanups []*lntest.Cleanup, confFunc func(*config.NodeConfig)) {
var initializeCleanups []*lntest.Cleanup
err := l.postgresBackend.Start(l.harness.Ctx)
if err != nil {
lntest.PerformCleanup(initializeCleanups)
l.harness.T.Fatalf("failed to start postgres container: %v", err)
}
initializeCleanups = append(initializeCleanups, &lntest.Cleanup{
Name: fmt.Sprintf("%s: postgres container", l.name),
Fn: func() error {
return l.postgresBackend.Stop(context.Background())
},
})
log.Printf("%s: Creating lspd startup script at %s", l.name, l.scriptFilePath)
scriptFile, err := os.OpenFile(l.scriptFilePath, os.O_CREATE|os.O_WRONLY, 0755)
if err != nil {
lntest.PerformCleanup(runtimeCleanups)
lntest.PerformCleanup(initializeCleanups)
l.harness.T.Fatalf("failed to create lspd startup script: %v", err)
}
defer scriptFile.Close()
writer := bufio.NewWriter(scriptFile)
_, err = writer.WriteString("#!/bin/bash\n")
if err != nil {
lntest.PerformCleanup(runtimeCleanups)
lntest.PerformCleanup(initializeCleanups)
l.harness.T.Fatalf("failed to write lspd startup script: %v", err)
}
confFunc(l.conf)
confJson, _ := json.Marshal(l.conf)
nodes := fmt.Sprintf(`NODES='[%s]'`, string(confJson))
log.Printf("%s: node config: %s", l.name, nodes)
for _, str := range append(l.env, nodes) {
_, err = writer.WriteString("export " + str + "\n")
if err != nil {
lntest.PerformCleanup(runtimeCleanups)
lntest.PerformCleanup(initializeCleanups)
l.harness.T.Fatalf("failed to write lspd startup script: %v", err)
}
}
_, err = writer.WriteString(l.binary + "\n")
if err != nil {
lntest.PerformCleanup(runtimeCleanups)
lntest.PerformCleanup(initializeCleanups)
l.harness.T.Fatalf("failed to write lspd startup script: %v", err)
}
err = writer.Flush()
if err != nil {
lntest.PerformCleanup(runtimeCleanups)
lntest.PerformCleanup(initializeCleanups)
l.harness.T.Fatalf("failed to flush lspd startup script: %v", err)
}
l.isInitialized = true
l.cleanups = initializeCleanups
}
func ChannelInformation(l LspNode) *lspd.ChannelInformationReply {
info, err := l.Rpc().ChannelInformation(
l.Harness().Ctx,
&lspd.ChannelInformationRequest{},
)
if err != nil {
l.Harness().T.Fatalf("Failed to get ChannelInformation: %v", err)
}
return info
}
func RegisterPayment(l LspNode, paymentInfo *lspd.PaymentInformation, continueOnError bool) error {
serialized, err := proto.Marshal(paymentInfo)
lntest.CheckError(l.Harness().T, err)
encrypted, err := ecies.Encrypt(l.EciesPublicKey(), serialized)
lntest.CheckError(l.Harness().T, err)
ctx := metadata.AppendToOutgoingContext(l.Harness().Ctx, "authorization", "Bearer hello")
log.Printf("Registering payment")
_, err = l.Rpc().RegisterPayment(
ctx,
&lspd.RegisterPaymentRequest{
Blob: encrypted,
},
)
if !continueOnError {
lntest.CheckError(l.Harness().T, err)
}
return err
}
func SubscribeNotifications(l LspNode, b BreezClient, url string, continueOnError bool) error {
msg := append(lightning.SignedMsgPrefix, []byte(url)...)
first := sha256.Sum256([]byte(msg))
second := sha256.Sum256(first[:])
sig, err := ecdsa.SignCompact(b.Node().PrivateKey(), second[:], true)
assert.NoError(b.Harness().T, err)
request := notifications.SubscribeNotificationsRequest{
Url: url,
Signature: zbase32.EncodeToString(sig),
}
serialized, err := proto.Marshal(&request)
lntest.CheckError(l.Harness().T, err)
encrypted, err := ecies.Encrypt(l.EciesPublicKey(), serialized)
lntest.CheckError(l.Harness().T, err)
ctx := metadata.AppendToOutgoingContext(l.Harness().Ctx, "authorization", "Bearer hello")
log.Printf("Subscribing to notifications")
_, err = l.NotificationsRpc().SubscribeNotifications(
ctx,
¬ifications.EncryptedNotificationRequest{
Blob: encrypted,
},
)
if !continueOnError {
lntest.CheckError(l.Harness().T, err)
}
return err
}
func UnsubscribeNotifications(l LspNode, b BreezClient, url string, continueOnError bool) error {
msg := append(lightning.SignedMsgPrefix, []byte(url)...)
first := sha256.Sum256([]byte(msg))
second := sha256.Sum256(first[:])
sig, err := ecdsa.SignCompact(b.Node().PrivateKey(), second[:], true)
assert.NoError(b.Harness().T, err)
request := notifications.UnsubscribeNotificationsRequest{
Url: url,
Signature: zbase32.EncodeToString(sig),
}
serialized, err := proto.Marshal(&request)
lntest.CheckError(l.Harness().T, err)
encrypted, err := ecies.Encrypt(l.EciesPublicKey(), serialized)
lntest.CheckError(l.Harness().T, err)
ctx := metadata.AppendToOutgoingContext(l.Harness().Ctx, "authorization", "Bearer hello")
log.Printf("Removing notification subscription")
_, err = l.NotificationsRpc().UnsubscribeNotifications(
ctx,
¬ifications.EncryptedNotificationRequest{
Blob: encrypted,
},
)
if !continueOnError {
lntest.CheckError(l.Harness().T, err)
}
return nil
}
type FeeParamSetting struct {
Validity time.Duration
MinMsat uint64
Proportional uint32
}
func SetFeeParams(l LspNode, settings []*FeeParamSetting) error {
_, err := l.PostgresBackend().Pool().Exec(l.Harness().Ctx, "DELETE FROM new_channel_params")
if err != nil {
return fmt.Errorf("failed to delete new_channel_params: %w", err)
}
if len(settings) == 0 {
return nil
}
query := `INSERT INTO new_channel_params (validity, params, token) VALUES `
first := true
for _, setting := range settings {
if !first {
query += `,`
}
query += fmt.Sprintf(
`(%d, '{"min_msat": "%d", "proportional": %d, "max_idle_time": 4320, "max_client_to_self_delay": 432}', 'hello')`,
int64(setting.Validity.Seconds()),
setting.MinMsat,
setting.Proportional,
)
first = false
}
query += `;`
_, err = l.PostgresBackend().Pool().Exec(l.Harness().Ctx, query)
if err != nil {
return fmt.Errorf("failed to insert new_channel_params: %w", err)
}
return nil
}
func getLspdBinary() (string, error) {
if lspdExecutable != nil {
return *lspdExecutable, nil
}
return exec.LookPath("lspd")
}
type token struct {
token string
}
func (t *token) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
m := make(map[string]string)
m["authorization"] = "Bearer " + t.token
return m, nil
}
// RequireTransportSecurity indicates whether the credentials requires
// transport security.
func (t *token) RequireTransportSecurity() bool {
return false
}