github.com/yinchengtsinghua/golang-Eos-dpos-Ethereum@v0.0.0-20190121132951-92cc4225ed8e/rpc/json.go (about) 1 2 //此源码被清华学神尹成大魔王专业翻译分析并修改 3 //尹成QQ77025077 4 //尹成微信18510341407 5 //尹成所在QQ群721929980 6 //尹成邮箱 yinc13@mails.tsinghua.edu.cn 7 //尹成毕业于清华大学,微软区块链领域全球最有价值专家 8 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 9 //版权所有2015 Go Ethereum作者 10 //此文件是Go以太坊库的一部分。 11 // 12 //Go-Ethereum库是免费软件:您可以重新分发它和/或修改 13 //根据GNU发布的较低通用公共许可证的条款 14 //自由软件基金会,或者许可证的第3版,或者 15 //(由您选择)任何更高版本。 16 // 17 //Go以太坊图书馆的发行目的是希望它会有用, 18 //但没有任何保证;甚至没有 19 //适销性或特定用途的适用性。见 20 //GNU较低的通用公共许可证,了解更多详细信息。 21 // 22 //你应该收到一份GNU较低级别的公共许可证副本 23 //以及Go以太坊图书馆。如果没有,请参见<http://www.gnu.org/licenses/>。 24 25 package rpc 26 27 import ( 28 "bytes" 29 "encoding/json" 30 "fmt" 31 "io" 32 "reflect" 33 "strconv" 34 "strings" 35 "sync" 36 37 "github.com/ethereum/go-ethereum/log" 38 ) 39 40 const ( 41 jsonrpcVersion = "2.0" 42 serviceMethodSeparator = "_" 43 subscribeMethodSuffix = "_subscribe" 44 unsubscribeMethodSuffix = "_unsubscribe" 45 notificationMethodSuffix = "_subscription" 46 ) 47 48 type jsonRequest struct { 49 Method string `json:"method"` 50 Version string `json:"jsonrpc"` 51 Id json.RawMessage `json:"id,omitempty"` 52 Payload json.RawMessage `json:"params,omitempty"` 53 } 54 55 type jsonSuccessResponse struct { 56 Version string `json:"jsonrpc"` 57 Id interface{} `json:"id,omitempty"` 58 Result interface{} `json:"result"` 59 } 60 61 type jsonError struct { 62 Code int `json:"code"` 63 Message string `json:"message"` 64 Data interface{} `json:"data,omitempty"` 65 } 66 67 type jsonErrResponse struct { 68 Version string `json:"jsonrpc"` 69 Id interface{} `json:"id,omitempty"` 70 Error jsonError `json:"error"` 71 } 72 73 type jsonSubscription struct { 74 Subscription string `json:"subscription"` 75 Result interface{} `json:"result,omitempty"` 76 } 77 78 type jsonNotification struct { 79 Version string `json:"jsonrpc"` 80 Method string `json:"method"` 81 Params jsonSubscription `json:"params"` 82 } 83 84 //jsondec读取JSON-RPC消息并将其写入基础连接。它 85 //还支持解析参数和序列化(结果)对象。 86 type jsonCodec struct { 87 closer sync.Once //关闭关闭通道一次 88 closed chan interface{} //关闭关闭 89 decMu sync.Mutex //保护解码器 90 decode func(v interface{}) error //允许多个传输的解码器 91 encMu sync.Mutex //保护编码器 92 encode func(v interface{}) error //允许多个传输的编码器 93 rw io.ReadWriteCloser //连接 94 } 95 96 func (err *jsonError) Error() string { 97 if err.Message == "" { 98 return fmt.Sprintf("json-rpc error %d", err.Code) 99 } 100 return err.Message 101 } 102 103 func (err *jsonError) ErrorCode() int { 104 return err.Code 105 } 106 107 //Newcodec创建了一个新的RPC服务器编解码器,支持基于JSON-RPC2.0的 108 //关于显式给定的编码和解码方法。 109 func NewCodec(rwc io.ReadWriteCloser, encode, decode func(v interface{}) error) ServerCodec { 110 return &jsonCodec{ 111 closed: make(chan interface{}), 112 encode: encode, 113 decode: decode, 114 rw: rwc, 115 } 116 } 117 118 //newjsondec创建了一个新的RPC服务器编解码器,支持json-rpc 2.0。 119 func NewJSONCodec(rwc io.ReadWriteCloser) ServerCodec { 120 enc := json.NewEncoder(rwc) 121 dec := json.NewDecoder(rwc) 122 dec.UseNumber() 123 124 return &jsonCodec{ 125 closed: make(chan interface{}), 126 encode: enc.Encode, 127 decode: dec.Decode, 128 rw: rwc, 129 } 130 } 131 132 //当第一个非空白字符为“[”时,isbatch返回true 133 func isBatch(msg json.RawMessage) bool { 134 for _, c := range msg { 135 //跳过不重要的空白(http://www.ietf.org/rfc/rfc4627.txt) 136 if c == 0x20 || c == 0x09 || c == 0x0a || c == 0x0d { 137 continue 138 } 139 return c == '[' 140 } 141 return false 142 } 143 144 //readRequestHeaders将在不分析参数的情况下读取新请求。它将 145 //返回请求集合,指示这些请求是否成批 146 //窗体或传入消息无法读取/分析时出错。 147 func (c *jsonCodec) ReadRequestHeaders() ([]rpcRequest, bool, Error) { 148 c.decMu.Lock() 149 defer c.decMu.Unlock() 150 151 var incomingMsg json.RawMessage 152 if err := c.decode(&incomingMsg); err != nil { 153 return nil, false, &invalidRequestError{err.Error()} 154 } 155 if isBatch(incomingMsg) { 156 return parseBatchRequest(incomingMsg) 157 } 158 return parseRequest(incomingMsg) 159 } 160 161 //当给定的reqid对rpc方法调用无效时,checkreqid返回一个错误。 162 //有效ID是字符串、数字或空值 163 func checkReqId(reqId json.RawMessage) error { 164 if len(reqId) == 0 { 165 return fmt.Errorf("missing request id") 166 } 167 if _, err := strconv.ParseFloat(string(reqId), 64); err == nil { 168 return nil 169 } 170 var str string 171 if err := json.Unmarshal(reqId, &str); err == nil { 172 return nil 173 } 174 return fmt.Errorf("invalid request id") 175 } 176 177 //ParseRequest将解析来自给定rawMessage的单个请求。它会回来 178 //解析的请求,指示请求是批处理还是错误,当 179 //无法分析请求。 180 func parseRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) { 181 var in jsonRequest 182 if err := json.Unmarshal(incomingMsg, &in); err != nil { 183 return nil, false, &invalidMessageError{err.Error()} 184 } 185 186 if err := checkReqId(in.Id); err != nil { 187 return nil, false, &invalidMessageError{err.Error()} 188 } 189 190 //订阅是特殊的,它们将始终使用'subscripbemethod'作为有效负载中的第一个参数 191 if strings.HasSuffix(in.Method, subscribeMethodSuffix) { 192 reqs := []rpcRequest{{id: &in.Id, isPubSub: true}} 193 if len(in.Payload) > 0 { 194 //第一个参数必须是订阅名称 195 var subscribeMethod [1]string 196 if err := json.Unmarshal(in.Payload, &subscribeMethod); err != nil { 197 log.Debug(fmt.Sprintf("Unable to parse subscription method: %v\n", err)) 198 return nil, false, &invalidRequestError{"Unable to parse subscription request"} 199 } 200 201 reqs[0].service, reqs[0].method = strings.TrimSuffix(in.Method, subscribeMethodSuffix), subscribeMethod[0] 202 reqs[0].params = in.Payload 203 return reqs, false, nil 204 } 205 return nil, false, &invalidRequestError{"Unable to parse subscription request"} 206 } 207 208 if strings.HasSuffix(in.Method, unsubscribeMethodSuffix) { 209 return []rpcRequest{{id: &in.Id, isPubSub: true, 210 method: in.Method, params: in.Payload}}, false, nil 211 } 212 213 elems := strings.Split(in.Method, serviceMethodSeparator) 214 if len(elems) != 2 { 215 return nil, false, &methodNotFoundError{in.Method, ""} 216 } 217 218 //常规RPC调用 219 if len(in.Payload) == 0 { 220 return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id}}, false, nil 221 } 222 223 return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id, params: in.Payload}}, false, nil 224 } 225 226 //ParseBatchRequest将批处理请求解析为来自给定rawMessage的请求集合,指示 227 //如果请求是批处理或无法读取请求时出错。 228 func parseBatchRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) { 229 var in []jsonRequest 230 if err := json.Unmarshal(incomingMsg, &in); err != nil { 231 return nil, false, &invalidMessageError{err.Error()} 232 } 233 234 requests := make([]rpcRequest, len(in)) 235 for i, r := range in { 236 if err := checkReqId(r.Id); err != nil { 237 return nil, false, &invalidMessageError{err.Error()} 238 } 239 240 id := &in[i].Id 241 242 //订阅是特殊的,它们将始终使用'subscriptionmethod'作为有效负载中的第一个参数 243 if strings.HasSuffix(r.Method, subscribeMethodSuffix) { 244 requests[i] = rpcRequest{id: id, isPubSub: true} 245 if len(r.Payload) > 0 { 246 //第一个参数必须是订阅名称 247 var subscribeMethod [1]string 248 if err := json.Unmarshal(r.Payload, &subscribeMethod); err != nil { 249 log.Debug(fmt.Sprintf("Unable to parse subscription method: %v\n", err)) 250 return nil, false, &invalidRequestError{"Unable to parse subscription request"} 251 } 252 253 requests[i].service, requests[i].method = strings.TrimSuffix(r.Method, subscribeMethodSuffix), subscribeMethod[0] 254 requests[i].params = r.Payload 255 continue 256 } 257 258 return nil, true, &invalidRequestError{"Unable to parse (un)subscribe request arguments"} 259 } 260 261 if strings.HasSuffix(r.Method, unsubscribeMethodSuffix) { 262 requests[i] = rpcRequest{id: id, isPubSub: true, method: r.Method, params: r.Payload} 263 continue 264 } 265 266 if len(r.Payload) == 0 { 267 requests[i] = rpcRequest{id: id, params: nil} 268 } else { 269 requests[i] = rpcRequest{id: id, params: r.Payload} 270 } 271 if elem := strings.Split(r.Method, serviceMethodSeparator); len(elem) == 2 { 272 requests[i].service, requests[i].method = elem[0], elem[1] 273 } else { 274 requests[i].err = &methodNotFoundError{r.Method, ""} 275 } 276 } 277 278 return requests, true, nil 279 } 280 281 //ParseRequestArguments尝试使用给定的 282 //类型。它返回已分析的值,或者在分析失败时返回错误。 283 func (c *jsonCodec) ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, Error) { 284 if args, ok := params.(json.RawMessage); !ok { 285 return nil, &invalidParamsError{"Invalid params supplied"} 286 } else { 287 return parsePositionalArguments(args, argTypes) 288 } 289 } 290 291 //ParsePositionalArguments尝试将给定的参数解析为具有 292 //给定类型。它返回已分析的值,或者当参数不能 293 //解析。缺少的可选参数作为reflect.zero值返回。 294 func parsePositionalArguments(rawArgs json.RawMessage, types []reflect.Type) ([]reflect.Value, Error) { 295 //读取args数组的开头。 296 dec := json.NewDecoder(bytes.NewReader(rawArgs)) 297 if tok, _ := dec.Token(); tok != json.Delim('[') { 298 return nil, &invalidParamsError{"non-array args"} 299 } 300 //读取ARG。 301 args := make([]reflect.Value, 0, len(types)) 302 for i := 0; dec.More(); i++ { 303 if i >= len(types) { 304 return nil, &invalidParamsError{fmt.Sprintf("too many arguments, want at most %d", len(types))} 305 } 306 argval := reflect.New(types[i]) 307 if err := dec.Decode(argval.Interface()); err != nil { 308 return nil, &invalidParamsError{fmt.Sprintf("invalid argument %d: %v", i, err)} 309 } 310 if argval.IsNil() && types[i].Kind() != reflect.Ptr { 311 return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)} 312 } 313 args = append(args, argval.Elem()) 314 } 315 //读取args数组的结尾。 316 if _, err := dec.Token(); err != nil { 317 return nil, &invalidParamsError{err.Error()} 318 } 319 //将所有缺少的参数设置为零。 320 for i := len(args); i < len(types); i++ { 321 if types[i].Kind() != reflect.Ptr { 322 return nil, &invalidParamsError{fmt.Sprintf("missing value for required argument %d", i)} 323 } 324 args = append(args, reflect.Zero(types[i])) 325 } 326 return args, nil 327 } 328 329 //createResponse将使用给定的ID创建一个JSON-RPC成功响应,并作为结果进行回复。 330 func (c *jsonCodec) CreateResponse(id interface{}, reply interface{}) interface{} { 331 return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: reply} 332 } 333 334 //CreateErrorResponse将使用给定的ID和错误创建JSON-RPC错误响应。 335 func (c *jsonCodec) CreateErrorResponse(id interface{}, err Error) interface{} { 336 return &jsonErrResponse{Version: jsonrpcVersion, Id: id, Error: jsonError{Code: err.ErrorCode(), Message: err.Error()}} 337 } 338 339 //CreateErrorResponseWithInfo将使用给定的ID和错误创建JSON-RPC错误响应。 340 //信息是可选的,包含有关错误的其他信息。当传递空字符串时,它将被忽略。 341 func (c *jsonCodec) CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{} { 342 return &jsonErrResponse{Version: jsonrpcVersion, Id: id, 343 Error: jsonError{Code: err.ErrorCode(), Message: err.Error(), Data: info}} 344 } 345 346 //createNotification将创建一个具有给定订阅ID和事件作为参数的JSON-RPC通知。 347 func (c *jsonCodec) CreateNotification(subid, namespace string, event interface{}) interface{} { 348 return &jsonNotification{Version: jsonrpcVersion, Method: namespace + notificationMethodSuffix, 349 Params: jsonSubscription{Subscription: subid, Result: event}} 350 } 351 352 //向客户端写入消息 353 func (c *jsonCodec) Write(res interface{}) error { 354 c.encMu.Lock() 355 defer c.encMu.Unlock() 356 357 return c.encode(res) 358 } 359 360 //关闭基础连接 361 func (c *jsonCodec) Close() { 362 c.closer.Do(func() { 363 close(c.closed) 364 c.rw.Close() 365 }) 366 } 367 368 //CLOSED返回调用CLOSE时将关闭的通道 369 func (c *jsonCodec) Closed() <-chan interface{} { 370 return c.closed 371 }