2022-08-20 14:11:45 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"math"
|
|
|
|
"math/rand"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/lightningnetwork/lnd/lnrpc"
|
|
|
|
)
|
|
|
|
|
2022-08-20 19:19:48 +00:00
|
|
|
func (r *regolancer) getChannels(ctx context.Context) error {
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, time.Second*30)
|
2022-08-20 14:11:45 +00:00
|
|
|
defer cancel()
|
|
|
|
channels, err := r.lnClient.ListChannels(ctx, &lnrpc.ListChannelsRequest{ActiveOnly: true, PublicOnly: true})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
r.channels = channels.Channels
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-08-20 18:12:19 +00:00
|
|
|
func (r *regolancer) getChannelCandidates(fromPerc, toPerc, amount int64, ignore []uint64) error {
|
|
|
|
ignoredSet := map[uint64]struct{}{}
|
|
|
|
for _, cid := range ignore {
|
|
|
|
ignoredSet[cid] = struct{}{}
|
|
|
|
}
|
2022-08-20 14:11:45 +00:00
|
|
|
for _, c := range r.channels {
|
|
|
|
if c.LocalBalance < c.Capacity*toPerc/100 && c.LocalBalance+amount < c.Capacity/2 {
|
|
|
|
r.toChannels = append(r.toChannels, c)
|
|
|
|
}
|
|
|
|
if c.RemoteBalance < c.Capacity*fromPerc/100 && c.RemoteBalance-amount < c.Capacity/2 {
|
2022-08-20 18:12:19 +00:00
|
|
|
if _, ok := ignoredSet[c.ChanId]; ok {
|
|
|
|
continue
|
|
|
|
}
|
2022-08-20 14:11:45 +00:00
|
|
|
r.fromChannels = append(r.fromChannels, c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func min(args ...int64) (result int64) {
|
|
|
|
result = math.MaxInt64
|
|
|
|
for _, a := range args {
|
|
|
|
if a < result {
|
|
|
|
result = a
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-08-20 19:19:48 +00:00
|
|
|
func (r *regolancer) pickChannelPair(ctx context.Context, amount int64) (from uint64, to uint64, maxAmount int64, err error) {
|
|
|
|
var fromChan, toChan *lnrpc.Channel
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return 0, 0, 0, ctx.Err()
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
fromIdx := rand.Int31n(int32(len(r.fromChannels)))
|
|
|
|
toIdx := rand.Int31n(int32(len(r.toChannels)))
|
|
|
|
fromChan = r.fromChannels[fromIdx]
|
|
|
|
toChan = r.toChannels[toIdx]
|
|
|
|
if !r.isFailedRoute(fromChan.ChanId, toChan.ChanId) {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2022-08-20 14:11:45 +00:00
|
|
|
maxFrom := fromChan.Capacity/2 - fromChan.RemoteBalance
|
|
|
|
maxTo := toChan.Capacity/2 - toChan.LocalBalance
|
|
|
|
if amount == 0 {
|
|
|
|
maxAmount = min(maxFrom, maxTo)
|
|
|
|
} else {
|
|
|
|
maxAmount = min(maxFrom, maxTo, amount)
|
|
|
|
}
|
2022-08-20 19:19:48 +00:00
|
|
|
return fromChan.ChanId, toChan.ChanId, maxAmount, nil
|
2022-08-20 14:11:45 +00:00
|
|
|
}
|