/
autopilot.go
423 lines (368 loc) · 10.6 KB
/
autopilot.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
package main
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"github.com/lightninglabs/lightning-terminal/litrpc"
"github.com/lightninglabs/lightning-terminal/rules"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/urfave/cli"
)
var autopilotCommands = cli.Command{
Name: "autopilot",
Usage: "Manage autopilot sessions",
Category: "LNC",
Subcommands: []cli.Command{
listAutopilotFeaturesCmd,
addAutopilotSessionCmd,
revokeAutopilotSessionCmd,
listAutopilotSessionsCmd,
},
Description: "Manage autopilot sessions.",
}
var listAutopilotFeaturesCmd = cli.Command{
Name: "features",
ShortName: "f",
Usage: "List available Autopilot features.",
Description: "List available Autopilot features.",
Action: listFeatures,
}
var addAutopilotSessionCmd = cli.Command{
Name: "add",
ShortName: "a",
Usage: "Initialize an Autopilot session.",
Description: `
Initialize an Autopilot session.
If one of the 'feature-' flags is set for any 'feature', then that flag
must be provided for each 'feature'.
The rules and configuration options available for each feature can be
seen in the 'autopilot features' output. For a rule, all fields must be
set since the unset ones are interpreteded as zero values. Rule values
must adhere to the limits found in 'autopilot features'. If a rule is
not set, default values are used.
An example call for AutoFees reads:
#!/bin/bash
./litcli autopilot add --label=customRules \
--feature=AutoFees \
--feature-rules='{
"rules": {
"channel-policy-bounds": {
"chan_policy_bounds": {
"min_base_msat": "0",
"max_base_msat": "10000",
"min_rate_ppm": 10,
"max_rate_ppm": 5000,
"min_cltv_delta": 60,
"max_cltv_delta": 120,
"min_htlc_msat": "1",
"max_htlc_msat": "100000000000"
}
},
"peer-restriction": {
"peer_restrict": {
"peer_ids": [
"abcabc",
"defdef"
]
}
}
}
}' \
--feature-config='{}'`,
Action: initAutopilotSession,
Flags: []cli.Flag{
labelFlag,
expiryFlag,
mailboxServerAddrFlag,
devserver,
cli.StringSliceFlag{
Name: "feature",
Required: true,
},
cli.StringSliceFlag{
Name: "channel-restrict-list",
Usage: "[deprecated] List of channel IDs that the " +
"Autopilot server should not " +
"perform actions on. In the " +
"form of: chanID1,chanID2,...",
Hidden: true,
},
cli.StringSliceFlag{
Name: "peer-restrict-list",
Usage: "[deprecated] List of peer IDs that the " +
"Autopilot server should not " +
"perform actions on. In the " +
"form of: peerID1,peerID2,...",
Hidden: true,
},
cli.StringFlag{
Name: "group_id",
Usage: "The hex encoded group ID of the session " +
"group to link this one to.",
},
cli.StringSliceFlag{
Name: "feature-config",
Usage: "JSON-serialized configuration with the " +
"expected format: {\"version\":0," +
"\"option1\":\"parameter1\"," +
"\"option2\":\"parameter2\",...}. An empty " +
"configuration is allowed with {} to use the " +
"default configuration.",
},
cli.StringSliceFlag{
Name: "feature-rules",
Usage: `JSON-serialized rule map (see main ` +
`description for a format example).` +
`An empty rule map is allowed with {} to ` +
`use the default rules.`,
},
},
}
var revokeAutopilotSessionCmd = cli.Command{
Name: "revoke",
ShortName: "r",
Usage: "Revoke an Autopilot session.",
Description: "Revoke an active Autopilot session.",
Action: revokeAutopilotSession,
Flags: []cli.Flag{
cli.StringFlag{
Name: "localpubkey",
Usage: "Local pubkey of the " +
"session to revoke.",
Required: true,
},
},
}
var listAutopilotSessionsCmd = cli.Command{
Name: "list",
ShortName: "l",
Usage: "List all Autopilot sessions.",
Description: "List all Autopilot sessions.\n",
Action: listAutopilotSessions,
}
func revokeAutopilotSession(ctx *cli.Context) error {
ctxb := context.Background()
clientConn, cleanup, err := connectClient(ctx, false)
if err != nil {
return err
}
defer cleanup()
client := litrpc.NewAutopilotClient(clientConn)
pubkey, err := hex.DecodeString(ctx.String("localpubkey"))
if err != nil {
return err
}
resp, err := client.RevokeAutopilotSession(
ctxb, &litrpc.RevokeAutopilotSessionRequest{
LocalPublicKey: pubkey,
},
)
if err != nil {
return err
}
printRespJSON(resp)
return nil
}
func listAutopilotSessions(ctx *cli.Context) error {
ctxb := context.Background()
clientConn, cleanup, err := connectClient(ctx, false)
if err != nil {
return err
}
defer cleanup()
client := litrpc.NewAutopilotClient(clientConn)
resp, err := client.ListAutopilotSessions(
ctxb, &litrpc.ListAutopilotSessionsRequest{},
)
if err != nil {
return err
}
printRespJSON(resp)
return nil
}
func listFeatures(ctx *cli.Context) error {
ctxb := context.Background()
clientConn, cleanup, err := connectClient(ctx, false)
if err != nil {
return err
}
defer cleanup()
client := litrpc.NewAutopilotClient(clientConn)
resp, err := client.ListAutopilotFeatures(
ctxb, &litrpc.ListAutopilotFeaturesRequest{},
)
if err != nil {
return err
}
printRespJSON(resp)
return nil
}
func initAutopilotSession(ctx *cli.Context) error {
sessionLength := time.Second * time.Duration(ctx.Uint64("expiry"))
sessionExpiry := time.Now().Add(sessionLength).Unix()
ctxb := context.Background()
clientConn, cleanup, err := connectClient(ctx, false)
if err != nil {
return err
}
defer cleanup()
client := litrpc.NewAutopilotClient(clientConn)
features := ctx.StringSlice("feature")
// Check that the user only sets unique features.
fs := make(map[string]struct{})
for _, feature := range features {
if _, ok := fs[feature]; ok {
return fmt.Errorf("feature %v is set multiple times",
feature)
}
fs[feature] = struct{}{}
}
// Check that the user did not set multiple restrict lists.
var chanRestrictList, peerRestrictList string
channelRestrictSlice := ctx.StringSlice("channel-restrict-list")
if len(channelRestrictSlice) > 1 {
return fmt.Errorf("channel-restrict-list can only be used once")
} else if len(channelRestrictSlice) == 1 {
chanRestrictList = channelRestrictSlice[0]
}
peerRestrictSlice := ctx.StringSlice("peer-restrict-list")
if len(peerRestrictSlice) > 1 {
return fmt.Errorf("peer-restrict-list can only be used once")
} else if len(peerRestrictSlice) == 1 {
peerRestrictList = peerRestrictSlice[0]
}
// rulesMap stores the rules per each feature.
rulesMap := make(map[string]*litrpc.RulesMap)
rulesFlags := ctx.StringSlice("feature-rules")
// For legacy flags, we allow setting the channel and peer restrict
// lists when only a single feature is added.
if chanRestrictList != "" || peerRestrictList != "" {
// Check that the user did not set both the legacy flags and the
// generic rules flags together.
if len(rulesFlags) > 0 {
return fmt.Errorf("either set channel-restrict-list/" +
"peer-restrict-list or feature-rules, not both")
}
if len(features) > 1 {
return fmt.Errorf("cannot set channel-restrict-list/" +
"peer-restrict-list when multiple features " +
"are set")
}
feature := features[0]
// Init the rule map for this feature.
ruleMap := make(map[string]*litrpc.RuleValue)
if chanRestrictList != "" {
var chanIDs []uint64
chans := strings.Split(chanRestrictList, ",")
for _, c := range chans {
i, err := strconv.ParseUint(c, 10, 64)
if err != nil {
return err
}
chanIDs = append(chanIDs, i)
}
channelRestrict := &litrpc.ChannelRestrict{
ChannelIds: chanIDs,
}
ruleMap[rules.ChannelRestrictName] = &litrpc.RuleValue{
Value: &litrpc.RuleValue_ChannelRestrict{
ChannelRestrict: channelRestrict,
},
}
}
if peerRestrictList != "" {
peerIDs := strings.Split(peerRestrictList, ",")
ruleMap[rules.PeersRestrictName] = &litrpc.RuleValue{
Value: &litrpc.RuleValue_PeerRestrict{
PeerRestrict: &litrpc.PeerRestrict{
PeerIds: peerIDs,
},
},
}
}
rulesMap[feature] = &litrpc.RulesMap{Rules: ruleMap}
} else {
// We make sure that if the rules or configs flags are set, they
// are set for all features, to avoid ambiguity.
if len(rulesFlags) > 0 && len(features) != len(rulesFlags) {
return fmt.Errorf("number of features (%v) and rules "+
"(%v) must match", len(features),
len(rulesFlags))
}
// Parse the rules and store them in the rulesMap.
for i, rulesFlag := range rulesFlags {
var ruleMap litrpc.RulesMap
// We allow empty rules, to signal the usage of the
// default rules when the session is registered.
if rulesFlag != "{}" {
err = lnrpc.ProtoJSONUnmarshalOpts.Unmarshal(
[]byte(rulesFlag), &ruleMap,
)
if err != nil {
return err
}
}
rulesMap[features[i]] = &ruleMap
}
}
configs := ctx.StringSlice("feature-config")
if len(configs) > 0 && len(features) != len(configs) {
return fmt.Errorf("number of features (%v) and configurations "+
"(%v) must match", len(features), len(configs))
}
// Parse the configs and store them in the configsMap.
configsMap := make(map[string][]byte)
for i, configFlag := range configs {
var config []byte
// We allow empty configs, to signal the usage of the default
// configuration when the session is registered.
if configFlag != "{}" {
// We expect the config to be a JSON dictionary, so we
// unmarshal it into a map to do a first validation.
var configMap map[string]interface{}
err := json.Unmarshal([]byte(configs[i]), &configMap)
if err != nil {
return fmt.Errorf("could not parse "+
"configuration for feature %v: %v",
features[i], err)
}
config = []byte(configs[i])
}
configsMap[features[i]] = config
}
featureMap := make(map[string]*litrpc.FeatureConfig)
for _, feature := range features {
// Map access for unknown features will return their zero value
// if not set, which is what we want to signal default usage.
featureMap[feature] = &litrpc.FeatureConfig{
Rules: rulesMap[feature],
Config: configsMap[feature],
}
}
var groupID []byte
if ctx.IsSet("group_id") {
groupID, err = hex.DecodeString(ctx.String("group_id"))
if err != nil {
return err
}
}
resp, err := client.AddAutopilotSession(
ctxb, &litrpc.AddAutopilotSessionRequest{
Label: ctx.String("label"),
ExpiryTimestampSeconds: uint64(sessionExpiry),
MailboxServerAddr: ctx.String("mailboxserveraddr"),
DevServer: ctx.Bool("devserver"),
Features: featureMap,
LinkedGroupId: groupID,
},
)
if err != nil {
return err
}
printRespJSON(resp)
return nil
}