forked from thrasher-corp/gocryptotrader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.go
445 lines (385 loc) · 11.6 KB
/
websocket.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
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
package main
import (
"log"
"net/http"
"github.com/gorilla/websocket"
"github.com/thrasher-/gocryptotrader/common"
"github.com/thrasher-/gocryptotrader/config"
"github.com/thrasher-/gocryptotrader/currency"
)
// Const vars for websocket
const (
WebsocketResponseSuccess = "OK"
)
var (
wsHub *WebsocketHub
wsHubStarted bool
)
type wsCommandHandler struct {
authRequired bool
handler func(client *WebsocketClient, data interface{}) error
}
var wsHandlers = map[string]wsCommandHandler{
"auth": {authRequired: false, handler: wsAuth},
"getconfig": {authRequired: true, handler: wsGetConfig},
"saveconfig": {authRequired: true, handler: wsSaveConfig},
"getaccountinfo": {authRequired: true, handler: wsGetAccountInfo},
"gettickers": {authRequired: false, handler: wsGetTickers},
"getticker": {authRequired: false, handler: wsGetTicker},
"getorderbooks": {authRequired: false, handler: wsGetOrderbooks},
"getorderbook": {authRequired: false, handler: wsGetOrderbook},
"getexchangerates": {authRequired: false, handler: wsGetExchangeRates},
"getportfolio": {authRequired: true, handler: wsGetPortfolio},
}
// WebsocketClient stores information related to the websocket client
type WebsocketClient struct {
Hub *WebsocketHub
Conn *websocket.Conn
Authenticated bool
authFailures int
Send chan []byte
}
// WebsocketHub stores the data for managing websocket clients
type WebsocketHub struct {
Clients map[*WebsocketClient]bool
Broadcast chan []byte
Register chan *WebsocketClient
Unregister chan *WebsocketClient
}
// WebsocketEvent is the struct used for websocket events
type WebsocketEvent struct {
Exchange string `json:"exchange,omitempty"`
AssetType string `json:"assetType,omitempty"`
Event string
Data interface{}
}
// WebsocketEventResponse is the struct used for websocket event responses
type WebsocketEventResponse struct {
Event string `json:"event"`
Data interface{} `json:"data"`
Error string `json:"error"`
}
// WebsocketOrderbookTickerRequest is a struct used for ticker and orderbook
// requests
type WebsocketOrderbookTickerRequest struct {
Exchange string `json:"exchangeName"`
Currency string `json:"currency"`
AssetType string `json:"assetType"`
}
// WebsocketAuth is a struct used for
type WebsocketAuth struct {
Username string `json:"username"`
Password string `json:"password"`
}
// NewWebsocketHub Creates a new websocket hub
func NewWebsocketHub() *WebsocketHub {
return &WebsocketHub{
Broadcast: make(chan []byte),
Register: make(chan *WebsocketClient),
Unregister: make(chan *WebsocketClient),
Clients: make(map[*WebsocketClient]bool),
}
}
func (h *WebsocketHub) run() {
for {
select {
case client := <-h.Register:
h.Clients[client] = true
case client := <-h.Unregister:
if _, ok := h.Clients[client]; ok {
log.Printf("websocket: disconnected client")
delete(h.Clients, client)
close(client.Send)
}
case message := <-h.Broadcast:
for client := range h.Clients {
select {
case client.Send <- message:
default:
log.Printf("websocket: disconnected client")
close(client.Send)
delete(h.Clients, client)
}
}
}
}
}
// SendWebsocketMessage sends a websocket event to the client
func (c *WebsocketClient) SendWebsocketMessage(evt interface{}) error {
data, err := common.JSONEncode(evt)
if err != nil {
log.Printf("websocket: failed to send message: %s", err)
return err
}
c.Send <- data
return nil
}
func (c *WebsocketClient) read() {
defer func() {
c.Hub.Unregister <- c
c.Conn.Close()
}()
for {
msgType, message, err := c.Conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("websocket: client disconnected, err: %s", err)
}
break
}
if msgType == websocket.TextMessage {
var evt WebsocketEvent
err := common.JSONDecode(message, &evt)
if err != nil {
log.Printf("websocket: failed to decode JSON sent from client %s", err)
break
}
if evt.Event == "" {
log.Printf("websocket: client sent a blank event, disconnecting")
break
}
dataJSON, err := common.JSONEncode(evt.Data)
if err != nil {
log.Printf("websocket: client sent data we couldn't JSON decode")
break
}
req := common.StringToLower(evt.Event)
log.Printf("websocket: request received: %s", req)
result, ok := wsHandlers[req]
if !ok {
log.Printf("websocket: unsupported event")
continue
}
if result.authRequired && !c.Authenticated {
log.Printf("Websocket: request %s failed due to unauthenticated request on an authenticated API", evt.Event)
c.SendWebsocketMessage(WebsocketEventResponse{Event: evt.Event, Error: "unauthorised request on authenticated API"})
continue
}
err = result.handler(c, dataJSON)
if err != nil {
log.Printf("websocket: request %s failed. Error %s", evt.Event, err)
continue
}
}
}
}
func (c *WebsocketClient) write() {
defer func() {
c.Conn.Close()
}()
for {
select {
case message, ok := <-c.Send:
if !ok {
c.Conn.WriteMessage(websocket.CloseMessage, []byte{})
log.Printf("websocket: hub closed the channel")
return
}
w, err := c.Conn.NextWriter(websocket.TextMessage)
if err != nil {
log.Printf("websocket: failed to create new io.writeCloser: %s", err)
return
}
w.Write(message)
// Add queued chat messages to the current websocket message
n := len(c.Send)
for i := 0; i < n; i++ {
w.Write(<-c.Send)
}
if err := w.Close(); err != nil {
log.Printf("websocket: failed to close io.WriteCloser: %s", err)
return
}
}
}
}
// StartWebsocketHandler starts the websocket hub and routine which
// handles clients
func StartWebsocketHandler() {
if !wsHubStarted {
wsHubStarted = true
wsHub = NewWebsocketHub()
go wsHub.run()
}
}
// BroadcastWebsocketMessage meow
func BroadcastWebsocketMessage(evt WebsocketEvent) error {
data, err := common.JSONEncode(evt)
if err != nil {
return err
}
wsHub.Broadcast <- data
return nil
}
// WebsocketClientHandler upgrades the HTTP connection to a websocket
// compatible one
func WebsocketClientHandler(w http.ResponseWriter, r *http.Request) {
if !wsHubStarted {
StartWebsocketHandler()
}
connectionLimit := bot.config.Webserver.WebsocketConnectionLimit
numClients := len(wsHub.Clients)
if numClients >= connectionLimit {
log.Printf("websocket: client rejected due to websocket client limit reached. Number of clients %d. Limit %d.",
numClients, connectionLimit)
w.WriteHeader(http.StatusForbidden)
return
}
upgrader := websocket.Upgrader{
WriteBufferSize: 1024,
ReadBufferSize: 1024,
}
// Allow insecure origin if the Origin request header is present and not
// equal to the Host request header. Default to false
if bot.config.Webserver.WebsocketAllowInsecureOrigin {
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
client := &WebsocketClient{Hub: wsHub, Conn: conn, Send: make(chan []byte, 1024)}
client.Hub.Register <- client
log.Printf("websocket: client connected. Connected clients: %d. Limit %d.",
numClients+1, connectionLimit)
go client.read()
go client.write()
}
func wsAuth(client *WebsocketClient, data interface{}) error {
wsResp := WebsocketEventResponse{
Event: "auth",
}
var auth WebsocketAuth
err := common.JSONDecode(data.([]byte), &auth)
if err != nil {
wsResp.Error = err.Error()
client.SendWebsocketMessage(wsResp)
return err
}
hashPW := common.HexEncodeToString(common.GetSHA256([]byte(bot.config.Webserver.AdminPassword)))
if auth.Username == bot.config.Webserver.AdminUsername && auth.Password == hashPW {
client.Authenticated = true
wsResp.Data = WebsocketResponseSuccess
log.Println("websocket: client authenticated successfully")
return client.SendWebsocketMessage(wsResp)
}
wsResp.Error = "invalid username/password"
client.authFailures++
client.SendWebsocketMessage(wsResp)
if client.authFailures >= bot.config.Webserver.WebsocketMaxAuthFailures {
log.Printf("websocket: disconnecting client, maximum auth failures threshold reached (failures: %d limit: %d)",
client.authFailures, bot.config.Webserver.WebsocketMaxAuthFailures)
wsHub.Unregister <- client
return nil
}
log.Printf("websocket: client sent wrong username/password (failures: %d limit: %d)",
client.authFailures, bot.config.Webserver.WebsocketMaxAuthFailures)
return nil
}
func wsGetConfig(client *WebsocketClient, data interface{}) error {
wsResp := WebsocketEventResponse{
Event: "GetConfig",
Data: bot.config,
}
return client.SendWebsocketMessage(wsResp)
}
func wsSaveConfig(client *WebsocketClient, data interface{}) error {
wsResp := WebsocketEventResponse{
Event: "SaveConfig",
}
var cfg config.Config
err := common.JSONDecode(data.([]byte), &cfg)
if err != nil {
wsResp.Error = err.Error()
client.SendWebsocketMessage(wsResp)
return err
}
err = bot.config.UpdateConfig(bot.configFile, cfg)
if err != nil {
wsResp.Error = err.Error()
client.SendWebsocketMessage(wsResp)
return err
}
SetupExchanges()
wsResp.Data = WebsocketResponseSuccess
return client.SendWebsocketMessage(wsResp)
}
func wsGetAccountInfo(client *WebsocketClient, data interface{}) error {
accountInfo := GetAllEnabledExchangeAccountInfo()
wsResp := WebsocketEventResponse{
Event: "GetAccountInfo",
Data: accountInfo,
}
return client.SendWebsocketMessage(wsResp)
}
func wsGetTickers(client *WebsocketClient, data interface{}) error {
wsResp := WebsocketEventResponse{
Event: "GetTickers",
}
wsResp.Data = GetAllActiveTickers()
return client.SendWebsocketMessage(wsResp)
}
func wsGetTicker(client *WebsocketClient, data interface{}) error {
wsResp := WebsocketEventResponse{
Event: "GetTicker",
}
var tickerReq WebsocketOrderbookTickerRequest
err := common.JSONDecode(data.([]byte), &tickerReq)
if err != nil {
wsResp.Error = err.Error()
client.SendWebsocketMessage(wsResp)
return err
}
result, err := GetSpecificTicker(tickerReq.Currency,
tickerReq.Exchange, tickerReq.AssetType)
if err != nil {
wsResp.Error = err.Error()
client.SendWebsocketMessage(wsResp)
return err
}
wsResp.Data = result
return client.SendWebsocketMessage(wsResp)
}
func wsGetOrderbooks(client *WebsocketClient, data interface{}) error {
wsResp := WebsocketEventResponse{
Event: "GetOrderbooks",
}
wsResp.Data = GetAllActiveOrderbooks()
return client.SendWebsocketMessage(wsResp)
}
func wsGetOrderbook(client *WebsocketClient, data interface{}) error {
wsResp := WebsocketEventResponse{
Event: "GetOrderbook",
}
var orderbookReq WebsocketOrderbookTickerRequest
err := common.JSONDecode(data.([]byte), &orderbookReq)
if err != nil {
wsResp.Error = err.Error()
client.SendWebsocketMessage(wsResp)
return err
}
result, err := GetSpecificOrderbook(orderbookReq.Currency,
orderbookReq.Exchange, orderbookReq.AssetType)
if err != nil {
wsResp.Error = err.Error()
client.SendWebsocketMessage(wsResp)
return err
}
wsResp.Data = result
return client.SendWebsocketMessage(wsResp)
}
func wsGetExchangeRates(client *WebsocketClient, data interface{}) error {
wsResp := WebsocketEventResponse{
Event: "GetExchangeRates",
}
wsResp.Data = currency.GetExchangeRates()
return client.SendWebsocketMessage(wsResp)
}
func wsGetPortfolio(client *WebsocketClient, data interface{}) error {
wsResp := WebsocketEventResponse{
Event: "GetPortfolio",
}
wsResp.Data = bot.portfolio.GetPortfolioSummary()
return client.SendWebsocketMessage(wsResp)
}