-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmux.go
204 lines (176 loc) · 5.13 KB
/
mux.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
package main
import (
"bytes"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"image"
_ "image/jpeg"
"image/png"
"log"
"net/http"
"net/url"
"os"
"strconv"
"time"
"github.com/lnproxy/lnc"
)
func replyJson(res http.ResponseWriter, value any) {
jsonData, _ := json.Marshal(value)
res.Header().Set("Content-Type", "application/json")
res.Header().Set("Content-Length", strconv.Itoa(len(jsonData)))
res.Write(jsonData)
}
func openIconFileAndConvertToPngBase64(iconFilePath string) (string, error) {
imageFile, err := os.Open(iconFilePath)
if err != nil {
return "", fmt.Errorf("unable to open icon_file at %q: %w", iconFilePath, err)
}
defer imageFile.Close()
icon, _, err := image.Decode(imageFile)
if err != nil {
return "", fmt.Errorf("invalid icon_file content: %w", err)
}
pngData := new(bytes.Buffer)
if err := png.Encode(pngData, icon); err != nil {
return "", err
}
pngBase64 := base64.StdEncoding.EncodeToString(pngData.Bytes())
return pngBase64, nil
}
func metadataArray(lightningAddress, shortDesc, pngBase64 string) json.RawMessage {
array := [][2]string{
{"text/identifier", lightningAddress},
{"text/plain", shortDesc},
{"image/png;base64", pngBase64},
}
jsonArray, _ := json.Marshal(array)
return json.RawMessage(jsonArray)
}
func createLndClient(cfg *LndConfig) (*lnc.Lnd, error) {
macaroon, err := os.ReadFile(cfg.MacaroonFile)
if err != nil {
return nil, fmt.Errorf("error reading macaroon file %q: %w", cfg.MacaroonFile, err)
}
var (
tlsConfig *tls.Config
protocol string
)
// To reach an LND instance running with `no-rest-tls=1`, use plaintext HTTP.
if cfg.TlsCertFile == "" && cfg.UnsafeAllowPlaintext {
log.Printf(
"WARNING: connecting to LND over plaintext HTTP; this exposes your macaroon " +
"credentials to middle-men. Use this only over an already-secure connection " +
"like a loopback address, or an SSH tunnel",
)
protocol = "http"
} else {
tlsCertContent, err := os.ReadFile(cfg.TlsCertFile)
if err != nil {
return nil, fmt.Errorf("error reading cert file %q: %w", cfg.TlsCertFile, err)
}
certPool := x509.NewCertPool()
certPool.AppendCertsFromPEM(tlsCertContent)
tlsConfig = &tls.Config{RootCAs: certPool}
protocol = "https"
}
lnd := &lnc.Lnd{
Host: &url.URL{Scheme: protocol, Host: cfg.Host},
Client: &http.Client{
Transport: &http.Transport{TLSClientConfig: tlsConfig},
Timeout: 15 * time.Second,
},
TlsConfig: tlsConfig,
Macaroon: hex.EncodeToString(macaroon),
}
return lnd, nil
}
func parseDomainName(authority string) (string, error) {
decoded, err := url.Parse(authority)
if err != nil {
return "", err
}
return decoded.Host, nil
}
func logRequest(req *http.Request) {
log.Printf("%s %s", req.Method, req.URL.Path)
}
func CreateMux(cfg *Config) (*http.ServeMux, error) {
pngBase64, err := openIconFileAndConvertToPngBase64(cfg.Lnurl.IconFile)
if err != nil {
return nil, err
}
lnd, err := createLndClient(&cfg.Lnd)
if err != nil {
return nil, err
}
domainName, err := parseDomainName(cfg.Lnurl.UrlAuthority)
if err != nil {
return nil, err
}
mux := http.NewServeMux()
for _, username := range cfg.LightningAddressUsernames {
lightningAddress := username + "@" + domainName
staticMetadataArray := metadataArray(lightningAddress, cfg.Lnurl.ShortDescription, pngBase64)
staticMetadataArrayHash := sha256.Sum256([]byte(staticMetadataArray))
mux.HandleFunc(
"GET /pay/callback/"+username,
func(res http.ResponseWriter, req *http.Request) {
logRequest(req)
millisatAmount, err := strconv.ParseUint(req.URL.Query().Get("amount"), 10, 64)
if err != nil {
res.WriteHeader(http.StatusBadRequest)
replyJson(res, map[string]string{
"status": "ERROR",
"reason": fmt.Sprintf("cannot parse amount: %s", err),
})
return
}
if millisatAmount > cfg.Lnurl.MaxPayRequestSats*1000 ||
millisatAmount < cfg.Lnurl.MinPayRequestSats*1000 {
res.WriteHeader(http.StatusBadRequest)
replyJson(res, map[string]string{
"status": "ERROR",
"reason": "amount is out of acceptable range",
})
return
}
invoice, err := lnd.AddInvoice(lnc.InvoiceParameters{
ValueMsat: millisatAmount,
DescriptionHash: staticMetadataArrayHash[:],
Expiry: uint64(cfg.Lnurl.InvoiceExpiry.Seconds()),
})
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
replyJson(res, map[string]string{
"status": "ERROR",
"reason": fmt.Sprintf("error constructing invoice: %s", err),
})
return
}
replyJson(res, map[string]any{
"pr": invoice,
"routes": []string{},
})
},
)
mux.HandleFunc(
"GET /.well-known/lnurlp/"+username,
func(res http.ResponseWriter, req *http.Request) {
logRequest(req)
replyJson(res, map[string]any{
"callback": cfg.Lnurl.UrlAuthority + "/pay/callback/" + username,
"maxSendable": cfg.Lnurl.MaxPayRequestSats * 1000,
"minSendable": cfg.Lnurl.MinPayRequestSats * 1000,
"metadata": string(staticMetadataArray),
"tag": "payRequest",
})
},
)
}
return mux, nil
}