forked from b2network/b2-zkevm-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
301 lines (256 loc) · 8.42 KB
/
handler.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
package jsonrpc
import (
"encoding/json"
"fmt"
"net/http"
"reflect"
"strings"
"unicode"
"github.com/0xPolygonHermez/zkevm-node/jsonrpc/types"
"github.com/0xPolygonHermez/zkevm-node/log"
)
const (
requiredReturnParamsPerFn = 2
)
type serviceData struct {
sv reflect.Value
funcMap map[string]*funcData
}
type funcData struct {
inNum int
reqt []reflect.Type
fv reflect.Value
isDyn bool
}
func (f *funcData) numParams() int {
return f.inNum - 1
}
type handleRequest struct {
types.Request
wsConn *concurrentWsConn
HttpRequest *http.Request
}
// Handler manage services to handle jsonrpc requests
//
// Services are public structures containing public methods
// matching the name of the jsonrpc method.
//
// Services must be registered with a prefix to identify the
// service and its methods, for example a service registered
// with a prefix `eth` will have all the public methods exposed
// as eth_<methodName> through the json rpc server.
//
// Go public methods requires the first char of its name to be
// in uppercase, but the exposition of the method will consider
// it to lower case, for example a method `func MyMethod()`
// provided by the service registered with `eth` prefix will
// be triggered when the method eth_myMethod is specified
//
// the public methods must follow the conventions:
// - return interface{}, rpcError
// - if the method depend on a Web Socket connection, it must be the first parameters as f(*websocket.Conn)
// - parameter types must match the type of the data provided for the method
//
// check the `eth.go` file for more example on how the methods are implemented
type Handler struct {
serviceMap map[string]*serviceData
}
func newJSONRpcHandler() *Handler {
handler := &Handler{
serviceMap: map[string]*serviceData{},
}
return handler
}
// Handle is the function that knows which and how a function should
// be executed when a JSON RPC request is received
func (h *Handler) Handle(req handleRequest) types.Response {
log := log.WithFields("method", req.Method, "requestId", req.ID)
log.Debugf("request params %v", string(req.Params))
service, fd, err := h.getFnHandler(req.Request)
if err != nil {
return types.NewResponse(req.Request, nil, err)
}
inArgsOffset := 0
inArgs := make([]reflect.Value, fd.inNum)
inArgs[0] = service.sv
requestHasWebSocketConn := req.wsConn != nil
funcHasMoreThanOneInputParams := len(fd.reqt) > 1
firstFuncParamIsWebSocketConn := false
firstFuncParamIsHttpRequest := false
if funcHasMoreThanOneInputParams {
firstFuncParamIsWebSocketConn = fd.reqt[1].AssignableTo(reflect.TypeOf(&concurrentWsConn{}))
firstFuncParamIsHttpRequest = fd.reqt[1].AssignableTo(reflect.TypeOf(&http.Request{}))
}
if requestHasWebSocketConn && firstFuncParamIsWebSocketConn {
inArgs[1] = reflect.ValueOf(req.wsConn)
inArgsOffset++
} else if firstFuncParamIsHttpRequest {
// If in the future one endponit needs to have both a websocket connection and an http request
// we will need to modify this code to properly handle it
inArgs[1] = reflect.ValueOf(req.HttpRequest)
inArgsOffset++
}
// check params passed by request match function params
var testStruct []interface{}
if err := json.Unmarshal(req.Params, &testStruct); err == nil && len(testStruct) > fd.numParams() {
return types.NewResponse(req.Request, nil, types.NewRPCError(types.InvalidParamsErrorCode, fmt.Sprintf("too many arguments, want at most %d", fd.numParams())))
}
inputs := make([]interface{}, fd.numParams()-inArgsOffset)
for i := inArgsOffset; i < fd.inNum-1; i++ {
val := reflect.New(fd.reqt[i+1])
inputs[i-inArgsOffset] = val.Interface()
inArgs[i+1] = val.Elem()
}
if fd.numParams() > 0 {
if err := json.Unmarshal(req.Params, &inputs); err != nil {
return types.NewResponse(req.Request, nil, types.NewRPCError(types.InvalidParamsErrorCode, "Invalid Params"))
}
}
output := fd.fv.Call(inArgs)
if err := getError(output[1]); err != nil {
log.Infof("failed call: [%v]%v. Params: %v", err.ErrorCode(), err.Error(), string(req.Params))
return types.NewResponse(req.Request, nil, err)
}
var data []byte
res := output[0].Interface()
if res != nil {
d, _ := json.Marshal(res)
data = d
}
return types.NewResponse(req.Request, data, nil)
}
// HandleWs handle websocket requests
func (h *Handler) HandleWs(reqBody []byte, wsConn *concurrentWsConn, httpReq *http.Request) ([]byte, error) {
log.Debugf("WS message received: %v", string(reqBody))
var req types.Request
if err := json.Unmarshal(reqBody, &req); err != nil {
return types.NewResponse(req, nil, types.NewRPCError(types.InvalidRequestErrorCode, "Invalid json request")).Bytes()
}
handleReq := handleRequest{
Request: req,
wsConn: wsConn,
HttpRequest: httpReq,
}
return h.Handle(handleReq).Bytes()
}
// RemoveFilterByWsConn uninstalls the filter attached to this websocket connection
func (h *Handler) RemoveFilterByWsConn(wsConn *concurrentWsConn) {
service, ok := h.serviceMap[APIEth]
if !ok {
return
}
ethEndpointsInterface := service.sv.Interface()
if ethEndpointsInterface == nil {
log.Errorf("failed to get ETH endpoint interface")
}
ethEndpoints := ethEndpointsInterface.(*EthEndpoints)
if ethEndpoints == nil {
log.Errorf("failed to get ETH endpoint instance")
return
}
err := ethEndpoints.uninstallFilterByWSConn(wsConn)
if err != nil {
log.Errorf("failed to uninstall filter by web socket connection:, %v", err)
return
}
}
func (h *Handler) registerService(service Service) {
st := reflect.TypeOf(service.Service)
if st.Kind() == reflect.Struct {
panic(fmt.Sprintf("jsonrpc: service '%s' must be a pointer to struct", service.Name))
}
funcMap := make(map[string]*funcData)
for i := 0; i < st.NumMethod(); i++ {
mv := st.Method(i)
if mv.PkgPath != "" {
// skip unexported methods
continue
}
name := lowerCaseFirst(mv.Name)
funcName := service.Name + "_" + name
fd := &funcData{
fv: mv.Func,
}
var err error
if fd.inNum, fd.reqt, err = validateFunc(funcName, fd.fv, true); err != nil {
panic(fmt.Sprintf("jsonrpc: %s", err))
}
// check if last item is a pointer
if fd.numParams() != 0 {
last := fd.reqt[fd.numParams()]
if last.Kind() == reflect.Ptr {
fd.isDyn = true
}
}
funcMap[name] = fd
}
h.serviceMap[service.Name] = &serviceData{
sv: reflect.ValueOf(service.Service),
funcMap: funcMap,
}
}
func (h *Handler) getFnHandler(req types.Request) (*serviceData, *funcData, types.Error) {
methodNotFoundErrorMessage := fmt.Sprintf("the method %s does not exist/is not available", req.Method)
callName := strings.SplitN(req.Method, "_", 2) //nolint:gomnd
if len(callName) != 2 { //nolint:gomnd
return nil, nil, types.NewRPCError(types.NotFoundErrorCode, methodNotFoundErrorMessage)
}
serviceName, funcName := callName[0], callName[1]
service, ok := h.serviceMap[serviceName]
if !ok {
log.Infof("Method %s not found", req.Method)
return nil, nil, types.NewRPCError(types.NotFoundErrorCode, methodNotFoundErrorMessage)
}
fd, ok := service.funcMap[funcName]
if !ok {
return nil, nil, types.NewRPCError(types.NotFoundErrorCode, methodNotFoundErrorMessage)
}
return service, fd, nil
}
func validateFunc(funcName string, fv reflect.Value, isMethod bool) (inNum int, reqt []reflect.Type, err error) {
if funcName == "" {
err = fmt.Errorf("getBlockNumByArg cannot be empty")
return
}
ft := fv.Type()
if ft.Kind() != reflect.Func {
err = fmt.Errorf("function '%s' must be a function instead of %s", funcName, ft)
return
}
inNum = ft.NumIn()
outNum := ft.NumOut()
if outNum != requiredReturnParamsPerFn {
err = fmt.Errorf("unexpected number of output arguments in the function '%s': %d. Expected 2", funcName, outNum)
return
}
if !isRPCErrorType(ft.Out(1)) {
err = fmt.Errorf("unexpected type for the second return value of the function '%s': '%s'. Expected '%s'", funcName, ft.Out(1), rpcErrType)
return
}
reqt = make([]reflect.Type, inNum)
for i := 0; i < inNum; i++ {
reqt[i] = ft.In(i)
}
return
}
var rpcErrType = reflect.TypeOf((*types.Error)(nil)).Elem()
func isRPCErrorType(t reflect.Type) bool {
return t.Implements(rpcErrType)
}
func getError(v reflect.Value) types.Error {
if v.IsNil() {
return nil
}
switch vt := v.Interface().(type) {
case *types.RPCError:
return vt
default:
return types.NewRPCError(types.DefaultErrorCode, "runtime error")
}
}
func lowerCaseFirst(str string) string {
for i, v := range str {
return string(unicode.ToLower(v)) + str[i+1:]
}
return ""
}