-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
274 lines (237 loc) · 7.65 KB
/
main.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
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"os/signal"
"strings"
"sync"
"time"
echologrus "github.com/davrux/echo-logrus/v4"
"github.com/getsentry/sentry-go"
sentryecho "github.com/getsentry/sentry-go/echo"
"github.com/joho/godotenv"
"github.com/kelseyhightower/envconfig"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
log "github.com/sirupsen/logrus"
)
type Config struct {
SentryDSN string `envconfig:"SENTRY_DSN"`
LogFilePath string `envconfig:"LOG_FILE_PATH"`
Port int `envconfig:"PORT" default:"3000"`
}
type LNResponse struct {
Lnurlp interface{} `json:"lnurlp"`
Keysend interface{} `json:"keysend"`
Nostr interface{} `json:"nostr"`
}
type GIResponse struct {
Invoice interface{} `json:"invoice"`
}
type GetJSONParams struct {
url string
wg *sync.WaitGroup
}
func GetJSON(p GetJSONParams) (interface{}, *http.Response, error) {
if p.wg != nil {
defer p.wg.Done()
}
urlPrefix := "https://getalby.com"
replacement := "http://alby-mainnet-getalbycom"
url := strings.Replace(p.url, urlPrefix, replacement, 1)
response, err := http.Get(url)
if err != nil || response.StatusCode > 300 {
return nil, response, fmt.Errorf("no details: %s - %v", p.url, err)
} else {
defer response.Body.Close()
var j interface{}
err = json.NewDecoder(response.Body).Decode(&j)
if err != nil {
return nil, response, fmt.Errorf("invalid JSON: %v", err)
} else {
return j, response, nil
}
}
}
func ToUrl(identifier string) (string, string, string, error) {
parts := strings.Split(identifier, "@")
if len(parts) != 2 {
return "", "", "", fmt.Errorf("invalid lightning address %s", identifier)
}
keysendUrl := fmt.Sprintf("https://%s/.well-known/keysend/%s", parts[1], parts[0])
lnurlpUrl := fmt.Sprintf("https://%s/.well-known/lnurlp/%s", parts[1], parts[0])
nostrUrl := fmt.Sprintf("https://%s/.well-known/nostr.json?name=%s", parts[1], parts[0])
return lnurlpUrl, keysendUrl, nostrUrl, nil
}
func main() {
c := &Config{}
logger := log.New()
logger.SetFormatter(&log.JSONFormatter{})
// Load configruation from environment variables
err := godotenv.Load(".env")
if err != nil {
logger.Infof("Failed to load .env file: %v", err)
}
err = envconfig.Process("", c)
if err != nil {
logger.Fatalf("Error loading environment variables: %v", err)
}
e := echo.New()
e.HideBanner = true
echologrus.Logger = logger
e.Use(echologrus.Middleware())
e.Use(middleware.Recover())
e.Use(middleware.RequestID())
e.Use(middleware.CORS())
// Setup exception tracking with Sentry if configured
if c.SentryDSN != "" {
if err = sentry.Init(sentry.ClientOptions{
Dsn: c.SentryDSN,
IgnoreErrors: []string{"401"},
}); err != nil {
log.Printf("sentry init error: %v", err)
}
defer sentry.Flush(2 * time.Second)
e.Use(sentryecho.New(sentryecho.Options{}))
}
e.GET("/lightning-address-details", func(c echo.Context) error {
responseBody := &LNResponse{}
var wg sync.WaitGroup
var lnurlp, keysend, nostr interface{}
var lnurlpResponse, keysendResponse, nostrResponse *http.Response
ln := c.QueryParam("ln")
lnurlpUrl, keysendUrl, nostrUrl, err := ToUrl(ln)
if err != nil {
logger.WithFields(log.Fields{
"lightning_address": ln,
}).Errorf("Failed to parse urls: %v", err)
return c.JSON(http.StatusBadRequest, &responseBody)
}
wg.Add(3)
go func() {
lnurlp, lnurlpResponse, err = GetJSON(GetJSONParams{url: lnurlpUrl, wg: &wg})
if err != nil {
logger.WithFields(log.Fields{
"lightning_address": ln,
"lnurlp_url": lnurlpUrl,
}).Errorf("Failed to fetch lnurlp response: %v", err)
} else {
responseBody.Lnurlp = lnurlp
}
}()
go func() {
keysend, keysendResponse, err = GetJSON(GetJSONParams{url: keysendUrl, wg: &wg})
if err != nil {
logger.WithFields(log.Fields{
"lightning_address": ln,
"keysend_url": keysendUrl,
}).Errorf("Failed to fetch keysend response: %v", err)
} else {
responseBody.Keysend = keysend
}
}()
go func() {
nostr, nostrResponse, err = GetJSON(GetJSONParams{url: nostrUrl, wg: &wg})
if err != nil {
logger.WithFields(log.Fields{
"lightning_address": ln,
"nostr_url": nostrUrl,
}).Errorf("Failed to fetch nostr response: %v", err)
} else {
responseBody.Nostr = nostr
}
}()
wg.Wait()
// if the requests resulted in errors return a bad request. something must be wrong with the ln address
if (lnurlpResponse == nil && keysendResponse == nil && nostrResponse == nil) ||
(lnurlpResponse.StatusCode >= 300 && keysendResponse.StatusCode >= 300 && nostrResponse.StatusCode >= 300) {
logger.WithFields(log.Fields{
"lightning_address": ln,
}).Errorf("Could not retrieve details for lightning address %v", ln)
return c.JSON(http.StatusBadRequest, &responseBody)
}
c.Response().Header().Set(echo.HeaderCacheControl, lnurlpResponse.Header.Get("Cache-Control"))
// default return response
return c.JSONPretty(http.StatusOK, &responseBody, " ")
})
e.GET("/generate-invoice", func(c echo.Context) error {
responseBody := &GIResponse{}
ln := c.QueryParam("ln")
lnurlpUrl, _, _, err := ToUrl(ln)
if err != nil {
return c.JSON(http.StatusBadRequest, &responseBody)
}
lnurlp, lnurlpResponse, err := GetJSON(GetJSONParams{url: lnurlpUrl})
if err != nil {
logger.WithFields(log.Fields{
"lightning_address": ln,
"lnurlp_url": lnurlpUrl,
}).Errorf("Failed to fetch lnurlp response: %v", err)
}
// if the request resulted in error return a bad request. something must be wrong with the ln address
if lnurlpResponse == nil {
return c.JSON(http.StatusBadRequest, &responseBody)
}
// if the response have no success
if lnurlpResponse != nil && lnurlpResponse.StatusCode > 300 {
return c.JSONPretty(lnurlpResponse.StatusCode, &responseBody, " ")
}
callback := lnurlp.(map[string]interface{})["callback"]
// if the lnurlp response doesn't have a callback to generate invoice
if callback == nil {
return c.JSON(http.StatusBadRequest, &responseBody)
}
c.QueryParams().Del("ln")
invoiceParams := c.QueryParams()
invoiceUrl, err := url.Parse(callback.(string))
if err != nil {
logger.WithFields(log.Fields{
"lightning_address": ln,
}).Errorf("Failed to parse callback url: %v", err)
return c.JSON(http.StatusBadRequest, &responseBody)
}
values := invoiceUrl.Query()
for key, val := range invoiceParams {
for _, v := range val {
values.Add(key, v)
}
}
invoiceUrl.RawQuery = values.Encode()
invoice, invoiceResponse, err := GetJSON(GetJSONParams{url: invoiceUrl.String()})
if err != nil {
logger.WithFields(log.Fields{
"lightning_address": ln,
}).Errorf("Failed to fetch invoice: %v", err)
} else {
responseBody.Invoice = invoice
}
if invoiceResponse == nil {
return c.JSON(http.StatusBadRequest, &responseBody)
}
if invoiceResponse != nil && invoiceResponse.StatusCode > 300 {
return c.JSONPretty(lnurlpResponse.StatusCode, &responseBody, " ")
}
// default return response
return c.JSONPretty(http.StatusOK, &responseBody, " ")
})
// Start server
go func() {
if err := e.Start(fmt.Sprintf(":%v", c.Port)); err != nil && err != http.ErrServerClosed {
logger.Fatal("shutting down the server", err)
}
}()
// Wait for interrupt signal to gracefully shutdown the server with a timeout of 10 seconds.
// Use a buffered channel to avoid missing signals as recommended for signal.Notify
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := e.Shutdown(ctx); err != nil {
logger.Fatal(err)
}
}