rpc: unexport ServerError

It's internal server thing that is not for the outside users.
This commit is contained in:
Anna Shaleva 2022-06-09 18:19:01 +03:00
parent 0687924e87
commit ef9eca7cce
4 changed files with 184 additions and 148 deletions

View file

@ -2,26 +2,34 @@ package response
import ( import (
"fmt" "fmt"
"net/http"
) )
type ( // Error represents JSON-RPC 2.0 error type.
// ServerError object for outputting JSON-RPC 2.0 errors on the server side. type Error struct {
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 {
Code int64 `json:"code"` Code int64 `json:"code"`
Message string `json:"message"` Message string `json:"message"`
Data string `json:"data,omitempty"` Data string `json:"data,omitempty"`
} }
// Standard RPC error codes defined by the JSON-RPC 2.0 specification.
const (
// InternalServerErrorCode is returned for internal RPC server error.
InternalServerErrorCode = -32603
// BadRequestCode is returned on parse error.
BadRequestCode = -32700
// InvalidRequestCode is returned on invalid request.
InvalidRequestCode = -32600
// MethodNotFoundCode is returned on unknown method calling.
MethodNotFoundCode = -32601
// InvalidParamsCode is returned on request with invalid params.
InvalidParamsCode = -32602
) )
// InternalServerErrorCode is returned for internal RPC server error. // RPC error codes defined by the Neo JSON-RPC specification extension.
const InternalServerErrorCode = -32603 const (
// RPCErrorCode is returned on RPC request processing error.
RPCErrorCode = -100
)
var ( var (
// ErrInvalidParams represents a generic 'invalid parameters' error. // ErrInvalidParams represents a generic 'invalid parameters' error.
@ -40,65 +48,61 @@ var (
ErrUnknown = NewSubmitError(-500, "Unknown error.") ErrUnknown = NewSubmitError(-500, "Unknown error.")
) )
// NewServerError is an ServerError constructor that takes ServerError contents from its // NewError is an Error constructor that takes Error contents from its parameters.
// parameters. func NewError(code int64, 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,
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) *ServerError { func NewParseError(data string) *Error {
return NewServerError(-32700, http.StatusBadRequest, "Parse Error", data) return NewError(BadRequestCode, "Parse Error", data)
} }
// NewInvalidRequestError creates a new error with // NewInvalidRequestError creates a new error with
// code -32600. // code -32600.
func NewInvalidRequestError(data string) *ServerError { func NewInvalidRequestError(data string) *Error {
return NewServerError(-32600, http.StatusUnprocessableEntity, "Invalid Request", data) return NewError(InvalidRequestCode, "Invalid Request", data)
} }
// NewMethodNotFoundError creates a new error with // NewMethodNotFoundError creates a new error with
// code -32601. // code -32601.
func NewMethodNotFoundError(data string) *ServerError { func NewMethodNotFoundError(data string) *Error {
return NewServerError(-32601, http.StatusMethodNotAllowed, "Method not found", data) return NewError(MethodNotFoundCode, "Method not found", data)
} }
// NewInvalidParamsError creates a new error with // NewInvalidParamsError creates a new error with
// code -32602. // code -32602.
func NewInvalidParamsError(data string) *ServerError { func NewInvalidParamsError(data string) *Error {
return NewServerError(-32602, http.StatusUnprocessableEntity, "Invalid Params", data) return NewError(InvalidParamsCode, "Invalid Params", data)
} }
// NewInternalServerError creates a new error with // NewInternalServerError creates a new error with
// code -32603. // code -32603.
func NewInternalServerError(data string) *ServerError { func NewInternalServerError(data string) *Error {
return NewServerError(InternalServerErrorCode, http.StatusInternalServerError, "Internal error", data) return NewError(InternalServerErrorCode, "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) *ServerError { func NewRPCError(message string, data string) *Error {
return NewServerError(-100, http.StatusUnprocessableEntity, message, data) return NewError(RPCErrorCode, 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) *ServerError { func NewSubmitError(code int64, message string) *Error {
return NewServerError(code, http.StatusUnprocessableEntity, message, "") return NewError(code, message, "")
} }
// WrapErrorWithData returns copy of the given error with the specified data and cause. // WrapErrorWithData returns copy of the given error with the specified data and cause.
// It does not modify the source error. // It does not modify the source error.
func WrapErrorWithData(e *ServerError, data string) *ServerError { func WrapErrorWithData(e *Error, data string) *Error {
return NewServerError(e.Code, e.HTTPCode, e.Message, data) return NewError(e.Code, e.Message, data)
} }
// Error implements the error interface. // Error implements the error interface.

View file

@ -24,40 +24,6 @@ type Raw struct {
Result json.RawMessage `json:"result,omitempty"` Result json.RawMessage `json:"result,omitempty"`
} }
// AbstractResult is an interface which represents either single JSON-RPC 2.0 response
// or batch JSON-RPC 2.0 response.
type AbstractResult interface {
RunForErrors(f func(jsonErr *Error))
}
// Abstract represents abstract JSON-RPC 2.0 response, it differs from Raw in
// that Result field is an interface here. It is used as a server-side response
// representation.
type Abstract struct {
Header
Error *ServerError `json:"error,omitempty"`
Result interface{} `json:"result,omitempty"`
}
// RunForErrors implements AbstractResult interface.
func (a Abstract) RunForErrors(f func(jsonErr *Error)) {
if a.Error != nil {
f(a.Error.Error)
}
}
// AbstractBatch represents abstract JSON-RPC 2.0 batch-response.
type AbstractBatch []Abstract
// RunForErrors implements AbstractResult interface.
func (ab AbstractBatch) RunForErrors(f func(jsonErr *Error)) {
for _, a := range ab {
if a.Error != nil {
f(a.Error.Error)
}
}
}
// Notification is a type used to represent wire format of events, they're // Notification is a type used to represent wire format of events, they're
// special in that they look like requests but they don't have IDs and their // special in that they look like requests but they don't have IDs and their
// "method" is actually an event name. // "method" is actually an event name.

66
pkg/rpc/server/error.go Normal file
View file

@ -0,0 +1,66 @@
package server
import (
"net/http"
"github.com/nspcc-dev/neo-go/pkg/rpc/response"
)
// serverError represents RPC error response on the server side.
type serverError struct {
*response.Error
HTTPCode int // HTTPCode won't be marshalled because Error's marshaller is used.
}
// abstractResult is an interface which represents either single JSON-RPC 2.0 response
// or batch JSON-RPC 2.0 response.
type abstractResult interface {
RunForErrors(f func(jsonErr *response.Error))
}
// abstract represents abstract JSON-RPC 2.0 response. It is used as a server-side response
// representation.
type abstract struct {
response.Header
Error *serverError `json:"error,omitempty"`
Result interface{} `json:"result,omitempty"`
}
// RunForErrors implements abstractResult interface.
func (a abstract) RunForErrors(f func(jsonErr *response.Error)) {
if a.Error != nil {
f(a.Error.Error)
}
}
// abstractBatch represents abstract JSON-RPC 2.0 batch-response.
type abstractBatch []abstract
// RunForErrors implements abstractResult interface.
func (ab abstractBatch) RunForErrors(f func(jsonErr *response.Error)) {
for _, a := range ab {
if a.Error != nil {
f(a.Error.Error)
}
}
}
func packClientError(respErr *response.Error) *serverError {
var httpCode int
switch respErr.Code {
case response.BadRequestCode:
httpCode = http.StatusBadRequest
case response.InvalidRequestCode, response.RPCErrorCode, response.InvalidParamsCode:
httpCode = http.StatusUnprocessableEntity
case response.MethodNotFoundCode:
httpCode = http.StatusMethodNotAllowed
case response.InternalServerErrorCode:
httpCode = http.StatusInternalServerError
default:
httpCode = http.StatusUnprocessableEntity
}
return &serverError{
Error: respErr,
HTTPCode: httpCode,
}
}

View file

@ -107,7 +107,7 @@ const (
maxTransfersLimit = 1000 maxTransfersLimit = 1000
) )
var rpcHandlers = map[string]func(*Server, request.Params) (interface{}, *response.ServerError){ var rpcHandlers = map[string]func(*Server, request.Params) (interface{}, *response.Error){
"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.ServerError){ var rpcWsHandlers = map[string]func(*Server, request.Params, *subscriber) (interface{}, *response.Error){
"subscribe": (*Server).subscribe, "subscribe": (*Server).subscribe,
"unsubscribe": (*Server).unsubscribe, "unsubscribe": (*Server).unsubscribe,
} }
var invalidBlockHeightError = func(index int, height int) *response.ServerError { var invalidBlockHeightError = func(index int, height int) *response.Error {
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))
} }
@ -310,7 +310,7 @@ func (s *Server) handleHTTPRequest(w http.ResponseWriter, httpRequest *http.Requ
s.log.Info("websocket connection upgrade failed", zap.Error(err)) s.log.Info("websocket connection upgrade failed", zap.Error(err))
return return
} }
resChan := make(chan response.AbstractResult) // response.Abstract or response.AbstractBatch resChan := make(chan abstractResult) // response.abstract or response.abstractBatch
subChan := make(chan *websocket.PreparedMessage, notificationBufSize) subChan := make(chan *websocket.PreparedMessage, notificationBufSize)
subscr := &subscriber{writer: subChan, ws: ws} subscr := &subscriber{writer: subChan, ws: ws}
s.subsLock.Lock() s.subsLock.Lock()
@ -340,12 +340,12 @@ func (s *Server) handleHTTPRequest(w http.ResponseWriter, httpRequest *http.Requ
s.writeHTTPServerResponse(req, w, resp) s.writeHTTPServerResponse(req, w, resp)
} }
func (s *Server) handleRequest(req *request.Request, sub *subscriber) response.AbstractResult { func (s *Server) handleRequest(req *request.Request, sub *subscriber) abstractResult {
if req.In != nil { if req.In != nil {
req.In.Method = escapeForLog(req.In.Method) // No valid method name will be changed by it. req.In.Method = escapeForLog(req.In.Method) // No valid method name will be changed by it.
return s.handleIn(req.In, sub) return s.handleIn(req.In, sub)
} }
resp := make(response.AbstractBatch, len(req.Batch)) resp := make(abstractBatch, len(req.Batch))
for i, in := range req.Batch { for i, in := range req.Batch {
in.Method = escapeForLog(in.Method) // No valid method name will be changed by it. in.Method = escapeForLog(in.Method) // No valid method name will be changed by it.
resp[i] = s.handleIn(&in, sub) resp[i] = s.handleIn(&in, sub)
@ -353,9 +353,9 @@ func (s *Server) handleRequest(req *request.Request, sub *subscriber) response.A
return resp return resp
} }
func (s *Server) handleIn(req *request.In, sub *subscriber) response.Abstract { func (s *Server) handleIn(req *request.In, sub *subscriber) abstract {
var res interface{} var res interface{}
var resErr *response.ServerError var resErr *response.Error
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)))
} }
@ -381,7 +381,7 @@ func (s *Server) handleIn(req *request.In, sub *subscriber) response.Abstract {
return s.packResponse(req, res, resErr) return s.packResponse(req, res, resErr)
} }
func (s *Server) handleWsWrites(ws *websocket.Conn, resChan <-chan response.AbstractResult, subChan <-chan *websocket.PreparedMessage) { func (s *Server) handleWsWrites(ws *websocket.Conn, resChan <-chan abstractResult, subChan <-chan *websocket.PreparedMessage) {
pingTicker := time.NewTicker(wsPingPeriod) pingTicker := time.NewTicker(wsPingPeriod)
eventloop: eventloop:
for { for {
@ -434,7 +434,7 @@ drainloop:
} }
} }
func (s *Server) handleWsReads(ws *websocket.Conn, resChan chan<- response.AbstractResult, subscr *subscriber) { func (s *Server) handleWsReads(ws *websocket.Conn, resChan chan<- abstractResult, subscr *subscriber) {
ws.SetReadLimit(s.wsReadLimit) ws.SetReadLimit(s.wsReadLimit)
err := ws.SetReadDeadline(time.Now().Add(wsPongLimit)) err := ws.SetReadDeadline(time.Now().Add(wsPongLimit))
ws.SetPongHandler(func(string) error { return ws.SetReadDeadline(time.Now().Add(wsPongLimit)) }) ws.SetPongHandler(func(string) error { return ws.SetReadDeadline(time.Now().Add(wsPongLimit)) })
@ -467,23 +467,23 @@ requestloop:
ws.Close() ws.Close()
} }
func (s *Server) getBestBlockHash(_ request.Params) (interface{}, *response.ServerError) { func (s *Server) getBestBlockHash(_ request.Params) (interface{}, *response.Error) {
return "0x" + s.chain.CurrentBlockHash().StringLE(), nil return "0x" + s.chain.CurrentBlockHash().StringLE(), nil
} }
func (s *Server) getBlockCount(_ request.Params) (interface{}, *response.ServerError) { func (s *Server) getBlockCount(_ request.Params) (interface{}, *response.Error) {
return s.chain.BlockHeight() + 1, nil return s.chain.BlockHeight() + 1, nil
} }
func (s *Server) getBlockHeaderCount(_ request.Params) (interface{}, *response.ServerError) { func (s *Server) getBlockHeaderCount(_ request.Params) (interface{}, *response.Error) {
return s.chain.HeaderHeight() + 1, nil return s.chain.HeaderHeight() + 1, nil
} }
func (s *Server) getConnectionCount(_ request.Params) (interface{}, *response.ServerError) { func (s *Server) getConnectionCount(_ request.Params) (interface{}, *response.Error) {
return s.coreServer.PeerCount(), nil return s.coreServer.PeerCount(), nil
} }
func (s *Server) blockHashFromParam(param *request.Param) (util.Uint256, *response.ServerError) { func (s *Server) blockHashFromParam(param *request.Param) (util.Uint256, *response.Error) {
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.ServerError) { func (s *Server) getBlock(reqParams request.Params) (interface{}, *response.Error) {
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.Serv
return writer.Bytes(), nil return writer.Bytes(), nil
} }
func (s *Server) getBlockHash(reqParams request.Params) (interface{}, *response.ServerError) { func (s *Server) getBlockHash(reqParams request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) getVersion(_ request.Params) (interface{}, *response.Error) {
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.ServerErro
}, nil }, nil
} }
func (s *Server) getPeers(_ request.Params) (interface{}, *response.ServerError) { func (s *Server) getPeers(_ request.Params) (interface{}, *response.Error) {
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.ServerError)
return peers, nil return peers, nil
} }
func (s *Server) getRawMempool(reqParams request.Params) (interface{}, *response.ServerError) { func (s *Server) getRawMempool(reqParams request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) validateAddress(reqParams request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) calculateNetworkFee(reqParams request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) getApplicationLog(reqParams request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) getNEP11Balances(ps request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) getNEP11Properties(ps request.Params) (interface{}, *response.Error) {
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.S
return res, nil return res, nil
} }
func (s *Server) getNEP17Balances(ps request.Params) (interface{}, *response.ServerError) { func (s *Server) getNEP17Balances(ps request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) getNEP11Transfers(ps request.Params) (interface{}, *response.Error) {
return s.getTokenTransfers(ps, true) return s.getTokenTransfers(ps, true)
} }
func (s *Server) getNEP17Transfers(ps request.Params) (interface{}, *response.ServerError) { func (s *Server) getNEP17Transfers(ps request.Params) (interface{}, *response.Error) {
return s.getTokenTransfers(ps, false) return s.getTokenTransfers(ps, false)
} }
func (s *Server) getTokenTransfers(ps request.Params, isNEP11 bool) (interface{}, *response.ServerError) { func (s *Server) getTokenTransfers(ps request.Params, isNEP11 bool) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) contractIDFromParam(param *request.Param) (int32, *response.Error) {
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.Ser
} }
// 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.ServerError) { func (s *Server) contractScriptHashFromParam(param *request.Param) (util.Uint160, *response.Error) {
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.ServerError) { func (s *Server) getProof(ps request.Params) (interface{}, *response.Error) {
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.ServerError
}, nil }, nil
} }
func (s *Server) verifyProof(ps request.Params) (interface{}, *response.ServerError) { func (s *Server) verifyProof(ps request.Params) (interface{}, *response.Error) {
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.ServerEr
return vp, nil return vp, nil
} }
func (s *Server) getState(ps request.Params) (interface{}, *response.ServerError) { func (s *Server) getState(ps request.Params) (interface{}, *response.Error) {
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.ServerError
return res, nil return res, nil
} }
func (s *Server) findStates(ps request.Params) (interface{}, *response.ServerError) { func (s *Server) findStates(ps request.Params) (interface{}, *response.Error) {
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.ServerErr
return res, nil return res, nil
} }
func (s *Server) getHistoricalContractState(root util.Uint256, csHash util.Uint160) (*state.Contract, *response.ServerError) { func (s *Server) getHistoricalContractState(root util.Uint256, csHash util.Uint160) (*state.Contract, *response.Error) {
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.ServerError) { func (s *Server) getStateHeight(_ request.Params) (interface{}, *response.Error) {
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.Server
}, nil }, nil
} }
func (s *Server) getStateRoot(ps request.Params) (interface{}, *response.ServerError) { func (s *Server) getStateRoot(ps request.Params) (interface{}, *response.Error) {
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.ServerE
return rt, nil return rt, nil
} }
func (s *Server) getStorage(ps request.Params) (interface{}, *response.ServerError) { func (s *Server) getStorage(ps request.Params) (interface{}, *response.Error) {
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.ServerErr
return []byte(item), nil return []byte(item), nil
} }
func (s *Server) getrawtransaction(reqParams request.Params) (interface{}, *response.ServerError) { func (s *Server) getrawtransaction(reqParams request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) getTransactionHeight(ps request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) getContractState(reqParams request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) getNativeContracts(_ request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) getBlockSysFee(reqParams request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) getBlockHeader(reqParams request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) getUnclaimedGas(ps request.Params) (interface{}, *response.Error) {
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.Serv
} }
// 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.ServerError) { func (s *Server) getNextBlockValidators(_ request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) getCommittee(_ request.Params) (interface{}, *response.Error) {
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.ServerEr
} }
// invokeFunction implements the `invokeFunction` RPC call. // invokeFunction implements the `invokeFunction` RPC call.
func (s *Server) invokeFunction(reqParams request.Params) (interface{}, *response.ServerError) { func (s *Server) invokeFunction(reqParams request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) invokeFunctionHistoric(reqParams request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) getInvokeFunctionParams(reqParams request.Params) (*transaction.Transaction, bool, *response.Error) {
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.ServerError) { func (s *Server) invokescript(reqParams request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) invokescripthistoric(reqParams request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) getInvokeScriptParams(reqParams request.Params) (*transaction.Transaction, bool, *response.Error) {
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.ServerError) { func (s *Server) invokeContractVerify(reqParams request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) invokeContractVerifyHistoric(reqParams request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) getInvokeContractVerifyParams(reqParams request.Params) (util.Uint160, *transaction.Transaction, []byte, *response.Error) {
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.ServerError) { func (s *Server) getHistoricParams(reqParams request.Params) (*block.Block, *response.Error) {
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.ServerError) { func (s *Server) runScriptInVM(t trigger.Type, script []byte, contractScriptHash util.Uint160, tx *transaction.Transaction, b *block.Block, verbose bool) (*result.Invoke, *response.Error) {
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.ServerError) { func (s *Server) submitBlock(reqParams request.Params) (interface{}, *response.Error) {
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.S
} }
// submitNotaryRequest broadcasts P2PNotaryRequest over the NEO network. // submitNotaryRequest broadcasts P2PNotaryRequest over the NEO network.
func (s *Server) submitNotaryRequest(ps request.Params) (interface{}, *response.ServerError) { func (s *Server) submitNotaryRequest(ps request.Params) (interface{}, *response.Error) {
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.ServerError) { func getRelayResult(err error, hash util.Uint256) (interface{}, *response.Error) {
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.Server
} }
} }
func (s *Server) submitOracleResponse(ps request.Params) (interface{}, *response.ServerError) { func (s *Server) submitOracleResponse(ps request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) sendrawtransaction(reqParams request.Params) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) subscribe(reqParams request.Params, sub *subscriber) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) unsubscribe(reqParams request.Params, sub *subscriber) (interface{}, *response.Error) {
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.ServerError) { func (s *Server) blockHeightFromParam(param *request.Param) (int, *response.Error) {
num, err := param.GetInt() num, err := param.GetInt()
if err != nil { if err != nil {
return 0, response.ErrInvalidParams return 0, response.ErrInvalidParams
@ -2242,15 +2242,15 @@ func (s *Server) blockHeightFromParam(param *request.Param) (int, *response.Serv
return num, nil return num, nil
} }
func (s *Server) packResponse(r *request.In, result interface{}, respErr *response.ServerError) response.Abstract { func (s *Server) packResponse(r *request.In, result interface{}, respErr *response.Error) abstract {
resp := response.Abstract{ resp := abstract{
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 = packClientError(respErr)
} else { } else {
resp.Result = result resp.Result = result
} }
@ -2279,18 +2279,18 @@ 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.ServerError) { func (s *Server) writeHTTPErrorResponse(r *request.In, w http.ResponseWriter, jsonErr *response.Error) {
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)
} }
func (s *Server) writeHTTPServerResponse(r *request.Request, w http.ResponseWriter, resp response.AbstractResult) { func (s *Server) writeHTTPServerResponse(r *request.Request, w http.ResponseWriter, resp abstractResult) {
// Errors can happen in many places and we can only catch ALL of them here. // Errors can happen in many places and we can only catch ALL of them here.
resp.RunForErrors(func(jsonErr *response.Error) { resp.RunForErrors(func(jsonErr *response.Error) {
s.logRequestError(r, jsonErr) s.logRequestError(r, jsonErr)
}) })
if r.In != nil { if r.In != nil {
resp := resp.(response.Abstract) resp := resp.(abstract)
if resp.Error != nil { if resp.Error != nil {
w.WriteHeader(resp.Error.HTTPCode) w.WriteHeader(resp.Error.HTTPCode)
} }