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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
|
package main
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"io"
"net/http"
"net/url"
"os"
"os/signal"
"strconv"
"sync"
"time"
"github.com/go-redis/redis/v8"
"github.com/gorilla/mux"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
var (
errBadLogic = errors.New("we should not be here")
errUnexpectedParam = errors.New("got unexpected parameter")
errUnknownDeployment = errors.New("unknown deployment kind")
)
const (
serverDeploymentType = "SERVER_DEPLOYMENT_TYPE"
coingeckoAPIURLv3 = "https://api.coingecko.com/api/v3"
coincapAPIURLv2 = "https://api.coincap.io/v2"
getTimeout = 5
httpClientTimeout = 5
serverTLSReadTimeout = 15
serverTLSWriteTimeout = 15
defaultGracefulShutdown = 15
)
// https://docs.coincap.io/
type CoinCapAssetGetResponseData struct {
ID string `json:"id"`
Rank string `json:"rank"`
Symbol string `json:"symbol"`
Name string `json:"name"`
Supply string `json:"supply"`
MaxSupply string `json:"maxSupply"`
MarketCapUsd string `json:"marketCapUsd"`
VolumeUsd24Hr string `json:"volumeUsd24Hr"`
PriceUsd string `json:"priceUsd"`
ChangePercent24Hr string `json:"changePercent24Hr"`
Vwap24Hr string `json:"vwap24Hr"`
}
type priceResponseData struct {
Name string `json:"name"`
Price float64 `json:"price"`
Unit string `json:"unit"`
Err string `json:"err"`
IsSuccessful bool `json:"isSuccessful"`
}
type CoinCapAssetGetResponse struct {
Data CoinCapAssetGetResponseData `json:"data"`
TimeStamp int64 `json:"timestamp"`
}
type HTTPHandlerFunc func(http.ResponseWriter, *http.Request)
type HTTPHandler struct {
name string
function HTTPHandlerFunc
}
type priceChanStruct struct {
name string
price float64
}
type errorChanStruct struct {
hasError bool
err error
}
func GetProxiedClient() *http.Client {
transport := &http.Transport{
DisableKeepAlives: true,
Proxy: http.ProxyFromEnvironment,
}
client := &http.Client{
Transport: transport,
Timeout: httpClientTimeout * time.Second,
CheckRedirect: nil,
Jar: nil,
}
return client
}
// OWASP: https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html
func addSecureHeaders(writer *http.ResponseWriter) {
(*writer).Header().Set("Cache-Control", "no-store")
(*writer).Header().Set("Content-Security-Policy", "default-src https;")
(*writer).Header().Set("Strict-Transport-Security", "max-age=63072000;")
(*writer).Header().Set("X-Content-Type-Options", "nosniff")
(*writer).Header().Set("X-Frame-Options", "DENY")
(*writer).Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
}
func getPriceFromCoinGecko(
ctx context.Context,
name, unit string,
wg *sync.WaitGroup,
priceChan chan<- priceChanStruct,
errChan chan<- errorChanStruct,
) {
defer wg.Done()
priceFloat := 0.
params := "/simple/price?ids=" + url.QueryEscape(name) + "&" +
"vs_currencies=" + url.QueryEscape(unit)
path := coingeckoAPIURLv3 + params
client := GetProxiedClient()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, path, nil)
if err != nil {
priceChan <- priceChanStruct{name: name, price: priceFloat}
errChan <- errorChanStruct{hasError: true, err: err}
log.Error().Err(err)
return
}
resp, err := client.Do(req)
if err != nil {
priceChan <- priceChanStruct{name: name, price: priceFloat}
errChan <- errorChanStruct{hasError: true, err: err}
log.Error().Err(err).Send()
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
priceChan <- priceChanStruct{name: name, price: priceFloat}
errChan <- errorChanStruct{hasError: true, err: err}
log.Error().Err(err).Send()
}
jsonBody := make(map[string]interface{})
err = json.Unmarshal(body, &jsonBody)
if err != nil {
priceChan <- priceChanStruct{name: name, price: priceFloat}
errChan <- errorChanStruct{hasError: true, err: err}
log.Error().Err(err).Send()
}
price, isOk := jsonBody[name].(map[string]interface{})
if !isOk {
priceChan <- priceChanStruct{name: name, price: priceFloat}
errChan <- errorChanStruct{hasError: true, err: err}
log.Error().Err(err)
return
}
log.Info().Msg(string(body))
priceFloat, isOk = price[unit].(float64)
if !isOk {
priceChan <- priceChanStruct{name: name, price: priceFloat}
errChan <- errorChanStruct{hasError: true, err: err}
log.Error().Err(err)
return
}
priceChan <- priceChanStruct{name: name, price: priceFloat}
errChan <- errorChanStruct{hasError: false, err: nil}
}
func getPriceFromCoinCap(
ctx context.Context,
name string,
wg *sync.WaitGroup,
priceChan chan<- priceChanStruct,
errChan chan<- errorChanStruct,
) {
defer wg.Done()
priceFloat := 0.
params := "/assets/" + url.QueryEscape(name)
path := coincapAPIURLv2 + params
client := GetProxiedClient()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, path, nil)
if err != nil {
priceChan <- priceChanStruct{name: name, price: priceFloat}
errChan <- errorChanStruct{hasError: true, err: err}
log.Error().Err(err)
return
}
resp, err := client.Do(req)
if err != nil {
priceChan <- priceChanStruct{name: name, price: priceFloat}
errChan <- errorChanStruct{hasError: true, err: err}
log.Error().Err(err).Send()
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
priceChan <- priceChanStruct{name: name, price: priceFloat}
errChan <- errorChanStruct{hasError: true, err: err}
log.Error().Err(err)
}
var coinCapAssetGetResponse CoinCapAssetGetResponse
err = json.Unmarshal(body, &coinCapAssetGetResponse)
if err != nil {
priceChan <- priceChanStruct{name: name, price: priceFloat}
errChan <- errorChanStruct{hasError: true, err: err}
log.Error().Err(err).Send()
}
priceFloat, err = strconv.ParseFloat(coinCapAssetGetResponse.Data.PriceUsd, 64)
if err != nil {
priceChan <- priceChanStruct{name: name, price: priceFloat}
errChan <- errorChanStruct{hasError: true, err: err}
log.Error().Err(err).Send()
}
log.Info().Msg(string(body))
priceChan <- priceChanStruct{name: name, price: priceFloat}
errChan <- errorChanStruct{hasError: false, err: nil}
}
func arbHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
if r.Method != http.MethodGet {
http.Error(w, "Method is not supported.", http.StatusNotFound)
}
addSecureHeaders(&w)
var name string
var unit string
params := r.URL.Query()
for key, value := range params {
switch key {
case "name":
name = value[0]
case "unit":
unit = value[0]
default:
log.Error().Err(errUnexpectedParam)
}
}
priceChan := make(chan priceChanStruct, 1)
errChan := make(chan errorChanStruct, 1)
var waitGroup sync.WaitGroup
ctx, cancel := context.WithTimeout(context.Background(), getTimeout*time.Second)
defer cancel()
waitGroup.Add(1)
//nolint:contextcheck
getPriceFromCoinGecko(ctx, name, unit, &waitGroup, priceChan, errChan)
waitGroup.Wait()
select {
case err := <-errChan:
if err.hasError {
log.Error().Err(err.err)
}
default:
log.Error().Err(errBadLogic).Send()
}
var price priceChanStruct
select {
case priceCh := <-priceChan:
price = priceCh
default:
log.Error().Err(errBadLogic)
}
responseData := priceResponseData{
Name: price.name,
Price: price.price,
Unit: "USD",
Err: "",
IsSuccessful: true,
}
jsonResp, err := json.Marshal(responseData)
if err != nil {
cancel()
//nolint:gocritic
log.Fatal().Err(err)
}
_, err = w.Write(jsonResp)
if err != nil {
cancel()
log.Fatal().Err(err)
}
}
func coincapHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method is not supported.", http.StatusNotFound)
}
w.Header().Add("Content-Type", "application/json")
addSecureHeaders(&w)
var name string
params := r.URL.Query()
for key, value := range params {
switch key {
case "name":
name = value[0]
default:
log.Error().Err(errUnexpectedParam).Send()
}
}
priceChan := make(chan priceChanStruct, 1)
errChan := make(chan errorChanStruct, 1)
var waitGroup sync.WaitGroup
waitGroup.Add(1)
ctx, cancel := context.WithTimeout(context.Background(), getTimeout*time.Second)
defer cancel()
getPriceFromCoinCap(ctx, name, &waitGroup, priceChan, errChan)
waitGroup.Wait()
select {
case err := <-errChan:
if err.hasError {
log.Error().Err(err.err)
}
default:
log.Error().Err(errBadLogic)
}
var price priceChanStruct
select {
case priceCh := <-priceChan:
price = priceCh
default:
log.Error().Err(errBadLogic)
}
responseData := priceResponseData{
Name: price.name,
Price: price.price,
Unit: "USD",
Err: "",
IsSuccessful: true,
}
jsonResp, err := json.Marshal(responseData)
if err != nil {
cancel()
log.Fatal().Err(err).Send()
}
_, err = w.Write(jsonResp)
if err != nil {
cancel()
log.Fatal().Err(err)
}
}
func setupLogging() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
}
func startServer(gracefulWait time.Duration,
handlers []HTTPHandler,
serverDeploymentType string, port string,
) {
route := mux.NewRouter()
cfg := &tls.Config{
MinVersion: tls.VersionTLS13,
}
srv := &http.Server{
Addr: "0.0.0.0:" + port,
WriteTimeout: time.Second * serverTLSWriteTimeout,
ReadTimeout: time.Second * serverTLSReadTimeout,
Handler: route,
TLSConfig: cfg,
}
for i := range len(handlers) {
route.HandleFunc(handlers[i].name, handlers[i].function)
}
go func() {
var certPath, keyPath string
switch os.Getenv(serverDeploymentType) {
case "deployment":
certPath = "/etc/letsencrypt/live/api.terminaldweller.com/fullchain.pem"
keyPath = "/etc/letsencrypt/live/api.terminaldweller.com/privkey.pem"
case "test":
certPath = "/certs/server.cert"
keyPath = "/certs/server.key"
default:
log.Error().Err(errUnknownDeployment).Send()
}
if err := srv.ListenAndServeTLS(certPath, keyPath); err != nil {
log.Error().Err(err)
}
}()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
ctx, cancel := context.WithTimeout(context.Background(), gracefulWait)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Error().Err(err)
}
log.Info().Msg("gracefully shut down the server")
}
func main() {
var gracefulWait time.Duration
var rdb *redis.Client
flag.DurationVar(
&gracefulWait,
"gracefulwait",
time.Second*defaultGracefulShutdown,
"the duration to wait during the graceful shutdown",
)
flagPort := flag.String("port", "8009", "determines the port the server will listen on")
redisDB := flag.Int64("redisdb", 1, "determines the db number")
redisAddress := flag.String("redisaddress", "redis:6379", "determines the address of the redis instance")
redisPassword := flag.String("redispassword", "", "determines the password of the redis db")
flag.Parse()
rdb = redis.NewClient(&redis.Options{
Addr: *redisAddress,
Password: *redisPassword,
DB: int(*redisDB),
})
defer rdb.Close()
setupLogging()
handlerFuncs := []HTTPHandler{
{name: "/crypto/v1/arb/gecko", function: arbHandler},
{name: "/crypto/v1/arb/coincap", function: coincapHandler},
}
startServer(gracefulWait, handlerFuncs, serverDeploymentType, *flagPort)
}
|