forked from DNAProject/DNA
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
471 lines (434 loc) · 12.8 KB
/
server.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
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
/*
* Copyright (C) 2018 The DNA Authors
* This file is part of The DNA library.
*
* The DNA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The DNA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with The DNA. If not, see <http://www.gnu.org/licenses/>.
*/
// Package websocket privides websocket server handler
package websocket
import (
"context"
"crypto/tls"
"encoding/json"
"net"
"net/http"
"strconv"
"sync"
"time"
"github.com/dnaproject2/DNA/common"
cfg "github.com/dnaproject2/DNA/common/config"
"github.com/dnaproject2/DNA/common/log"
Err "github.com/dnaproject2/DNA/http/base/error"
"github.com/dnaproject2/DNA/http/base/rest"
"github.com/dnaproject2/DNA/http/websocket/session"
"github.com/gorilla/websocket"
)
const (
WSTOPIC_EVENT = 1
WSTOPIC_JSON_BLOCK = 2
WSTOPIC_RAW_BLOCK = 3
WSTOPIC_TXHASHS = 4
)
type handler func(map[string]interface{}) map[string]interface{}
type Handler struct {
handler handler
pushFlag bool
}
//subscribe event for client
type subscribe struct {
ContractsFilter []string `json:"ContractsFilter"`
SubscribeEvent bool `json:"SubscribeEvent"`
SubscribeJsonBlock bool `json:"SubscribeJsonBlock"`
SubscribeRawBlock bool `json:"SubscribeRawBlock"`
SubscribeBlockTxHashs bool `json:"SubscribeBlockTxHashs"`
}
type WsServer struct {
sync.RWMutex
Upgrader websocket.Upgrader
listener net.Listener
server *http.Server
SessionList *session.SessionList // websocket sesseionlist
ActionMap map[string]Handler //handler functions
TxHashMap map[string]string //key: txHash value:sessionid
SubscribeMap map[string]subscribe //key: sessionId value:subscribeInfo
}
//init websocket server
func InitWsServer() *WsServer {
ws := &WsServer{
Upgrader: websocket.Upgrader{},
SessionList: session.NewSessionList(),
TxHashMap: make(map[string]string),
SubscribeMap: make(map[string]subscribe),
}
return ws
}
//start websocket server
func (self *WsServer) Start() error {
wsPort := int(cfg.DefConfig.Ws.HttpWsPort)
if wsPort == 0 {
log.Error("Not configure HttpWsPort port ")
return nil
}
self.registryMethod()
self.Upgrader.CheckOrigin = func(r *http.Request) bool {
return true
}
tlsFlag := false
if tlsFlag || wsPort%1000 == rest.TLS_PORT {
var err error
self.listener, err = self.initTlsListen()
if err != nil {
log.Error("Https Cert: ", err.Error())
return err
}
} else {
var err error
self.listener, err = net.Listen("tcp", ":"+strconv.Itoa(wsPort))
if err != nil {
log.Fatal("net.Listen: ", err.Error())
return err
}
}
var done = make(chan bool)
go self.checkSessionsTimeout(done)
self.server = &http.Server{Handler: http.HandlerFunc(self.webSocketHandler)}
err := self.server.Serve(self.listener)
done <- true
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
return err
}
return nil
}
//registry handler method
func (self *WsServer) registryMethod() {
heartbeat := func(cmd map[string]interface{}) map[string]interface{} {
resp := rest.ResponsePack(Err.SUCCESS)
self.Lock()
defer self.Unlock()
sessionId, _ := cmd["SessionId"].(string)
sub := self.SubscribeMap[sessionId]
resp["Action"] = "heartbeat"
resp["Result"] = sub
return resp
}
subscribe := func(cmd map[string]interface{}) map[string]interface{} {
resp := rest.ResponsePack(Err.SUCCESS)
self.Lock()
defer self.Unlock()
sessionId, _ := cmd["SessionId"].(string)
sub := self.SubscribeMap[sessionId]
if b, ok := cmd["SubscribeEvent"].(bool); ok {
sub.SubscribeEvent = b
}
if b, ok := cmd["SubscribeJsonBlock"].(bool); ok {
sub.SubscribeJsonBlock = b
}
if b, ok := cmd["SubscribeRawBlock"].(bool); ok {
sub.SubscribeRawBlock = b
}
if b, ok := cmd["SubscribeBlockTxHashs"].(bool); ok {
sub.SubscribeBlockTxHashs = b
}
if ctsf, ok := cmd["ContractsFilter"].([]interface{}); ok {
sub.ContractsFilter = []string{}
for _, v := range ctsf {
if addr, k := v.(string); k {
sub.ContractsFilter = append(sub.ContractsFilter, addr)
}
}
}
self.SubscribeMap[sessionId] = sub
resp["Action"] = "subscribe"
resp["Result"] = sub
return resp
}
getsessioncount := func(cmd map[string]interface{}) map[string]interface{} {
resp := rest.ResponsePack(Err.SUCCESS)
resp["Action"] = "getsessioncount"
resp["Result"] = self.SessionList.GetSessionCount()
return resp
}
actionMap := map[string]Handler{
"getblockheightbytxhash": {handler: rest.GetBlockHeightByTxHash},
"getsmartcodeeventbyhash": {handler: rest.GetSmartCodeEventByTxHash},
"getsmartcodeeventbyheight": {handler: rest.GetSmartCodeEventTxsByHeight},
"getcontract": {handler: rest.GetContractState},
"getbalance": {handler: rest.GetBalance},
"getconnectioncount": {handler: rest.GetConnectionCount},
"getblockbyheight": {handler: rest.GetBlockByHeight},
"getblockhash": {handler: rest.GetBlockHash},
"getblockbyhash": {handler: rest.GetBlockByHash},
"getblockheight": {handler: rest.GetBlockHeight},
"gettransaction": {handler: rest.GetTransactionByHash},
"sendrawtransaction": {handler: rest.SendRawTransaction, pushFlag: true},
"heartbeat": {handler: heartbeat},
"subscribe": {handler: subscribe},
"getstorage": {handler: rest.GetStorage},
"getallowance": {handler: rest.GetAllowance},
"getmerkleproof": {handler: rest.GetMerkleProof},
"getblocktxsbyheight": {handler: rest.GetBlockTxsByHeight},
"getgasprice": {handler: rest.GetGasPrice},
"getunboundong": {handler: rest.GetUnboundOng},
"getgrantong": {handler: rest.GetGrantOng},
"getmempooltxcount": {handler: rest.GetMemPoolTxCount},
"getmempooltxstate": {handler: rest.GetMemPoolTxState},
"getversion": {handler: rest.GetNodeVersion},
"getnetworkid": {handler: rest.GetNetworkId},
"getsessioncount": {handler: getsessioncount},
}
self.ActionMap = actionMap
}
func (self *WsServer) Stop() {
if self.server != nil {
self.server.Shutdown(context.Background())
log.Infof("Close websocket ")
}
}
func (self *WsServer) Restart() {
go func() {
time.Sleep(time.Second)
self.Stop()
time.Sleep(time.Second)
go self.Start()
}()
}
//check sessions timeout,if expire close the session
func (self *WsServer) checkSessionsTimeout(done chan bool) {
ticker := time.NewTicker(time.Second * 10)
defer ticker.Stop()
for {
select {
case <-ticker.C:
var closeList []*session.Session
self.SessionList.ForEachSession(func(v *session.Session) {
if v.SessionTimeoverCheck() {
resp := rest.ResponsePack(Err.SESSION_EXPIRED)
v.Send(marshalResp(resp))
closeList = append(closeList, v)
}
})
for _, s := range closeList {
self.SessionList.CloseSession(s)
}
case <-done:
return
}
}
}
func (self *WsServer) webSocketHandler(w http.ResponseWriter, r *http.Request) {
wsConn, err := self.Upgrader.Upgrade(w, r, nil)
wsConn.SetReadLimit(1024 * 1024)
if err != nil {
log.Error("websocket Upgrader: ", err)
return
}
defer wsConn.Close()
nsSession, err := self.SessionList.NewSession(wsConn)
if err != nil {
log.Error("websocket NewSession:", err)
return
}
defer func() {
self.deleteTxHashes(nsSession.GetSessionId())
self.deleteSubscribe(nsSession.GetSessionId())
self.SessionList.CloseSession(nsSession)
if err := recover(); err != nil {
log.Fatal("websocket recover:", err)
}
}()
for {
_, bysMsg, err := wsConn.ReadMessage()
if err == nil {
if self.OnDataHandle(nsSession, bysMsg, r) {
nsSession.UpdateActiveTime()
}
continue
}
e, ok := err.(net.Error)
if !ok || !e.Timeout() {
log.Infof("websocket conn:", err)
return
}
}
}
func (self *WsServer) IsValidMsg(reqMsg map[string]interface{}) bool {
if _, ok := reqMsg["Hash"].(string); !ok && reqMsg["Hash"] != nil {
return false
}
if _, ok := reqMsg["Addr"].(string); !ok && reqMsg["Addr"] != nil {
return false
}
if _, ok := reqMsg["Assetid"].(string); !ok && reqMsg["Assetid"] != nil {
return false
}
return true
}
func (self *WsServer) OnDataHandle(curSession *session.Session, bysMsg []byte, r *http.Request) bool {
var req = make(map[string]interface{})
if err := json.Unmarshal(bysMsg, &req); err != nil {
resp := rest.ResponsePack(Err.ILLEGAL_DATAFORMAT)
curSession.Send(marshalResp(resp))
log.Infof("websocket OnDataHandle:", err)
return false
}
actionName, ok := req["Action"].(string)
if !ok {
resp := rest.ResponsePack(Err.INVALID_METHOD)
curSession.Send(marshalResp(resp))
return false
}
action, ok := self.ActionMap[actionName]
if !ok {
resp := rest.ResponsePack(Err.INVALID_METHOD)
curSession.Send(marshalResp(resp))
return false
}
if !self.IsValidMsg(req) {
resp := rest.ResponsePack(Err.INVALID_PARAMS)
curSession.Send(marshalResp(resp))
return true
}
if height, ok := req["Height"].(float64); ok {
req["Height"] = strconv.FormatInt(int64(height), 10)
}
if raw, ok := req["Raw"].(float64); ok {
req["Raw"] = strconv.FormatInt(int64(raw), 10)
}
req["SessionId"] = curSession.GetSessionId()
resp := action.handler(req)
resp["Action"] = actionName
resp["Id"] = req["Id"]
if action.pushFlag {
if error, _ := resp["Error"].(int64); ok && error == 0 {
if txHash, ok := resp["Result"].(string); ok && len(txHash) == common.UINT256_SIZE*2 {
//delete timeover txhashs
txhashs := curSession.RemoveTimeoverTxHashes()
self.Lock()
defer self.Unlock()
for _, v := range txhashs {
delete(self.TxHashMap, v.TxHash)
}
//add new txhash
self.TxHashMap[txHash] = curSession.GetSessionId()
curSession.AppendTxHash(txHash)
}
}
}
curSession.Send(marshalResp(resp))
return true
}
func (self *WsServer) InsertTxHashMap(txhash string, sessionid string) {
self.Lock()
defer self.Unlock()
self.TxHashMap[txhash] = sessionid
}
func (self *WsServer) deleteTxHashes(sessionId string) {
self.Lock()
defer self.Unlock()
for k, v := range self.TxHashMap {
if v == sessionId {
delete(self.TxHashMap, k)
}
}
}
func (self *WsServer) deleteSubscribe(sessionId string) {
self.Lock()
defer self.Unlock()
delete(self.SubscribeMap, sessionId)
}
func marshalResp(resp map[string]interface{}) []byte {
resp["Desc"] = Err.ErrMap[resp["Error"].(int64)]
data, err := json.Marshal(resp)
if err != nil {
log.Infof("Websocket marshal json error:", err)
return nil
}
return data
}
func (self *WsServer) PushTxResult(contractAddrs map[string]bool, txHashStr string, resp map[string]interface{}) {
self.Lock()
sessionId := self.TxHashMap[txHashStr]
delete(self.TxHashMap, txHashStr)
//avoid twice, will send in BroadcastToSubscribers
sub := self.SubscribeMap[sessionId]
if sub.SubscribeEvent {
if len(sub.ContractsFilter) == 0 {
self.Unlock()
return
}
for _, addr := range sub.ContractsFilter {
if contractAddrs[addr] {
self.Unlock()
return
}
}
}
self.Unlock()
s := self.SessionList.GetSessionById(sessionId)
if s != nil {
s.Send(marshalResp(resp))
}
}
func (self *WsServer) BroadcastToSubscribers(contractAddrs map[string]bool, sub int, resp map[string]interface{}) {
// broadcast SubscribeMap
self.Lock()
defer self.Unlock()
data := marshalResp(resp)
for sid, v := range self.SubscribeMap {
s := self.SessionList.GetSessionById(sid)
if s == nil {
continue
}
if sub == WSTOPIC_JSON_BLOCK && v.SubscribeJsonBlock {
s.Send(data)
} else if sub == WSTOPIC_RAW_BLOCK && v.SubscribeRawBlock {
s.Send(data)
} else if sub == WSTOPIC_TXHASHS && v.SubscribeBlockTxHashs {
s.Send(data)
} else if sub == WSTOPIC_EVENT && v.SubscribeEvent {
if len(v.ContractsFilter) == 0 {
s.Send(data)
continue
}
for _, addr := range v.ContractsFilter {
if contractAddrs[addr] {
s.Send(data)
break
}
}
}
}
}
func (self *WsServer) initTlsListen() (net.Listener, error) {
certPath := cfg.DefConfig.Ws.HttpCertPath
keyPath := cfg.DefConfig.Ws.HttpKeyPath
// load cert
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
log.Error("load keys fail", err)
return nil, err
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
}
wsPort := strconv.Itoa(int(cfg.DefConfig.Ws.HttpWsPort))
log.Info("TLS listen port is ", wsPort)
listener, err := tls.Listen("tcp", ":"+wsPort, tlsConfig)
if err != nil {
log.Error(err)
return nil, err
}
return listener, nil
}