rpc: split response.Error into server/client side

This commit is contained in:
Anna Shaleva 2022-06-08 18:14:00 +03:00
parent 5803923f68
commit 0687924e87
3 changed files with 118 additions and 103 deletions

View file

@ -6,11 +6,15 @@ import (
) )
type ( type (
// Error object for outputting JSON-RPC 2.0 // ServerError object for outputting JSON-RPC 2.0 errors on the server side.
// errors. ServerError struct {
*Error
HTTPCode int // HTTPCode won't be marshalled because Error's marshaller is used.
}
// Error represents JSON-RPC 2.0 error type.
Error struct { Error struct {
Code int64 `json:"code"` Code int64 `json:"code"`
HTTPCode int `json:"-"`
Message string `json:"message"` Message string `json:"message"`
Data string `json:"data,omitempty"` Data string `json:"data,omitempty"`
} }
@ -36,57 +40,65 @@ var (
ErrUnknown = NewSubmitError(-500, "Unknown error.") ErrUnknown = NewSubmitError(-500, "Unknown error.")
) )
// NewError is an Error constructor that takes Error contents from its // NewServerError is an ServerError constructor that takes ServerError contents from its
// parameters. // parameters.
func NewError(code int64, httpCode int, message string, data string) *Error { func NewServerError(code int64, httpCode int, message string, data string) *ServerError {
return &Error{ return &ServerError{
Error: &Error{
Code: code, Code: code,
HTTPCode: httpCode,
Message: message, Message: message,
Data: data, Data: data,
},
HTTPCode: httpCode,
} }
} }
// NewParseError creates a new error with code // NewParseError creates a new error with code
// -32700. // -32700.
func NewParseError(data string) *Error { func NewParseError(data string) *ServerError {
return NewError(-32700, http.StatusBadRequest, "Parse Error", data) return NewServerError(-32700, http.StatusBadRequest, "Parse Error", data)
} }
// NewInvalidRequestError creates a new error with // NewInvalidRequestError creates a new error with
// code -32600. // code -32600.
func NewInvalidRequestError(data string) *Error { func NewInvalidRequestError(data string) *ServerError {
return NewError(-32600, http.StatusUnprocessableEntity, "Invalid Request", data) return NewServerError(-32600, http.StatusUnprocessableEntity, "Invalid Request", data)
} }
// NewMethodNotFoundError creates a new error with // NewMethodNotFoundError creates a new error with
// code -32601. // code -32601.
func NewMethodNotFoundError(data string) *Error { func NewMethodNotFoundError(data string) *ServerError {
return NewError(-32601, http.StatusMethodNotAllowed, "Method not found", data) return NewServerError(-32601, http.StatusMethodNotAllowed, "Method not found", data)
} }
// NewInvalidParamsError creates a new error with // NewInvalidParamsError creates a new error with
// code -32602. // code -32602.
func NewInvalidParamsError(data string) *Error { func NewInvalidParamsError(data string) *ServerError {
return NewError(-32602, http.StatusUnprocessableEntity, "Invalid Params", data) return NewServerError(-32602, http.StatusUnprocessableEntity, "Invalid Params", data)
} }
// NewInternalServerError creates a new error with // NewInternalServerError creates a new error with
// code -32603. // code -32603.
func NewInternalServerError(data string) *Error { func NewInternalServerError(data string) *ServerError {
return NewError(InternalServerErrorCode, http.StatusInternalServerError, "Internal error", data) return NewServerError(InternalServerErrorCode, http.StatusInternalServerError, "Internal error", data)
} }
// NewRPCError creates a new error with // NewRPCError creates a new error with
// code -100. // code -100.
func NewRPCError(message string, data string) *Error { func NewRPCError(message string, data string) *ServerError {
return NewError(-100, http.StatusUnprocessableEntity, message, data) return NewServerError(-100, http.StatusUnprocessableEntity, message, data)
} }
// NewSubmitError creates a new error with // NewSubmitError creates a new error with
// specified error code and error message. // specified error code and error message.
func NewSubmitError(code int64, message string) *Error { func NewSubmitError(code int64, message string) *ServerError {
return NewError(code, http.StatusUnprocessableEntity, message, "") return NewServerError(code, http.StatusUnprocessableEntity, message, "")
}
// WrapErrorWithData returns copy of the given error with the specified data and cause.
// It does not modify the source error.
func WrapErrorWithData(e *ServerError, data string) *ServerError {
return NewServerError(e.Code, e.HTTPCode, e.Message, data)
} }
// Error implements the error interface. // Error implements the error interface.
@ -97,8 +109,11 @@ func (e *Error) Error() string {
return fmt.Sprintf("%s (%d) - %s", e.Message, e.Code, e.Data) return fmt.Sprintf("%s (%d) - %s", e.Message, e.Code, e.Data)
} }
// WrapErrorWithData returns copy of the given error with the specified data and cause. // Is denotes whether the error matches the target one.
// It does not modify the source error. func (e *Error) Is(target error) bool {
func WrapErrorWithData(e *Error, data string) *Error { clTarget, ok := target.(*Error)
return NewError(e.Code, e.HTTPCode, e.Message, data) if !ok {
return false
}
return e.Code == clTarget.Code
} }

View file

