-
Notifications
You must be signed in to change notification settings - Fork 14
/
relay.go
240 lines (219 loc) · 7.53 KB
/
relay.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
package relay
import (
"encoding/hex"
"errors"
"fmt"
"log"
"sync"
"time"
"github.com/lnproxy/lnc"
)
var ClientFacing = errors.New("")
type Relay struct {
RelayParameters
lnc.LN
sync.WaitGroup
}
type RelayParameters struct {
MinAmountMsat uint64
MaxAmountMsat uint64
MinFeeBudgetMsat uint64
RoutingFeeBaseMsat uint64
RoutingFeePPM uint64
ExpiryBuffer uint64
MaxExpiry uint64
CltvDeltaAlpha uint64
CltvDeltaBeta uint64
RoutingBudgetAlpha uint64
RoutingBudgetBeta uint64
// Should be set to the same as the node's `--max-cltv-expiry` setting (default: 2016)
MaxCltvExpiry uint64
MinCltvExpiry uint64
// Should be set so that CltvDeltaAlpha blocks are very unlikely to be added before timeout
PaymentTimeout uint64
PaymentTimePreference float64
}
// Returns a Relay with with sane defaults
func NewRelay(ln lnc.LN) *Relay {
return &Relay{
RelayParameters: RelayParameters{
MinAmountMsat: 10_000,
MaxAmountMsat: 1_000_000_000,
ExpiryBuffer: 300,
MaxExpiry: 604800, // 60*60*24*7 one week
MinFeeBudgetMsat: 1000,
RoutingBudgetAlpha: 1000,
RoutingBudgetBeta: 1_500_000,
RoutingFeeBaseMsat: 1000,
RoutingFeePPM: 1000,
CltvDeltaAlpha: 42,
CltvDeltaBeta: 42,
// Should be set to at most the node's `--max-cltv-expiry` setting (default: 2016)
MaxCltvExpiry: 1800,
MinCltvExpiry: 420,
// Should be set so that CltvDeltaAlpha blocks are very unlikely to be added before timeout
PaymentTimeout: 60,
PaymentTimePreference: 0.9,
},
LN: ln,
}
}
// Parameters for lnproxy requests
type ProxyParameters struct {
Invoice string `json:"invoice"`
RoutingMsat *uint64 `json:"routing_msat,string"`
Description *string `json:"description"`
DescriptionHash *string `json:"description_hash"`
}
func (x ProxyParameters) String() string {
result := fmt.Sprintf("ProxyParameters {Invoice:%s", x.Invoice)
if x.RoutingMsat != nil {
result += fmt.Sprintf(" RoutingMsat:%d", *(x.RoutingMsat))
}
if x.Description != nil {
result += fmt.Sprintf(" Description:\"%s\"", *(x.Description))
} else if x.DescriptionHash != nil {
result += fmt.Sprintf(" DescriptionHash:%s", *(x.DescriptionHash))
}
return result + "}"
}
func (relay *Relay) wrap(x ProxyParameters) (proxy_invoice_params *lnc.InvoiceParameters, fee_budget_msat uint64, err error) {
p, err := relay.LN.DecodeInvoice(x.Invoice)
if err != nil {
return nil, 0, err
}
if p.NumMsat == 0 {
return nil, 0, errors.Join(ClientFacing, errors.New("zero amount invoices cannot be relayed trustlessly"))
}
if p.NumMsat < relay.MinAmountMsat {
return nil, 0, errors.Join(ClientFacing, errors.New("invoice amount too low"))
}
if p.NumMsat > relay.MaxAmountMsat {
return nil, 0, errors.Join(ClientFacing, errors.New("invoice amount too high"))
}
min_fee_budget_msat, min_cltv_delta, err := relay.LN.EstimateRoutingFee(*p, 0)
if err != nil {
// log.Println("route estimation error:", err)
// return nil, 0, errors.Join(ClientFacing, errors.New("could not find route"))
min_fee_budget_msat = 1000
min_cltv_delta = 144
}
for flag, _ := range p.Features {
switch flag {
case "8", "9", "14", "15", "16", "17", "25", "48", "49", "149", "151", "262":
// 25 is route blinding
// 48/49 is payment metadata
// 148/149 is trampoline routing
// 150/151 is electrum's trampoline
// 262/263 is bolt11 blinded paths
default:
return nil, 0, errors.Join(ClientFacing, fmt.Errorf("unknown feature flag: %s", flag))
}
}
q := lnc.InvoiceParameters{}
hash, err := hex.DecodeString(p.PaymentHash)
if err != nil {
return nil, 0, err
}
q.Hash = hash
if x.Description != nil && x.DescriptionHash != nil {
return nil, 0, errors.Join(ClientFacing, errors.New("description and description hash cannot both be set"))
} else if x.Description != nil {
q.Memo = *x.Description
} else if x.DescriptionHash != nil {
description_hash, err := hex.DecodeString(*x.DescriptionHash)
if err != nil {
return nil, 0, err
}
q.DescriptionHash = description_hash
} else if p.DescriptionHash != "" {
description_hash, err := hex.DecodeString(p.DescriptionHash)
if err != nil {
return nil, 0, err
}
q.DescriptionHash = description_hash
} else {
q.Memo = p.Description
}
if p.Timestamp+p.Expiry < uint64(time.Now().Unix())+relay.ExpiryBuffer {
return nil, 0, errors.Join(ClientFacing, errors.New("payment request expiration is too close."))
}
expiry := p.Expiry
if expiry > relay.MaxExpiry {
expiry = relay.MaxExpiry
}
q.Expiry = p.Timestamp + expiry - uint64(time.Now().Unix()) - relay.ExpiryBuffer
q.CltvExpiry = min_cltv_delta + relay.CltvDeltaBeta + relay.CltvDeltaAlpha
if q.CltvExpiry >= relay.MaxCltvExpiry {
return nil, 0, errors.Join(ClientFacing, errors.New("cltv_expiry is too long"))
} else if q.CltvExpiry < relay.MinCltvExpiry {
q.CltvExpiry = relay.MinCltvExpiry
}
routing_fee_msat := relay.RoutingFeeBaseMsat + (p.NumMsat*relay.RoutingFeePPM)/1_000_000
if x.RoutingMsat != nil {
if *x.RoutingMsat < (relay.MinFeeBudgetMsat + routing_fee_msat) {
return nil, 0, errors.Join(ClientFacing, errors.New("custom fee budget too low"))
}
q.ValueMsat = p.NumMsat + *x.RoutingMsat
return &q, *x.RoutingMsat - routing_fee_msat, nil
}
fee_budget_msat = min_fee_budget_msat + relay.RoutingBudgetAlpha + (min_fee_budget_msat*relay.RoutingBudgetBeta)/1_000_000
q.ValueMsat = p.NumMsat + fee_budget_msat + routing_fee_msat
return &q, fee_budget_msat, nil
}
// Takes an lnproxy request, validates that it can be proxied securely,
// opens a circuit that will be completed when invoice is successfully relayed,
// and returns a wrapped invoice.
func (relay *Relay) OpenCircuit(x ProxyParameters) (string, error) {
proxy_invoice_params, fee_budget_msat, err := relay.wrap(x)
if err != nil {
return "", err
}
proxy_invoice, err := relay.LN.AddInvoice(*proxy_invoice_params)
if errors.Is(err, lnc.PaymentHashExists) {
return "", errors.Join(ClientFacing, lnc.PaymentHashExists)
} else if err != nil {
return "", err
}
relay.WaitGroup.Add(1)
go relay.circuitSwitch(proxy_invoice_params.Hash, x.Invoice, fee_budget_msat)
return proxy_invoice, nil
}
func (relay *Relay) circuitSwitch(hash []byte, invoice string, fee_budget_msat uint64) {
defer relay.WaitGroup.Done()
log.Println("opened circuit for:", invoice, hex.EncodeToString(hash))
invoice_state, err := relay.LN.WatchInvoice(hash)
if err != nil || invoice_state.State != lnc.Accepted {
log.Println("error while watching wrapped invoice:", hex.EncodeToString(hash), invoice_state.State, err)
if invoice_state.State != lnc.Canceled {
err = relay.LN.CancelInvoice(hash)
if err != nil {
log.Println("error while canceling invoice:", hash, err)
}
}
return
}
preimage, err := relay.LN.PayInvoice(lnc.PaymentParameters{
Invoice: invoice,
TimeoutSeconds: relay.PaymentTimeout,
FeeLimitMsat: fee_budget_msat,
CltvLimit: invoice_state.CltvExpiryDelta - relay.CltvDeltaAlpha,
})
if errors.Is(err, lnc.PaymentFailed) {
log.Println("payment failed", hex.EncodeToString(hash), err)
err = relay.LN.CancelInvoice(hash)
if err != nil {
log.Println("error while canceling invoice:", hash, err)
}
return
} else if err != nil {
log.Panicln("payment in unknown state:", hex.EncodeToString(hash), err)
}
log.Println("preimage:", hex.EncodeToString(preimage), hex.EncodeToString(hash))
err = relay.LN.SettleInvoice(preimage)
if err != nil {
log.Panicln("error while settling original invoice:", hex.EncodeToString(hash), err)
}
log.Println("circuit settled")
return
}