You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

187 lines
5.0 KiB

6 years ago
6 years ago
6 years ago
9 years ago
6 years ago
9 years ago
7 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
7 years ago
  1. package rpctypes
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "strings"
  7. "github.com/pkg/errors"
  8. amino "github.com/tendermint/go-amino"
  9. tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
  10. )
  11. //----------------------------------------
  12. // REQUEST
  13. type RPCRequest struct {
  14. JSONRPC string `json:"jsonrpc"`
  15. ID string `json:"id"`
  16. Method string `json:"method"`
  17. Params json.RawMessage `json:"params"` // must be map[string]interface{} or []interface{}
  18. }
  19. func NewRPCRequest(id string, method string, params json.RawMessage) RPCRequest {
  20. return RPCRequest{
  21. JSONRPC: "2.0",
  22. ID: id,
  23. Method: method,
  24. Params: params,
  25. }
  26. }
  27. func (req RPCRequest) String() string {
  28. return fmt.Sprintf("[%s %s]", req.ID, req.Method)
  29. }
  30. func MapToRequest(cdc *amino.Codec, id string, method string, params map[string]interface{}) (RPCRequest, error) {
  31. var params_ = make(map[string]json.RawMessage, len(params))
  32. for name, value := range params {
  33. valueJSON, err := cdc.MarshalJSON(value)
  34. if err != nil {
  35. return RPCRequest{}, err
  36. }
  37. params_[name] = valueJSON
  38. }
  39. payload, err := json.Marshal(params_) // NOTE: Amino doesn't handle maps yet.
  40. if err != nil {
  41. return RPCRequest{}, err
  42. }
  43. request := NewRPCRequest(id, method, payload)
  44. return request, nil
  45. }
  46. func ArrayToRequest(cdc *amino.Codec, id string, method string, params []interface{}) (RPCRequest, error) {
  47. var params_ = make([]json.RawMessage, len(params))
  48. for i, value := range params {
  49. valueJSON, err := cdc.MarshalJSON(value)
  50. if err != nil {
  51. return RPCRequest{}, err
  52. }
  53. params_[i] = valueJSON
  54. }
  55. payload, err := json.Marshal(params_) // NOTE: Amino doesn't handle maps yet.
  56. if err != nil {
  57. return RPCRequest{}, err
  58. }
  59. request := NewRPCRequest(id, method, payload)
  60. return request, nil
  61. }
  62. //----------------------------------------
  63. // RESPONSE
  64. type RPCError struct {
  65. Code int `json:"code"`
  66. Message string `json:"message"`
  67. Data string `json:"data,omitempty"`
  68. }
  69. func (err RPCError) Error() string {
  70. const baseFormat = "RPC error %v - %s"
  71. if err.Data != "" {
  72. return fmt.Sprintf(baseFormat+": %s", err.Code, err.Message, err.Data)
  73. }
  74. return fmt.Sprintf(baseFormat, err.Code, err.Message)
  75. }
  76. type RPCResponse struct {
  77. JSONRPC string `json:"jsonrpc"`
  78. ID string `json:"id"`
  79. Result json.RawMessage `json:"result,omitempty"`
  80. Error *RPCError `json:"error,omitempty"`
  81. }
  82. func NewRPCSuccessResponse(cdc *amino.Codec, id string, res interface{}) RPCResponse {
  83. var rawMsg json.RawMessage
  84. if res != nil {
  85. var js []byte
  86. js, err := cdc.MarshalJSON(res)
  87. if err != nil {
  88. return RPCInternalError(id, errors.Wrap(err, "Error marshalling response"))
  89. }
  90. rawMsg = json.RawMessage(js)
  91. }
  92. return RPCResponse{JSONRPC: "2.0", ID: id, Result: rawMsg}
  93. }
  94. func NewRPCErrorResponse(id string, code int, msg string, data string) RPCResponse {
  95. return RPCResponse{
  96. JSONRPC: "2.0",
  97. ID: id,
  98. Error: &RPCError{Code: code, Message: msg, Data: data},
  99. }
  100. }
  101. func (resp RPCResponse) String() string {
  102. if resp.Error == nil {
  103. return fmt.Sprintf("[%s %v]", resp.ID, resp.Result)
  104. }
  105. return fmt.Sprintf("[%s %s]", resp.ID, resp.Error)
  106. }
  107. func RPCParseError(id string, err error) RPCResponse {
  108. return NewRPCErrorResponse(id, -32700, "Parse error. Invalid JSON", err.Error())
  109. }
  110. func RPCInvalidRequestError(id string, err error) RPCResponse {
  111. return NewRPCErrorResponse(id, -32600, "Invalid Request", err.Error())
  112. }
  113. func RPCMethodNotFoundError(id string) RPCResponse {
  114. return NewRPCErrorResponse(id, -32601, "Method not found", "")
  115. }
  116. func RPCInvalidParamsError(id string, err error) RPCResponse {
  117. return NewRPCErrorResponse(id, -32602, "Invalid params", err.Error())
  118. }
  119. func RPCInternalError(id string, err error) RPCResponse {
  120. return NewRPCErrorResponse(id, -32603, "Internal error", err.Error())
  121. }
  122. func RPCServerError(id string, err error) RPCResponse {
  123. return NewRPCErrorResponse(id, -32000, "Server error", err.Error())
  124. }
  125. //----------------------------------------
  126. // *wsConnection implements this interface.
  127. type WSRPCConnection interface {
  128. GetRemoteAddr() string
  129. WriteRPCResponse(resp RPCResponse)
  130. TryWriteRPCResponse(resp RPCResponse) bool
  131. GetEventSubscriber() EventSubscriber
  132. Codec() *amino.Codec
  133. }
  134. // EventSubscriber mirros tendermint/tendermint/types.EventBusSubscriber
  135. type EventSubscriber interface {
  136. Subscribe(ctx context.Context, subscriber string, query tmpubsub.Query, out chan<- interface{}) error
  137. Unsubscribe(ctx context.Context, subscriber string, query tmpubsub.Query) error
  138. UnsubscribeAll(ctx context.Context, subscriber string) error
  139. }
  140. // websocket-only RPCFuncs take this as the first parameter.
  141. type WSRPCContext struct {
  142. Request RPCRequest
  143. WSRPCConnection
  144. }
  145. //----------------------------------------
  146. // SOCKETS
  147. //
  148. // Determine if its a unix or tcp socket.
  149. // If tcp, must specify the port; `0.0.0.0` will return incorrectly as "unix" since there's no port
  150. // TODO: deprecate
  151. func SocketType(listenAddr string) string {
  152. socketType := "unix"
  153. if len(strings.Split(listenAddr, ":")) >= 2 {
  154. socketType = "tcp"
  155. }
  156. return socketType
  157. }