@ -31,16 +31,18 @@ type AbstractResult interface {
} }
// Abstract represents abstract JSON-RPC 2.0 response, it differs from Raw in // Abstract represents abstract JSON-RPC 2.0 response, it differs from Raw in
// that Result field is an interface here. // that Result field is an interface here. It is used as a server-side response
// representation.
type Abstract struct { type Abstract struct {
HeaderAndError Header
Error *ServerError `json:"error,omitempty"`
Result interface{} `json:"result,omitempty"` Result interface{} `json:"result,omitempty"`
} }
// RunForErrors implements AbstractResult interface. // RunForErrors implements AbstractResult interface.
func (a Abstract) RunForErrors(f func(jsonErr *Error)) { func (a Abstract) RunForErrors(f func(jsonErr *Error)) {
if a.Error != nil { if a.Error != nil {
f(a.Error) f(a.Error.Error)
} }
} }
@ -51,7 +53,7 @@ type AbstractBatch []Abstract
func (ab AbstractBatch) RunForErrors(f func(jsonErr *Error)) { func (ab AbstractBatch) RunForErrors(f func(jsonErr *Error)) {
for _, a := range ab { for _, a := range ab {
if a.Error != nil { if a.Error != nil {
f(a.Error) f(a.Error.Error)
} }
} }
} }

View file

