Files
tendermint/rpc/lib/client/decode.go
Anton Kaliaev 44a3fbf109 rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141)
https://www.jsonrpc.org/specification

What is done in this PR:

    JSONRPCClient: validate that Response.ID matches Request.ID I wanted
    to do the same for the WSClient, but since we're sending events as
    responses, not notifications, checking IDs would require storing
    them in memory indefinitely (and we won't be able to remove them
    upon client unsubscribing because ID is different then).

    Request.ID is now optional. Notification is a Request without an ID.
    Previously "" or 0 were considered as notifications

    Remove #event suffix from ID from an event response (partially fixes
    #2949) ID must be either string, int or null AND must be equal to
    request's ID. Now, because we've implemented events as responses, WS
    clients are tripping when they see Response.ID("0#event") !=
    Request.ID("0"). Implementing events as requests would require a lot
    of time (~ 2 days to completely rewrite WS client and server)

    generate unique ID for each request

    switch to integer IDs instead of "json-client-XYZ"
    id=0 method=/subscribe
    id=0 result=...
    id=1 method=/abci_query
    id=1 result=...

> send events (resulting from /subscribe) as requests+notifications (not
responses)

this will require a lot of work. probably not worth it

* rpc: generate an unique ID for each request
in conformance with JSON-RPC spec

* WSClient: check for unsolicited responses

* fix golangci warnings

* save commit

* fix errors

* remove ID from responses from subscribe
Refs #2949

* clients are safe for concurrent access

* tm-bench: switch to int ID

* fixes after my own review

* comment out sentIDs in WSClient
see commit body for the reason

* remove body.Close
it will be closed automatically

* stop ws connection outside of write/read routines
also, use t.Rate in tm-bench indexer when calculating ID

fix gocritic issues

* update swagger.yaml

* Apply suggestions from code review

* fix stylecheck and golint linter warnings

* update changelog

* update changelog2
2019-11-15 14:16:04 +04:00

130 lines
3.2 KiB
Go

package rpcclient
import (
"encoding/json"
"github.com/pkg/errors"
amino "github.com/tendermint/go-amino"
types "github.com/tendermint/tendermint/rpc/lib/types"
)
func unmarshalResponseBytes(
cdc *amino.Codec,
responseBytes []byte,
expectedID types.JSONRPCIntID,
result interface{},
) (interface{}, error) {
// Read response. If rpc/core/types is imported, the result will unmarshal
// into the correct type.
response := &types.RPCResponse{}
if err := json.Unmarshal(responseBytes, response); err != nil {
return nil, errors.Wrap(err, "error unmarshalling")
}
if response.Error != nil {
return nil, response.Error
}
if err := validateAndVerifyID(response, expectedID); err != nil {
return nil, errors.Wrap(err, "wrong ID")
}
// Unmarshal the RawMessage into the result.
if err := cdc.UnmarshalJSON(response.Result, result); err != nil {
return nil, errors.Wrap(err, "error unmarshalling result")
}
return result, nil
}
func unmarshalResponseBytesArray(
cdc *amino.Codec,
responseBytes []byte,
expectedIDs []types.JSONRPCIntID,
results []interface{},
) ([]interface{}, error) {
var (
responses []types.RPCResponse
)
if err := json.Unmarshal(responseBytes, &responses); err != nil {
return nil, errors.Wrap(err, "error unmarshalling")
}
// No response error checking here as there may be a mixture of successful
// and unsuccessful responses.
if len(results) != len(responses) {
return nil, errors.Errorf(
"expected %d result objects into which to inject responses, but got %d",
len(responses),
len(results),
)
}
// Intersect IDs from responses with expectedIDs.
ids := make([]types.JSONRPCIntID, len(responses))
var ok bool
for i, resp := range responses {
ids[i], ok = resp.ID.(types.JSONRPCIntID)
if !ok {
return nil, errors.Errorf("expected JSONRPCIntID, got %T", resp.ID)
}
}
if err := validateResponseIDs(ids, expectedIDs); err != nil {
return nil, errors.Wrap(err, "wrong IDs")
}
for i := 0; i < len(responses); i++ {
if err := cdc.UnmarshalJSON(responses[i].Result, results[i]); err != nil {
return nil, errors.Wrapf(err, "error unmarshalling #%d result", i)
}
}
return results, nil
}
func validateResponseIDs(ids, expectedIDs []types.JSONRPCIntID) error {
m := make(map[types.JSONRPCIntID]bool, len(expectedIDs))
for _, expectedID := range expectedIDs {
m[expectedID] = true
}
for i, id := range ids {
if m[id] {
delete(m, id)
} else {
return errors.Errorf("unsolicited ID #%d: %v", i, id)
}
}
return nil
}
// From the JSON-RPC 2.0 spec:
// id: It MUST be the same as the value of the id member in the Request Object.
func validateAndVerifyID(res *types.RPCResponse, expectedID types.JSONRPCIntID) error {
if err := validateResponseID(res.ID); err != nil {
return err
}
if expectedID != res.ID.(types.JSONRPCIntID) { // validateResponseID ensured res.ID has the right type
return errors.Errorf("response ID (%d) does not match request ID (%d)", res.ID, expectedID)
}
return nil
}
func validateResponseID(id interface{}) error {
if id == nil {
return errors.New("no ID")
}
_, ok := id.(types.JSONRPCIntID)
if !ok {
return errors.Errorf("expected JSONRPCIntID, but got: %T", id)
}
return nil
}