-
Notifications
You must be signed in to change notification settings - Fork 2
/
config.go
417 lines (355 loc) · 12 KB
/
config.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
// Copyright 2019 Bonsai Software, Inc. All Rights Reserved.
package main
import (
"fmt"
"os"
"os/user"
"path/filepath"
"strings"
"time"
"github.com/btcsuite/btcutil"
"github.com/davecgh/go-spew/spew"
// "github.com/davecgh/go-spew/spew"
flags "github.com/jessevdk/go-flags"
)
const (
defaultVerbose = false
defaultNetwork = "mainnet"
defaultTLSCertFilename = "tls.cert"
defaultMacaroonFilename = "admin.macaroon"
defaultRPCHost = "localhost"
defaultStatsWindow = (time.Hour * 24 * 30)
defaultFinalCLTVDelta = uint32(144)
defaultFeeLimitRate = float64(0.0005)
defaultMinImbalance = int64(1000)
defaultTransferAmount = int64(10000)
defaultRetryInhibit = time.Hour
)
func rpcPort(network string) string {
switch network {
case "mainnet":
{
return "10009"
}
case "testnet":
{
return "11009"
}
default:
{
return "unknown"
}
}
}
var (
defaultLndDir = btcutil.AppDataDir("lnd", false)
defaultLndToolDir = btcutil.AppDataDir("lndtool", false)
defaultConfigFile = filepath.Join(
defaultLndToolDir, "lndtool-"+defaultNetwork+".conf")
defaultDBFile = filepath.Join(
defaultLndToolDir, "lndtool-"+defaultNetwork+".db")
defaultTLSCertPath = filepath.Join(defaultLndDir, defaultTLSCertFilename)
defaultMacaroonPath = filepath.Join(
defaultLndDir, "data", "chain", "bitcoin", defaultNetwork, defaultMacaroonFilename,
)
defaultRPCServer = defaultRPCHost + ":" + rpcPort(defaultNetwork)
)
type channelsConfig struct {
StatsWindow time.Duration `long:"statswindow" description:"Time window for channel statistics"`
}
type rebalanceConfig struct {
FinalCLTVDelta uint32 `long:"finalcltvdelta" description:"Final CLTV delta"`
FeeLimitRate float64 `long:"feelimitrate" description:"Limit fees to this rate"`
}
type recommendConfig struct {
SrcChanTarget []uint64 `long:"srcchantarget" description:"Adds channel to source target list (default: all)"`
DstChanTarget []uint64 `long:"dstchantarget" description:"Adds channel to destination target list (default: all)"`
PeerNodeBlacklist []string `long:"peernodeblacklist" description:"Adds node to peers to skip"`
MinImbalance int64 `long:"minimbalance" description:"Minimum imbalance to consider rebalancing"`
TransferAmount int64 `long:"transferamount" description:"Size of rebalance transfers"`
RetryInhibit time.Duration `long:"retryinhibit" description:"Inhibit retrying failed loops for this long"`
}
type config struct {
Verbose bool `long:"verbose" description:"Verbose output"`
Network string `long:"network" description:"Network (mainnet, testnet, ...)"`
LndDir string `long:"lnddir" description:"The base directory that contains lnd's data, logs, configuration file, etc."`
LndToolDir string `long:"lndtooldir" description:"The base directory that contains lndtool's data, logs, configuration file, etc."`
ConfigFile string `long:"C" long:"configfile" description:"Path to configuration file"`
DBFile string `long:"dbfile" description:"Path to database file"`
TLSCertPath string `long:"tlscertpath" description:"Path to read the TLS certificate for lnd's RPC and REST services"`
MacaroonPath string `long:"macaroonpath" description:"path to macaroon file"`
RPCServer string `long:"rpcserver" description:"host:port of ln daemon"`
Channels *channelsConfig `group:"Channels" namespace:"channels"`
Rebalance *rebalanceConfig `group:"Rebalance" namespace:"rebalance"`
Recommend *recommendConfig `group:"Recommend" namespace:"recommend"`
}
var defaultCfg = config{
Verbose: defaultVerbose,
Network: defaultNetwork,
LndDir: defaultLndDir,
LndToolDir: defaultLndToolDir,
ConfigFile: defaultConfigFile,
DBFile: defaultDBFile,
TLSCertPath: defaultTLSCertPath,
MacaroonPath: defaultMacaroonPath,
RPCServer: defaultRPCServer,
Channels: &channelsConfig{
StatsWindow: defaultStatsWindow,
},
Rebalance: &rebalanceConfig{
FinalCLTVDelta: defaultFinalCLTVDelta,
FeeLimitRate: defaultFeeLimitRate,
},
Recommend: &recommendConfig{
SrcChanTarget: []uint64{},
DstChanTarget: []uint64{},
PeerNodeBlacklist: []string{},
MinImbalance: defaultMinImbalance,
TransferAmount: defaultTransferAmount,
RetryInhibit: defaultRetryInhibit,
},
}
func nilHandler(flags.Commander, []string) error {
return nil
}
func loadConfig() (*config, error) {
// Pre-parse the command line options to pick up an alternative
// config file.
preCfg := defaultCfg
preParser := flags.NewParser(&preCfg, flags.Default)
addCommands(preParser)
preParser.CommandHandler = nilHandler // disable execution on this pass
if _, err := preParser.Parse(); err != nil {
return nil, err
}
// If the network has been changed on the command line update dependent
// defaults.
if preCfg.Network != defaultNetwork {
preCfg.RPCServer = defaultRPCHost + ":" + rpcPort(preCfg.Network)
preCfg.ConfigFile = filepath.Join(
defaultLndToolDir, "lndtool-"+preCfg.Network+".conf")
preCfg.DBFile = filepath.Join(
defaultLndToolDir, "lndtool-"+preCfg.Network+".db")
preCfg.MacaroonPath = filepath.Join(
defaultLndDir,
"data", "chain", "bitcoin", preCfg.Network,
defaultMacaroonFilename,
)
}
// If the config file path has not been modified by the user, then we'll
// use the default config file path. However, if the user has modified
// their lnddir, then we should assume they intend to use the config
// file within it.
lndtdir := cleanAndExpandPath(preCfg.LndToolDir)
configFilePath := cleanAndExpandPath(preCfg.ConfigFile)
if lndtdir != defaultLndDir {
if configFilePath == defaultConfigFile {
configFilePath = filepath.Join(
lndtdir, "lndtool-"+preCfg.Network+".conf")
}
preCfg.DBFile = filepath.Join(
lndtdir, "lndtool-"+preCfg.Network+".db")
}
// Next, load any additional configuration options from the file.
var configFileError error
postCfg := preCfg
if err := flags.IniParse(configFilePath, &postCfg); err != nil {
// If it's a parsing related error, then we'll return
// immediately, otherwise we can proceed as possibly the config
// file doesn't exist which is OK.
if _, ok := err.(*flags.IniError); ok {
return nil, err
}
configFileError = err
}
// Finally, parse the remaining command line options again to ensure
// they take precedence.
parser := flags.NewParser(&postCfg, flags.Default)
addCommands(parser)
_, err := parser.Parse()
if err != nil {
return nil, err
}
// If the provided lnd directory is not the default, we'll modify the
// path to all of the files and directories that will live within it.
lndDir := cleanAndExpandPath(postCfg.LndDir)
if lndDir != defaultLndDir {
postCfg.TLSCertPath = filepath.Join(lndDir, defaultTLSCertFilename)
postCfg.MacaroonPath = filepath.Join(
lndDir,
"data", "chain", "bitcoin", postCfg.Network,
defaultMacaroonFilename,
)
}
// If the provided lndtool directory is not the default, we'll modify the
// path to all of the files and directories that will live within it.
lndToolDir := cleanAndExpandPath(postCfg.LndToolDir)
if lndToolDir != defaultLndToolDir {
postCfg.DBFile = filepath.Join(
lndToolDir, "lndtool-"+preCfg.Network+".db")
}
// Create the lndtool directory if it doesn't already exist.
funcName := "loadConfig"
if err := os.MkdirAll(lndToolDir, 0700); err != nil {
// Show a nicer error message if it's because a symlink is
// linked to a directory that does not exist (probably because
// it's not mounted).
if e, ok := err.(*os.PathError); ok && os.IsExist(err) {
if link, lerr := os.Readlink(e.Path); lerr == nil {
str := "is symlink %s -> %s mounted?"
err = fmt.Errorf(str, e.Path, link)
}
}
str := "%s: Failed to create lndtool directory: %v"
err := fmt.Errorf(str, funcName, err)
fmt.Fprintln(os.Stderr, err)
return nil, err
}
// As soon as we're done parsing configuration options, ensure all paths
// to directories and files are cleaned and expanded before attempting
// to use them later on.
postCfg.TLSCertPath = cleanAndExpandPath(postCfg.TLSCertPath)
postCfg.MacaroonPath = cleanAndExpandPath(postCfg.MacaroonPath)
postCfg.DBFile = cleanAndExpandPath(postCfg.DBFile)
// Warn about missing config file only after all other configuration is
// done. This prevents the warning on help messages and invalid
// options. Note this should go directly before the return.
if configFileError != nil {
// ltndLog.Warnf("%v", configFileError)
fmt.Printf("warn: %v\n", configFileError)
}
return &postCfg, nil
}
// cleanAndExpandPath expands environment variables and leading ~ in the
// passed path, cleans the result, and returns it.
// This function is taken from https://github.com/btcsuite/btcd
func cleanAndExpandPath(path string) string {
if path == "" {
return ""
}
// Expand initial ~ to OS specific home directory.
if strings.HasPrefix(path, "~") {
var homeDir string
user, err := user.Current()
if err == nil {
homeDir = user.HomeDir
} else {
homeDir = os.Getenv("HOME")
}
path = strings.Replace(path, "~", homeDir, 1)
}
// NOTE: The os.ExpandEnv doesn't work with Windows-style %VARIABLE%,
// but the variables can still be expanded via POSIX-style $VARIABLE.
return filepath.Clean(os.ExpandEnv(path))
}
type LNDToolCommand interface {
RunCommand() error
}
var command LNDToolCommand = nil
var arguments []string = nil
func addCommands(parser *flags.Parser) {
parser.AddCommand("dumpconfig",
"Dumps the configuration to stdout",
"The dumpconfig command prints the config to stdout",
&dumpConfigCmd)
parser.AddCommand("channels",
"Lists channels in tabular form",
"Lists channels in tabular form",
&listChannelsCmd)
parser.AddCommand("farside",
"Finds nodes on the far side of the connected set",
"Finds nodes on the far side of the connected set",
&farSideCmd)
parser.AddCommand("rebalance",
"Balance a pair of channels with a loop transaction",
"Balance a pair of channels with a loop transaction",
&rebalanceCmd)
parser.AddCommand("recommend",
"Recommend a pair of channels to rebalance",
"Recommend a pair of channels to rebalance",
&recommendCmd)
parser.AddCommand("autobalance",
"Loop balancing channels",
"Loop balancing channels",
&autoBalanceCmd)
}
type DumpConfigCmd struct {
}
var dumpConfigCmd DumpConfigCmd
func (cmd *DumpConfigCmd) Execute(args []string) error {
command = cmd
arguments = args
return nil
}
func (cmd *DumpConfigCmd) RunCommand() error {
spew.Dump(gCfg)
return nil
}
type ListChannelsCmd struct {
}
var listChannelsCmd ListChannelsCmd
func (cmd *ListChannelsCmd) Execute(args []string) error {
command = cmd
arguments = args
return nil
}
func (cmd *ListChannelsCmd) RunCommand() error {
listChannels()
return nil
}
type FarSideCmd struct {
}
var farSideCmd FarSideCmd
func (cmd *FarSideCmd) Execute(args []string) error {
command = cmd
arguments = args
return nil
}
func (cmd *FarSideCmd) RunCommand() error {
farSide()
return nil
}
type RebalanceCmd struct {
Amount int64 `short:"a" long:"amount" description:"Amount to transfer" required:"true"`
Source uint64 `short:"s" long:"source" description:"Source channel" required:"true"`
Destination uint64 `short:"d" long:"destination" description:"Destination channel" required:"true"`
}
var rebalanceCmd RebalanceCmd
func (cmd *RebalanceCmd) Execute(args []string) error {
command = cmd
arguments = args
return nil
}
func (cmd *RebalanceCmd) RunCommand() error {
doRebalance(cmd.Amount, cmd.Source, cmd.Destination)
return nil
}
type RecommendCmd struct {
DoIt bool `short:"d" long:"doit" description:"Execute the recommended rebalance command"`
}
var recommendCmd RecommendCmd
func (cmd *RecommendCmd) Execute(args []string) error {
command = cmd
arguments = args
return nil
}
func (cmd *RecommendCmd) RunCommand() error {
recommend(cmd.DoIt)
return nil
}
type AutoBalanceCmd struct {
}
var autoBalanceCmd AutoBalanceCmd
func (cmd *AutoBalanceCmd) Execute(args []string) error {
command = cmd
arguments = args
return nil
}
func (cmd *AutoBalanceCmd) RunCommand() error {
for {
if !recommend(true) {
break
}
}
return nil
}