@ -107,7 +107,7 @@ const (
maxTransfersLimit = 1000 maxTransfersLimit = 1000
) )
var rpcHandlers = map[string]func(*Server, request.Params) (interface{}, *response.Error){ var rpcHandlers = map[string]func(*Server, request.Params) (interface{}, *response.ServerError){
"calculatenetworkfee": (*Server).calculateNetworkFee, "calculatenetworkfee": (*Server).calculateNetworkFee,
"findstates": (*Server).findStates, "findstates": (*Server).findStates,
"getapplicationlog": (*Server).getApplicationLog, "getapplicationlog": (*Server).getApplicationLog,
@ -153,12 +153,12 @@ var rpcHandlers = map[string]func(*Server, request.Params) (interface{}, *respon
"verifyproof": (*Server).verifyProof, "verifyproof": (*Server).verifyProof,
} }
var rpcWsHandlers = map[string]func(*Server, request.Params, *subscriber) (interface{}, *response.Error){ var rpcWsHandlers = map[string]func(*Server, request.Params, *subscriber) (interface{}, *response.ServerError){
"subscribe": (*Server).subscribe, "subscribe": (*Server).subscribe,
"unsubscribe": (*Server).unsubscribe, "unsubscribe": (*Server).unsubscribe,
} }
var invalidBlockHeightError = func(index int, height int) *response.Error { var invalidBlockHeightError = func(index int, height int) *response.ServerError {
return response.NewRPCError("Invalid block height", fmt.Sprintf("param at index %d should be greater than or equal to 0 and less then or equal to current block height, got: %d", index, height)) return response.NewRPCError("Invalid block height", fmt.Sprintf("param at index %d should be greater than or equal to 0 and less then or equal to current block height, got: %d", index, height))
} }
@ -355,7 +355,7 @@ func (s *Server) handleRequest(req *request.Request, sub *subscriber) response.A
func (s *Server) handleIn(req *request.In, sub *subscriber) response.Abstract { func (s *Server) handleIn(req *request.In, sub *subscriber) response.Abstract {
var res interface{} var res interface{}
var resErr *response.Error var resErr *response.ServerError
if req.JSONRPC != request.JSONRPCVersion { if req.JSONRPC != request.JSONRPCVersion {
return s.packResponse(req, nil, response.NewInvalidParamsError(fmt.Sprintf("problem parsing JSON: invalid version, expected 2.0 got '%s'", req.JSONRPC))) return s.packResponse(req, nil, response.NewInvalidParamsError(fmt.Sprintf("problem parsing JSON: invalid version, expected 2.0 got '%s'", req.JSONRPC)))
} }
@ -467,23 +467,23 @@ requestloop:
ws.Close() ws.Close()
} }
func (s *Server) getBestBlockHash(_ request.Params) (interface{}, *response.Error) { func (s *Server) getBestBlockHash(_ request.Params) (interface{}, *response.ServerError) {
return "0x" + s.chain.CurrentBlockHash().StringLE(), nil return "0x" + s.chain.CurrentBlockHash().StringLE(), nil
} }
func (s *Server) getBlockCount(_ request.Params) (interface{}, *response.Error) { func (s *Server) getBlockCount(_ request.Params) (interface{}, *response.ServerError) {
return s.chain.BlockHeight() + 1, nil return s.chain.BlockHeight() + 1, nil
} }
func (s *Server) getBlockHeaderCount(_ request.Params) (interface{}, *response.Error) { func (s *Server) getBlockHeaderCount(_ request.Params) (interface{}, *response.ServerError) {
return s.chain.HeaderHeight() + 1, nil return s.chain.HeaderHeight() + 1, nil
} }
func (s *Server) getConnectionCount(_ request.Params) (interface{}, *response.Error) { func (s *Server) getConnectionCount(_ request.Params) (interface{}, *response.ServerError) {
return s.coreServer.PeerCount(), nil return s.coreServer.PeerCount(), nil
} }
func (s *Server) blockHashFromParam(param *request.Param) (util.Uint256, *response.Error) { func (s *Server) blockHashFromParam(param *request.Param) (util.Uint256, *response.ServerError) {
var ( var (
hash util.Uint256 hash util.Uint256
err error err error
@ -502,7 +502,7 @@ func (s *Server) blockHashFromParam(param *request.Param) (util.Uint256, *respon
return hash, nil return hash, nil
} }
func (s *Server) getBlock(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) getBlock(reqParams request.Params) (interface{}, *response.ServerError) {
param := reqParams.Value(0) param := reqParams.Value(0)
hash, respErr := s.blockHashFromParam(param) hash, respErr := s.blockHashFromParam(param)
if respErr != nil { if respErr != nil {
@ -522,7 +522,7 @@ func (s *Server) getBlock(reqParams request.Params) (interface{}, *response.Erro
return writer.Bytes(), nil return writer.Bytes(), nil
} }
func (s *Server) getBlockHash(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) getBlockHash(reqParams request.Params) (interface{}, *response.ServerError) {
num, err := s.blockHeightFromParam(reqParams.Value(0)) num, err := s.blockHeightFromParam(reqParams.Value(0))
if err != nil { if err != nil {
return nil, response.ErrInvalidParams return nil, response.ErrInvalidParams
@ -531,7 +531,7 @@ func (s *Server) getBlockHash(reqParams request.Params) (interface{}, *response.
return s.chain.GetHeaderHash(num), nil return s.chain.GetHeaderHash(num), nil
} }
func (s *Server) getVersion(_ request.Params) (interface{}, *response.Error) { func (s *Server) getVersion(_ request.Params) (interface{}, *response.ServerError) {
port, err := s.coreServer.Port() port, err := s.coreServer.Port()
if err != nil { if err != nil {
return nil, response.NewInternalServerError(fmt.Sprintf("cannot fetch tcp port: %s", err)) return nil, response.NewInternalServerError(fmt.Sprintf("cannot fetch tcp port: %s", err))
@ -559,7 +559,7 @@ func (s *Server) getVersion(_ request.Params) (interface{}, *response.Error) {
}, nil }, nil
} }
func (s *Server) getPeers(_ request.Params) (interface{}, *response.Error) { func (s *Server) getPeers(_ request.Params) (interface{}, *response.ServerError) {
peers := result.NewGetPeers() peers := result.NewGetPeers()
peers.AddUnconnected(s.coreServer.UnconnectedPeers()) peers.AddUnconnected(s.coreServer.UnconnectedPeers())
peers.AddConnected(s.coreServer.ConnectedPeers()) peers.AddConnected(s.coreServer.ConnectedPeers())
@ -567,7 +567,7 @@ func (s *Server) getPeers(_ request.Params) (interface{}, *response.Error) {
return peers, nil return peers, nil
} }
func (s *Server) getRawMempool(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) getRawMempool(reqParams request.Params) (interface{}, *response.ServerError) {
verbose, _ := reqParams.Value(0).GetBoolean() verbose, _ := reqParams.Value(0).GetBoolean()
mp := s.chain.GetMemPool() mp := s.chain.GetMemPool()
hashList := make([]util.Uint256, 0) hashList := make([]util.Uint256, 0)
@ -584,7 +584,7 @@ func (s *Server) getRawMempool(reqParams request.Params) (interface{}, *response
}, nil }, nil
} }
func (s *Server) validateAddress(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) validateAddress(reqParams request.Params) (interface{}, *response.ServerError) {
param, err := reqParams.Value(0).GetString() param, err := reqParams.Value(0).GetString()
if err != nil { if err != nil {
return nil, response.ErrInvalidParams return nil, response.ErrInvalidParams
@ -597,7 +597,7 @@ func (s *Server) validateAddress(reqParams request.Params) (interface{}, *respon
} }
// calculateNetworkFee calculates network fee for the transaction. // calculateNetworkFee calculates network fee for the transaction.
func (s *Server) calculateNetworkFee(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) calculateNetworkFee(reqParams request.Params) (interface{}, *response.ServerError) {
if len(reqParams) < 1 { if len(reqParams) < 1 {
return 0, response.ErrInvalidParams return 0, response.ErrInvalidParams
} }
@ -651,7 +651,7 @@ func (s *Server) calculateNetworkFee(reqParams request.Params) (interface{}, *re
} }
// getApplicationLog returns the contract log based on the specified txid or blockid. // getApplicationLog returns the contract log based on the specified txid or blockid.
func (s *Server) getApplicationLog(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) getApplicationLog(reqParams request.Params) (interface{}, *response.ServerError) {
hash, err := reqParams.Value(0).GetUint256() hash, err := reqParams.Value(0).GetUint256()
if err != nil { if err != nil {
return nil, response.ErrInvalidParams return nil, response.ErrInvalidParams
@ -689,7 +689,7 @@ func (s *Server) getNEP11Tokens(h util.Uint160, acc util.Uint160, bw *io.BufBinW
return nil, fmt.Errorf("invalid `tokensOf` result type %s", item.String()) return nil, fmt.Errorf("invalid `tokensOf` result type %s", item.String())
} }
func (s *Server) getNEP11Balances(ps request.Params) (interface{}, *response.Error) { func (s *Server) getNEP11Balances(ps request.Params) (interface{}, *response.ServerError) {
u, err := ps.Value(0).GetUint160FromAddressOrHex() u, err := ps.Value(0).GetUint160FromAddressOrHex()
if err != nil { if err != nil {
return nil, response.ErrInvalidParams return nil, response.ErrInvalidParams
@ -775,7 +775,7 @@ func (s *Server) invokeNEP11Properties(h util.Uint160, id []byte, bw *io.BufBinW
return item.Value().([]stackitem.MapElement), nil return item.Value().([]stackitem.MapElement), nil
} }
func (s *Server) getNEP11Properties(ps request.Params) (interface{}, *response.Error) { func (s *Server) getNEP11Properties(ps request.Params) (interface{}, *response.ServerError) {
asset, err := ps.Value(0).GetUint160FromAddressOrHex() asset, err := ps.Value(0).GetUint160FromAddressOrHex()
if err != nil { if err != nil {
return nil, response.ErrInvalidParams return nil, response.ErrInvalidParams
@ -811,7 +811,7 @@ func (s *Server) getNEP11Properties(ps request.Params) (interface{}, *response.E
return res, nil return res, nil
} }
func (s *Server) getNEP17Balances(ps request.Params) (interface{}, *response.Error) { func (s *Server) getNEP17Balances(ps request.Params) (interface{}, *response.ServerError) {
u, err := ps.Value(0).GetUint160FromAddressOrHex() u, err := ps.Value(0).GetUint160FromAddressOrHex()
if err != nil { if err != nil {
return nil, response.ErrInvalidParams return nil, response.ErrInvalidParams
@ -959,15 +959,15 @@ func getTimestampsAndLimit(ps request.Params, index int) (uint64, uint64, int, i
return start, end, limit, page, nil return start, end, limit, page, nil
} }
func (s *Server) getNEP11Transfers(ps request.Params) (interface{}, *response.Error) { func (s *Server) getNEP11Transfers(ps request.Params) (interface{}, *response.ServerError) {
return s.getTokenTransfers(ps, true) return s.getTokenTransfers(ps, true)
} }
func (s *Server) getNEP17Transfers(ps request.Params) (interface{}, *response.Error) { func (s *Server) getNEP17Transfers(ps request.Params) (interface{}, *response.ServerError) {
return s.getTokenTransfers(ps, false) return s.getTokenTransfers(ps, false)
} }
func (s *Server) getTokenTransfers(ps request.Params, isNEP11 bool) (interface{}, *response.Error) { func (s *Server) getTokenTransfers(ps request.Params, isNEP11 bool) (interface{}, *response.ServerError) {
u, err := ps.Value(0).GetUint160FromAddressOrHex() u, err := ps.Value(0).GetUint160FromAddressOrHex()
if err != nil { if err != nil {
return nil, response.ErrInvalidParams return nil, response.ErrInvalidParams
@ -1084,7 +1084,7 @@ func (s *Server) getHash(contractID int32, cache map[int32]util.Uint160) (util.U
return h, nil return h, nil
} }
func (s *Server) contractIDFromParam(param *request.Param) (int32, *response.Error) { func (s *Server) contractIDFromParam(param *request.Param) (int32, *response.ServerError) {
var result int32 var result int32
if param == nil { if param == nil {
return 0, response.ErrInvalidParams return 0, response.ErrInvalidParams
@ -1109,7 +1109,7 @@ func (s *Server) contractIDFromParam(param *request.Param) (int32, *response.Err
} }
// getContractScriptHashFromParam returns the contract script hash by hex contract hash, address, id or native contract name. // getContractScriptHashFromParam returns the contract script hash by hex contract hash, address, id or native contract name.
func (s *Server) contractScriptHashFromParam(param *request.Param) (util.Uint160, *response.Error) { func (s *Server) contractScriptHashFromParam(param *request.Param) (util.Uint160, *response.ServerError) {
var result util.Uint160 var result util.Uint160
if param == nil { if param == nil {
return result, response.ErrInvalidParams return result, response.ErrInvalidParams
@ -1149,7 +1149,7 @@ func makeStorageKey(id int32, key []byte) []byte {
var errKeepOnlyLatestState = errors.New("'KeepOnlyLatestState' setting is enabled") var errKeepOnlyLatestState = errors.New("'KeepOnlyLatestState' setting is enabled")
func (s *Server) getProof(ps request.Params) (interface{}, *response.Error) { func (s *Server) getProof(ps request.Params) (interface{}, *response.ServerError) {
if s.chain.GetConfig().KeepOnlyLatestState { if s.chain.GetConfig().KeepOnlyLatestState {
return nil, response.NewInvalidRequestError(fmt.Sprintf("'getproof' is not supported: %s", errKeepOnlyLatestState)) return nil, response.NewInvalidRequestError(fmt.Sprintf("'getproof' is not supported: %s", errKeepOnlyLatestState))
} }
@ -1180,7 +1180,7 @@ func (s *Server) getProof(ps request.Params) (interface{}, *response.Error) {
}, nil }, nil
} }
func (s *Server) verifyProof(ps request.Params) (interface{}, *response.Error) { func (s *Server) verifyProof(ps request.Params) (interface{}, *response.ServerError) {
if s.chain.GetConfig().KeepOnlyLatestState { if s.chain.GetConfig().KeepOnlyLatestState {
return nil, response.NewInvalidRequestError(fmt.Sprintf("'verifyproof' is not supported: %s", errKeepOnlyLatestState)) return nil, response.NewInvalidRequestError(fmt.Sprintf("'verifyproof' is not supported: %s", errKeepOnlyLatestState))
} }
@ -1204,7 +1204,7 @@ func (s *Server) verifyProof(ps request.Params) (interface{}, *response.Error) {
return vp, nil return vp, nil
} }
func (s *Server) getState(ps request.Params) (interface{}, *response.Error) { func (s *Server) getState(ps request.Params) (interface{}, *response.ServerError) {
root, err := ps.Value(0).GetUint256() root, err := ps.Value(0).GetUint256()
if err != nil { if err != nil {
return nil, response.WrapErrorWithData(response.ErrInvalidParams, "invalid stateroot") return nil, response.WrapErrorWithData(response.ErrInvalidParams, "invalid stateroot")
@ -1238,7 +1238,7 @@ func (s *Server) getState(ps request.Params) (interface{}, *response.Error) {
return res, nil return res, nil
} }
func (s *Server) findStates(ps request.Params) (interface{}, *response.Error) { func (s *Server) findStates(ps request.Params) (interface{}, *response.ServerError) {
root, err := ps.Value(0).GetUint256() root, err := ps.Value(0).GetUint256()
if err != nil { if err != nil {
return nil, response.WrapErrorWithData(response.ErrInvalidParams, "invalid stateroot") return nil, response.WrapErrorWithData(response.ErrInvalidParams, "invalid stateroot")
@ -1332,7 +1332,7 @@ func (s *Server) findStates(ps request.Params) (interface{}, *response.Error) {
return res, nil return res, nil
} }
func (s *Server) getHistoricalContractState(root util.Uint256, csHash util.Uint160) (*state.Contract, *response.Error) { func (s *Server) getHistoricalContractState(root util.Uint256, csHash util.Uint160) (*state.Contract, *response.ServerError) {
csKey := makeStorageKey(native.ManagementContractID, native.MakeContractKey(csHash)) csKey := makeStorageKey(native.ManagementContractID, native.MakeContractKey(csHash))
csBytes, err := s.chain.GetStateModule().GetState(root, csKey) csBytes, err := s.chain.GetStateModule().GetState(root, csKey)
if err != nil { if err != nil {
@ -1346,7 +1346,7 @@ func (s *Server) getHistoricalContractState(root util.Uint256, csHash util.Uint1
return contract, nil return contract, nil
} }
func (s *Server) getStateHeight(_ request.Params) (interface{}, *response.Error) { func (s *Server) getStateHeight(_ request.Params) (interface{}, *response.ServerError) {
var height = s.chain.BlockHeight() var height = s.chain.BlockHeight()
var stateHeight = s.chain.GetStateModule().CurrentValidatedHeight() var stateHeight = s.chain.GetStateModule().CurrentValidatedHeight()
if s.chain.GetConfig().StateRootInHeader { if s.chain.GetConfig().StateRootInHeader {
@ -1358,7 +1358,7 @@ func (s *Server) getStateHeight(_ request.Params) (interface{}, *response.Error)
}, nil }, nil
} }
func (s *Server) getStateRoot(ps request.Params) (interface{}, *response.Error) { func (s *Server) getStateRoot(ps request.Params) (interface{}, *response.ServerError) {
p := ps.Value(0) p := ps.Value(0)
if p == nil { if p == nil {
return nil, response.NewInvalidParamsError("missing stateroot identifier") return nil, response.NewInvalidParamsError("missing stateroot identifier")
@ -1384,7 +1384,7 @@ func (s *Server) getStateRoot(ps request.Params) (interface{}, *response.Error)
return rt, nil return rt, nil
} }
func (s *Server) getStorage(ps request.Params) (interface{}, *response.Error) { func (s *Server) getStorage(ps request.Params) (interface{}, *response.ServerError) {
id, rErr := s.contractIDFromParam(ps.Value(0)) id, rErr := s.contractIDFromParam(ps.Value(0))
if rErr == response.ErrUnknown { if rErr == response.ErrUnknown {
return nil, nil return nil, nil
@ -1406,7 +1406,7 @@ func (s *Server) getStorage(ps request.Params) (interface{}, *response.Error) {
return []byte(item), nil return []byte(item), nil
} }
func (s *Server) getrawtransaction(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) getrawtransaction(reqParams request.Params) (interface{}, *response.ServerError) {
txHash, err := reqParams.Value(0).GetUint256() txHash, err := reqParams.Value(0).GetUint256()
if err != nil { if err != nil {
return nil, response.ErrInvalidParams return nil, response.ErrInvalidParams
@ -1436,7 +1436,7 @@ func (s *Server) getrawtransaction(reqParams request.Params) (interface{}, *resp
return tx.Bytes(), nil return tx.Bytes(), nil
} }
func (s *Server) getTransactionHeight(ps request.Params) (interface{}, *response.Error) { func (s *Server) getTransactionHeight(ps request.Params) (interface{}, *response.ServerError) {
h, err := ps.Value(0).GetUint256() h, err := ps.Value(0).GetUint256()
if err != nil { if err != nil {
return nil, response.ErrInvalidParams return nil, response.ErrInvalidParams
@ -1452,7 +1452,7 @@ func (s *Server) getTransactionHeight(ps request.Params) (interface{}, *response
// getContractState returns contract state (contract information, according to the contract script hash, // getContractState returns contract state (contract information, according to the contract script hash,
// contract id or native contract name). // contract id or native contract name).
func (s *Server) getContractState(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) getContractState(reqParams request.Params) (interface{}, *response.ServerError) {
scriptHash, err := s.contractScriptHashFromParam(reqParams.Value(0)) scriptHash, err := s.contractScriptHashFromParam(reqParams.Value(0))
if err != nil { if err != nil {
return nil, err return nil, err
@ -1464,12 +1464,12 @@ func (s *Server) getContractState(reqParams request.Params) (interface{}, *respo
return cs, nil return cs, nil
} }
func (s *Server) getNativeContracts(_ request.Params) (interface{}, *response.Error) { func (s *Server) getNativeContracts(_ request.Params) (interface{}, *response.ServerError) {
return s.chain.GetNatives(), nil return s.chain.GetNatives(), nil
} }
// getBlockSysFee returns the system fees of the block, based on the specified index. // getBlockSysFee returns the system fees of the block, based on the specified index.
func (s *Server) getBlockSysFee(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) getBlockSysFee(reqParams request.Params) (interface{}, *response.ServerError) {
num, err := s.blockHeightFromParam(reqParams.Value(0)) num, err := s.blockHeightFromParam(reqParams.Value(0))
if err != nil { if err != nil {
return 0, response.NewRPCError("Invalid height", "invalid block identifier") return 0, response.NewRPCError("Invalid height", "invalid block identifier")
@ -1490,7 +1490,7 @@ func (s *Server) getBlockSysFee(reqParams request.Params) (interface{}, *respons
} }
// getBlockHeader returns the corresponding block header information according to the specified script hash. // getBlockHeader returns the corresponding block header information according to the specified script hash.
func (s *Server) getBlockHeader(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) getBlockHeader(reqParams request.Params) (interface{}, *response.ServerError) {
param := reqParams.Value(0) param := reqParams.Value(0)
hash, respErr := s.blockHashFromParam(param) hash, respErr := s.blockHashFromParam(param)
if respErr != nil { if respErr != nil {
@ -1516,7 +1516,7 @@ func (s *Server) getBlockHeader(reqParams request.Params) (interface{}, *respons
} }
// getUnclaimedGas returns unclaimed GAS amount of the specified address. // getUnclaimedGas returns unclaimed GAS amount of the specified address.
func (s *Server) getUnclaimedGas(ps request.Params) (interface{}, *response.Error) { func (s *Server) getUnclaimedGas(ps request.Params) (interface{}, *response.ServerError) {
u, err := ps.Value(0).GetUint160FromAddressOrHex() u, err := ps.Value(0).GetUint160FromAddressOrHex()
if err != nil { if err != nil {
return nil, response.ErrInvalidParams return nil, response.ErrInvalidParams
@ -1539,7 +1539,7 @@ func (s *Server) getUnclaimedGas(ps request.Params) (interface{}, *response.Erro
} }
// getNextBlockValidators returns validators for the next block with voting status. // getNextBlockValidators returns validators for the next block with voting status.
func (s *Server) getNextBlockValidators(_ request.Params) (interface{}, *response.Error) { func (s *Server) getNextBlockValidators(_ request.Params) (interface{}, *response.ServerError) {
var validators keys.PublicKeys var validators keys.PublicKeys
validators, err := s.chain.GetNextBlockValidators() validators, err := s.chain.GetNextBlockValidators()
@ -1562,7 +1562,7 @@ func (s *Server) getNextBlockValidators(_ request.Params) (interface{}, *respons
} }
// getCommittee returns the current list of NEO committee members. // getCommittee returns the current list of NEO committee members.
func (s *Server) getCommittee(_ request.Params) (interface{}, *response.Error) { func (s *Server) getCommittee(_ request.Params) (interface{}, *response.ServerError) {
keys, err := s.chain.GetCommittee() keys, err := s.chain.GetCommittee()
if err != nil { if err != nil {
return nil, response.NewInternalServerError(fmt.Sprintf("can't get committee members: %s", err)) return nil, response.NewInternalServerError(fmt.Sprintf("can't get committee members: %s", err))
@ -1571,7 +1571,7 @@ func (s *Server) getCommittee(_ request.Params) (interface{}, *response.Error) {
} }
// invokeFunction implements the `invokeFunction` RPC call. // invokeFunction implements the `invokeFunction` RPC call.
func (s *Server) invokeFunction(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) invokeFunction(reqParams request.Params) (interface{}, *response.ServerError) {
tx, verbose, respErr := s.getInvokeFunctionParams(reqParams) tx, verbose, respErr := s.getInvokeFunctionParams(reqParams)
if respErr != nil { if respErr != nil {
return nil, respErr return nil, respErr
@ -1580,7 +1580,7 @@ func (s *Server) invokeFunction(reqParams request.Params) (interface{}, *respons
} }
// invokeFunctionHistoric implements the `invokeFunctionHistoric` RPC call. // invokeFunctionHistoric implements the `invokeFunctionHistoric` RPC call.
func (s *Server) invokeFunctionHistoric(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) invokeFunctionHistoric(reqParams request.Params) (interface{}, *response.ServerError) {
b, respErr := s.getHistoricParams(reqParams) b, respErr := s.getHistoricParams(reqParams)
if respErr != nil { if respErr != nil {
return nil, respErr return nil, respErr
@ -1595,7 +1595,7 @@ func (s *Server) invokeFunctionHistoric(reqParams request.Params) (interface{},
return s.runScriptInVM(trigger.Application, tx.Script, util.Uint160{}, tx, b, verbose) return s.runScriptInVM(trigger.Application, tx.Script, util.Uint160{}, tx, b, verbose)
} }
func (s *Server) getInvokeFunctionParams(reqParams request.Params) (*transaction.Transaction, bool, *response.Error) { func (s *Server) getInvokeFunctionParams(reqParams request.Params) (*transaction.Transaction, bool, *response.ServerError) {
if len(reqParams) < 2 { if len(reqParams) < 2 {
return nil, false, response.ErrInvalidParams return nil, false, response.ErrInvalidParams
} }
@ -1638,7 +1638,7 @@ func (s *Server) getInvokeFunctionParams(reqParams request.Params) (*transaction
} }
// invokescript implements the `invokescript` RPC call. // invokescript implements the `invokescript` RPC call.
func (s *Server) invokescript(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) invokescript(reqParams request.Params) (interface{}, *response.ServerError) {
tx, verbose, respErr := s.getInvokeScriptParams(reqParams) tx, verbose, respErr := s.getInvokeScriptParams(reqParams)
if respErr != nil { if respErr != nil {
return nil, respErr return nil, respErr
@ -1647,7 +1647,7 @@ func (s *Server) invokescript(reqParams request.Params) (interface{}, *response.
} }
// invokescripthistoric implements the `invokescripthistoric` RPC call. // invokescripthistoric implements the `invokescripthistoric` RPC call.
func (s *Server) invokescripthistoric(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) invokescripthistoric(reqParams request.Params) (interface{}, *response.ServerError) {
b, respErr := s.getHistoricParams(reqParams) b, respErr := s.getHistoricParams(reqParams)
if respErr != nil { if respErr != nil {
return nil, respErr return nil, respErr
@ -1662,7 +1662,7 @@ func (s *Server) invokescripthistoric(reqParams request.Params) (interface{}, *r
return s.runScriptInVM(trigger.Application, tx.Script, util.Uint160{}, tx, b, verbose) return s.runScriptInVM(trigger.Application, tx.Script, util.Uint160{}, tx, b, verbose)
} }
func (s *Server) getInvokeScriptParams(reqParams request.Params) (*transaction.Transaction, bool, *response.Error) { func (s *Server) getInvokeScriptParams(reqParams request.Params) (*transaction.Transaction, bool, *response.ServerError) {
script, err := reqParams.Value(0).GetBytesBase64() script, err := reqParams.Value(0).GetBytesBase64()
if err != nil { if err != nil {
return nil, false, response.ErrInvalidParams return nil, false, response.ErrInvalidParams
@ -1692,7 +1692,7 @@ func (s *Server) getInvokeScriptParams(reqParams request.Params) (*transaction.T
} }
// invokeContractVerify implements the `invokecontractverify` RPC call. // invokeContractVerify implements the `invokecontractverify` RPC call.
func (s *Server) invokeContractVerify(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) invokeContractVerify(reqParams request.Params) (interface{}, *response.ServerError) {
scriptHash, tx, invocationScript, respErr := s.getInvokeContractVerifyParams(reqParams) scriptHash, tx, invocationScript, respErr := s.getInvokeContractVerifyParams(reqParams)
if respErr != nil { if respErr != nil {
return nil, respErr return nil, respErr
@ -1701,7 +1701,7 @@ func (s *Server) invokeContractVerify(reqParams request.Params) (interface{}, *r
} }
// invokeContractVerifyHistoric implements the `invokecontractverifyhistoric` RPC call. // invokeContractVerifyHistoric implements the `invokecontractverifyhistoric` RPC call.
func (s *Server) invokeContractVerifyHistoric(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) invokeContractVerifyHistoric(reqParams request.Params) (interface{}, *response.ServerError) {
b, respErr := s.getHistoricParams(reqParams) b, respErr := s.getHistoricParams(reqParams)
if respErr != nil { if respErr != nil {
return nil, respErr return nil, respErr
@ -1716,7 +1716,7 @@ func (s *Server) invokeContractVerifyHistoric(reqParams request.Params) (interfa
return s.runScriptInVM(trigger.Verification, invocationScript, scriptHash, tx, b, false) return s.runScriptInVM(trigger.Verification, invocationScript, scriptHash, tx, b, false)
} }
func (s *Server) getInvokeContractVerifyParams(reqParams request.Params) (util.Uint160, *transaction.Transaction, []byte, *response.Error) { func (s *Server) getInvokeContractVerifyParams(reqParams request.Params) (util.Uint160, *transaction.Transaction, []byte, *response.ServerError) {
scriptHash, responseErr := s.contractScriptHashFromParam(reqParams.Value(0)) scriptHash, responseErr := s.contractScriptHashFromParam(reqParams.Value(0))
if responseErr != nil { if responseErr != nil {
return util.Uint160{}, nil, nil, responseErr return util.Uint160{}, nil, nil, responseErr
@ -1756,7 +1756,7 @@ func (s *Server) getInvokeContractVerifyParams(reqParams request.Params) (util.U
// with the specified index to perform the historic call. It also checks that // with the specified index to perform the historic call. It also checks that
// specified stateroot is stored at the specified height for further request // specified stateroot is stored at the specified height for further request
// handling consistency. // handling consistency.
func (s *Server) getHistoricParams(reqParams request.Params) (*block.Block, *response.Error) { func (s *Server) getHistoricParams(reqParams request.Params) (*block.Block, *response.ServerError) {
if s.chain.GetConfig().KeepOnlyLatestState { if s.chain.GetConfig().KeepOnlyLatestState {
return nil, response.NewInvalidRequestError(fmt.Sprintf("only latest state is supported: %s", errKeepOnlyLatestState)) return nil, response.NewInvalidRequestError(fmt.Sprintf("only latest state is supported: %s", errKeepOnlyLatestState))
} }
@ -1806,7 +1806,7 @@ func (s *Server) getFakeNextBlock(nextBlockHeight uint32) (*block.Block, error)
// witness invocation script in case of `verification` trigger (it pushes `verify` // witness invocation script in case of `verification` trigger (it pushes `verify`
// arguments on stack before verification). In case of contract verification // arguments on stack before verification). In case of contract verification
// contractScriptHash should be specified. // contractScriptHash should be specified.
func (s *Server) runScriptInVM(t trigger.Type, script []byte, contractScriptHash util.Uint160, tx *transaction.Transaction, b *block.Block, verbose bool) (*result.Invoke, *response.Error) { func (s *Server) runScriptInVM(t trigger.Type, script []byte, contractScriptHash util.Uint160, tx *transaction.Transaction, b *block.Block, verbose bool) (*result.Invoke, *response.ServerError) {
var ( var (
err error err error
ic *interop.Context ic *interop.Context
@ -1851,7 +1851,7 @@ func (s *Server) runScriptInVM(t trigger.Type, script []byte, contractScriptHash
} }
// submitBlock broadcasts a raw block over the NEO network. // submitBlock broadcasts a raw block over the NEO network.
func (s *Server) submitBlock(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) submitBlock(reqParams request.Params) (interface{}, *response.ServerError) {
blockBytes, err := reqParams.Value(0).GetBytesBase64() blockBytes, err := reqParams.Value(0).GetBytesBase64()
if err != nil { if err != nil {
return nil, response.NewInvalidParamsError(fmt.Sprintf("missing parameter or not a base64: %s", err)) return nil, response.NewInvalidParamsError(fmt.Sprintf("missing parameter or not a base64: %s", err))
@ -1877,7 +1877,7 @@ func (s *Server) submitBlock(reqParams request.Params) (interface{}, *response.E
} }
// submitNotaryRequest broadcasts P2PNotaryRequest over the NEO network. // submitNotaryRequest broadcasts P2PNotaryRequest over the NEO network.
func (s *Server) submitNotaryRequest(ps request.Params) (interface{}, *response.Error) { func (s *Server) submitNotaryRequest(ps request.Params) (interface{}, *response.ServerError) {
if !s.chain.P2PSigExtensionsEnabled() { if !s.chain.P2PSigExtensionsEnabled() {
return nil, response.NewRPCError("P2PSignatureExtensions are disabled", "") return nil, response.NewRPCError("P2PSignatureExtensions are disabled", "")
} }
@ -1894,7 +1894,7 @@ func (s *Server) submitNotaryRequest(ps request.Params) (interface{}, *response.
} }
// getRelayResult returns successful relay result or an error. // getRelayResult returns successful relay result or an error.
func getRelayResult(err error, hash util.Uint256) (interface{}, *response.Error) { func getRelayResult(err error, hash util.Uint256) (interface{}, *response.ServerError) {
switch { switch {
case err == nil: case err == nil:
return result.RelayResult{ return result.RelayResult{
@ -1911,7 +1911,7 @@ func getRelayResult(err error, hash util.Uint256) (interface{}, *response.Error)
} }
} }
func (s *Server) submitOracleResponse(ps request.Params) (interface{}, *response.Error) { func (s *Server) submitOracleResponse(ps request.Params) (interface{}, *response.ServerError) {
if s.oracle == nil { if s.oracle == nil {
return nil, response.NewRPCError("Oracle is not enabled", "") return nil, response.NewRPCError("Oracle is not enabled", "")
} }
@ -1943,7 +1943,7 @@ func (s *Server) submitOracleResponse(ps request.Params) (interface{}, *response
return json.RawMessage([]byte("{}")), nil return json.RawMessage([]byte("{}")), nil
} }
func (s *Server) sendrawtransaction(reqParams request.Params) (interface{}, *response.Error) { func (s *Server) sendrawtransaction(reqParams request.Params) (interface{}, *response.ServerError) {
if len(reqParams) < 1 { if len(reqParams) < 1 {
return nil, response.NewInvalidParamsError("not enough parameters") return nil, response.NewInvalidParamsError("not enough parameters")
} }
@ -1959,7 +1959,7 @@ func (s *Server) sendrawtransaction(reqParams request.Params) (interface{}, *res
} }
// subscribe handles subscription requests from websocket clients. // subscribe handles subscription requests from websocket clients.
func (s *Server) subscribe(reqParams request.Params, sub *subscriber) (interface{}, *response.Error) { func (s *Server) subscribe(reqParams request.Params, sub *subscriber) (interface{}, *response.ServerError) {
streamName, err := reqParams.Value(0).GetString() streamName, err := reqParams.Value(0).GetString()
if err != nil { if err != nil {
return nil, response.ErrInvalidParams return nil, response.ErrInvalidParams
@ -2060,7 +2060,7 @@ func (s *Server) subscribeToChannel(event response.EventID) {
} }
// unsubscribe handles unsubscription requests from websocket clients. // unsubscribe handles unsubscription requests from websocket clients.
func (s *Server) unsubscribe(reqParams request.Params, sub *subscriber) (interface{}, *response.Error) { func (s *Server) unsubscribe(reqParams request.Params, sub *subscriber) (interface{}, *response.ServerError) {
id, err := reqParams.Value(0).GetInt() id, err := reqParams.Value(0).GetInt()
if err != nil || id < 0 { if err != nil || id < 0 {
return nil, response.ErrInvalidParams return nil, response.ErrInvalidParams
@ -2230,7 +2230,7 @@ drainloop:
close(s.notaryRequestCh) close(s.notaryRequestCh)
} }
func (s *Server) blockHeightFromParam(param *request.Param) (int, *response.Error) { func (s *Server) blockHeightFromParam(param *request.Param) (int, *response.ServerError) {
num, err := param.GetInt() num, err := param.GetInt()
if err != nil { if err != nil {
return 0, response.ErrInvalidParams return 0, response.ErrInvalidParams
@ -2242,14 +2242,12 @@ func (s *Server) blockHeightFromParam(param *request.Param) (int, *response.Erro
return num, nil return num, nil
} }
func (s *Server) packResponse(r *request.In, result interface{}, respErr *response.Error) response.Abstract { func (s *Server) packResponse(r *request.In, result interface{}, respErr *response.ServerError) response.Abstract {
resp := response.Abstract{ resp := response.Abstract{
HeaderAndError: response.HeaderAndError{
Header: response.Header{ Header: response.Header{
JSONRPC: r.JSONRPC, JSONRPC: r.JSONRPC,
ID: r.RawID, ID: r.RawID,
}, },
},
} }
if respErr != nil { if respErr != nil {
resp.Error = respErr resp.Error = respErr
@ -2281,7 +2279,7 @@ func (s *Server) logRequestError(r *request.Request, jsonErr *response.Error) {
} }
// writeHTTPErrorResponse writes an error response to the ResponseWriter. // writeHTTPErrorResponse writes an error response to the ResponseWriter.
func (s *Server) writeHTTPErrorResponse(r *request.In, w http.ResponseWriter, jsonErr *response.Error) { func (s *Server) writeHTTPErrorResponse(r *request.In, w http.ResponseWriter, jsonErr *response.ServerError) {
resp := s.packResponse(r, nil, jsonErr) resp := s.packResponse(r, nil, jsonErr)
s.writeHTTPServerResponse(&request.Request{In: r}, w, resp) s.writeHTTPServerResponse(&request.Request{In: r}, w, resp)
} }