regolancer/payment.go

148 lines
4.5 KiB
Go
Raw Normal View History

2022-08-20 14:11:45 +00:00
package main
import (
"context"
"fmt"
"log"
"os"
2022-08-20 14:11:45 +00:00
"time"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/routerrpc"
)
2022-08-20 17:02:25 +00:00
type ErrRetry struct {
amount int64
}
func (e ErrRetry) Error() string {
return fmt.Sprintf("retry payment with %d sats", e.amount)
}
var ErrProbeFailed = fmt.Errorf("probe failed")
func (r *regolancer) createInvoice(ctx context.Context, amount int64) (result *lnrpc.AddInvoiceResponse, err error) {
2022-10-09 11:06:12 +00:00
var ok bool
if result, ok = r.invoiceCache[amount]; ok {
return
}
result, err = r.lnClient.AddInvoice(ctx, &lnrpc.Invoice{Value: amount,
Memo: "Rebalance attempt",
2022-08-20 14:11:45 +00:00
Expiry: int64(time.Hour.Seconds() * 24)})
2022-10-09 11:06:12 +00:00
r.invoiceCache[amount] = result
2022-10-27 20:10:17 +00:00
2022-10-09 11:06:12 +00:00
return
}
func (r *regolancer) invalidateInvoice(amount int64) {
delete(r.invoiceCache, amount)
2022-08-20 14:11:45 +00:00
}
func (r *regolancer) pay(ctx context.Context, amount int64, minAmount int64,
route *lnrpc.Route, probeSteps int) error {
2022-08-21 09:57:47 +00:00
fmt.Println()
defer fmt.Println()
invoice, err := r.createInvoice(ctx, amount)
if err != nil {
log.Printf("Error creating invoice: %s", err)
return err
}
defer func() {
if ctx.Err() == context.DeadlineExceeded {
r.invalidateInvoice(amount)
}
}()
2022-08-20 14:11:45 +00:00
lastHop := route.Hops[len(route.Hops)-1]
lastHop.MppRecord = &lnrpc.MPPRecord{
PaymentAddr: invoice.PaymentAddr,
TotalAmtMsat: amount * 1000,
}
2022-10-27 20:10:17 +00:00
result, err := r.routerClient.SendToRouteV2(ctx,
2022-08-20 14:11:45 +00:00
&routerrpc.SendToRouteRequest{
PaymentHash: invoice.RHash,
Route: route,
})
if err != nil {
return err
}
if result.Status == lnrpc.HTLCAttempt_FAILED {
if result.Failure.FailureSourceIndex >= uint32(len(route.Hops)) {
2022-10-22 12:19:19 +00:00
logErrorF("%s (unexpected hop index %d, should be less than %d)", result.Failure.Code.String(),
result.Failure.FailureSourceIndex, len(route.Hops))
return fmt.Errorf("error: %s @ %d", result.Failure.Code.String(),
result.Failure.FailureSourceIndex)
}
2022-09-09 16:16:18 +00:00
if result.Failure.FailureSourceIndex == 0 {
2022-10-22 12:19:19 +00:00
logErrorF("%s (unexpected hop index %d, should be greater than 0)", result.Failure.Code.String(),
result.Failure.FailureSourceIndex)
2022-09-09 16:16:18 +00:00
return fmt.Errorf("error: %s @ %d", result.Failure.Code.String(),
result.Failure.FailureSourceIndex)
}
prevHop := route.Hops[result.Failure.FailureSourceIndex-1]
failedHop := route.Hops[result.Failure.FailureSourceIndex]
nodeCtx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
node1, err := r.getNodeInfo(nodeCtx, prevHop.PubKey)
2022-08-20 14:11:45 +00:00
node1name := ""
node2name := ""
if err != nil {
node1name = fmt.Sprintf("node%d", result.Failure.FailureSourceIndex-1)
} else {
node1name = node1.Node.Alias
}
node2, err := r.getNodeInfo(nodeCtx, failedHop.PubKey)
2022-08-20 14:11:45 +00:00
if err != nil {
node2name = fmt.Sprintf("node%d", result.Failure.FailureSourceIndex)
} else {
node2name = node2.Node.Alias
}
log.Printf("%s %s ⇒ %s", faintWhiteColor(result.Failure.Code.String()), cyanColor(node1name), cyanColor(node2name))
if result.Failure.Code == lnrpc.Failure_TEMPORARY_CHANNEL_FAILURE {
r.addFailedChan(node1.Node.PubKey, node2.Node.PubKey, prevHop.
AmtToForwardMsat)
}
2022-08-25 16:57:56 +00:00
if probeSteps > 0 && int(result.Failure.FailureSourceIndex) == len(route.Hops)-2 &&
result.Failure.Code == lnrpc.Failure_TEMPORARY_CHANNEL_FAILURE {
2022-08-20 17:02:25 +00:00
fmt.Println("Probing route...")
2022-08-22 20:01:46 +00:00
min := int64(0)
start := amount / 2
if minAmount > 0 && minAmount < amount {
min = -minAmount - 1
start = minAmount
}
2022-10-01 13:02:19 +00:00
maxAmount, err := r.probeRoute(ctx, route, min, amount, start,
probeSteps)
2022-08-20 17:02:25 +00:00
if err != nil {
2022-10-22 12:19:19 +00:00
logErrorF("Probe error: %s", err)
2022-08-20 17:02:25 +00:00
return err
}
if maxAmount == 0 {
return ErrProbeFailed
}
2022-08-20 22:15:39 +00:00
return ErrRetry{amount: maxAmount}
2022-08-20 17:02:25 +00:00
}
2022-08-20 14:11:45 +00:00
return fmt.Errorf("error: %s @ %d", result.Failure.Code.String(), result.Failure.FailureSourceIndex)
} else {
2022-10-22 11:45:10 +00:00
log.Printf("Success! Paid %s in fees, %s ppm",
formatFee(result.Route.TotalFeesMsat), formatFeePPM(result.Route.TotalAmtMsat, result.Route.TotalFeesMsat))
if r.statFilename != "" {
_, err := os.Stat(r.statFilename)
f, ferr := os.OpenFile(r.statFilename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if ferr != nil {
2022-10-22 12:19:19 +00:00
logErrorF("Error saving rebalance stats to %s: %s", r.statFilename, ferr)
return nil
}
defer f.Close()
if os.IsNotExist(err) {
f.WriteString("timestamp,from_channel,to_channel,amount_msat,fees_msat\n")
}
f.Write([]byte(fmt.Sprintf("%d,%d,%d,%d,%d\n", time.Now().Unix(), route.Hops[0].ChanId,
lastHop.ChanId, route.TotalAmtMsat-route.TotalFeesMsat, route.TotalFeesMsat)))
}
2022-10-27 20:10:17 +00:00
// Necessary for Rapid Rebalancing
r.invalidateInvoice(amount)
2022-08-20 14:11:45 +00:00
return nil
}
}