forked from elastos/Elastos.ELA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
321 lines (289 loc) · 9.46 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
// Copyright (c) 2017-2019 The Elastos Foundation
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
//
package httpjsonrpc
import (
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"io/ioutil"
"mime"
"net"
"net/http"
"strconv"
"time"
"github.com/elastos/Elastos.ELA/common/config"
"github.com/elastos/Elastos.ELA/common/log"
elaErr "github.com/elastos/Elastos.ELA/errors"
. "github.com/elastos/Elastos.ELA/servers"
)
//an instance of the multiplexer
var mainMux map[string]func(Params) map[string]interface{}
const (
// JSON-RPC protocol error codes.
ParseError = -32700
InvalidRequest = -32600
MethodNotFound = -32601
InvalidParams = -32602
InternalError = -32603
//-32000 to -32099 Server error, waiting for defining
// IOTimeout is the maximum duration for JSON-RPC reading or writing
// timeout.
IOTimeout = 60 * time.Second
// MaxRPCRead is the maximum buffer size for reading request.
MaxRPCRead = 1024 * 1024 * 8
)
func StartRPCServer() {
mainMux = make(map[string]func(Params) map[string]interface{})
mainMux["setloglevel"] = SetLogLevel
mainMux["getinfo"] = GetInfo
mainMux["getblock"] = GetBlockByHash
mainMux["getconfirmbyheight"] = GetConfirmByHeight
mainMux["getconfirmbyhash"] = GetConfirmByHash
mainMux["getcurrentheight"] = GetBlockHeight
mainMux["getblockhash"] = GetBlockHash
mainMux["getconnectioncount"] = GetConnectionCount
mainMux["getrawmempool"] = GetTransactionPool
mainMux["getrawtransaction"] = GetRawTransaction
mainMux["getneighbors"] = GetNeighbors
mainMux["getnodestate"] = GetNodeState
mainMux["sendrawtransaction"] = SendRawTransaction
mainMux["getarbitratorgroupbyheight"] = GetArbitratorGroupByHeight
mainMux["getbestblockhash"] = GetBestBlockHash
mainMux["getblockcount"] = GetBlockCount
mainMux["getblockbyheight"] = GetBlockByHeight
mainMux["getexistwithdrawtransactions"] = GetExistWithdrawTransactions
mainMux["getreceivedbyaddress"] = GetReceivedByAddress
// wallet interfaces
mainMux["getamountbyinputs"] = GetAmountByInputs
mainMux["getutxosbyamount"] = GetUTXOsByAmount
mainMux["listunspent"] = ListUnspent
mainMux["createrawtransaction"] = CreateRawTransaction
mainMux["decoderawtransaction"] = DecodeRawTransaction
mainMux["signrawtransactionwithkey"] = SignRawTransactionWithKey
// aux interfaces
mainMux["help"] = AuxHelp
mainMux["submitauxblock"] = SubmitAuxBlock
mainMux["createauxblock"] = CreateAuxBlock
// mining interfaces
mainMux["getmininginfo"] = GetMiningInfo
mainMux["togglemining"] = ToggleMining
mainMux["discretemining"] = DiscreteMining
//cr interfaces
mainMux["listcrcandidates"] = ListCRCandidates
mainMux["listcurrentcrs"] = ListCurrentCRs
// vote interfaces
mainMux["listproducers"] = ListProducers
mainMux["producerstatus"] = ProducerStatus
mainMux["votestatus"] = VoteStatus
// for cross-chain arbiter
mainMux["submitsidechainillegaldata"] = SubmitSidechainIllegalData
mainMux["getarbiterpeersinfo"] = GetArbiterPeersInfo
mainMux["estimatesmartfee"] = EstimateSmartFee
mainMux["getdepositcoin"] = GetDepositCoin
mainMux["getcrdepositcoin"] = GetCRDepositCoin
mainMux["getarbitersinfo"] = GetArbitersInfo
rpcServeMux := http.NewServeMux()
server := http.Server{
Handler: rpcServeMux,
ReadTimeout: IOTimeout,
WriteTimeout: IOTimeout,
}
rpcServeMux.HandleFunc("/", Handle)
l, err := net.Listen("tcp4", ":"+strconv.Itoa(config.Parameters.HttpJsonPort))
if err != nil {
log.Fatal("Create listener error: ", err.Error())
return
}
err = server.Serve(l)
if err != nil {
log.Fatal("ListenAndServe error: ", err.Error())
}
}
//this is the function that should be called in order to answer an rpc call
//should be registered like "http.AddMethod("/", httpjsonrpc.Handle)"
func Handle(w http.ResponseWriter, r *http.Request) {
isClientAllowed := clientAllowed(r)
if !isClientAllowed {
log.Warn("Client ip is not allowed")
RPCError(w, http.StatusForbidden, InternalError, "Client ip is not allowed")
return
}
// JSON RPC commands should be POSTs
if r.Method != "POST" {
log.Warn("JSON-RPC Handle - Method!=\"POST\"")
RPCError(w, http.StatusMethodNotAllowed, InternalError, "JSON-RPC protocol only allows POST method")
return
}
contentType, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
if contentType != "application/json" {
RPCError(w, http.StatusUnsupportedMediaType, InternalError, "JSON-RPC need content type to be application/json")
return
}
isCheckAuthOk := checkAuth(r)
if !isCheckAuthOk {
log.Warn("Client authenticate failed")
RPCError(w, http.StatusUnauthorized, InternalError, "Client authenticate failed")
return
}
//read the body of the request
body, err := ioutil.ReadAll(http.MaxBytesReader(w, r.Body, MaxRPCRead))
if err != nil {
RPCError(w, http.StatusBadRequest, InvalidRequest, "JSON-RPC request reading error:"+err.Error())
return
}
request := make(map[string]interface{})
err = json.Unmarshal(body, &request)
if err != nil {
log.Error("JSON-RPC request parsing error: ", err)
RPCError(w, http.StatusBadRequest, ParseError, "JSON-RPC request parsing error:"+err.Error())
return
}
//get the corresponding function
requestMethod, ok := request["method"].(string)
if !ok {
RPCError(w, http.StatusBadRequest, InvalidRequest, "JSON-RPC need a method")
return
}
method, ok := mainMux[requestMethod]
if !ok {
RPCError(w, http.StatusNotFound, MethodNotFound, "JSON-RPC method "+requestMethod+" not found")
return
}
requestParams := request["params"]
// Json rpc 1.0 support positional parameters while json rpc 2.0 support named parameters.
// positional parameters: { "requestParams":[1, 2, 3....] }
// named parameters: { "requestParams":{ "a":1, "b":2, "c":3 } }
// Here we support both of them.
var params Params
switch requestParams := requestParams.(type) {
case nil:
case []interface{}:
params = convertParams(requestMethod, requestParams)
case map[string]interface{}:
params = Params(requestParams)
default:
RPCError(w, http.StatusBadRequest, InvalidRequest, "params format error, must be an array or a map")
return
}
log.Debug("RPC method:", requestMethod)
response := method(params)
var data []byte
if response["Error"] != elaErr.ErrCode(0) {
data, _ = json.Marshal(map[string]interface{}{
"jsonrpc": "2.0",
"result": nil,
"error": map[string]interface{}{
"code": response["Error"],
"message": response["Result"],
"id": request["id"],
},
})
} else {
data, _ = json.Marshal(map[string]interface{}{
"jsonrpc": "2.0",
"result": response["Result"],
"id": request["id"],
"error": nil,
})
}
w.Header().Set("Content-type", "application/json")
w.Write(data)
}
func clientAllowed(r *http.Request) bool {
//this ipAbbr may be ::1 when request is localhost
ipAbbr, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
log.Errorf("RemoteAddr clientAllowed SplitHostPort failure %s \n", r.RemoteAddr)
return false
}
//after ParseIP ::1 chg to 0:0:0:0:0:0:0:1 the true ip
remoteIp := net.ParseIP(ipAbbr)
if remoteIp == nil {
log.Errorf("clientAllowed ParseIP ipAbbr %s failure \n", ipAbbr)
return false
}
if remoteIp.IsLoopback() {
return true
}
for _, cfgIp := range config.Parameters.RpcConfiguration.WhiteIPList {
//WhiteIPList have 0.0.0.0 allow all ip in
if cfgIp == "0.0.0.0" {
return true
}
if cfgIp == remoteIp.String() {
return true
}
}
return false
}
func checkAuth(r *http.Request) bool {
if (config.Parameters.RpcConfiguration.User == config.Parameters.RpcConfiguration.Pass) &&
(len(config.Parameters.RpcConfiguration.User) == 0) {
return true
}
authHeader := r.Header["Authorization"]
if len(authHeader) <= 0 {
return false
}
authSha256 := sha256.Sum256([]byte(authHeader[0]))
login := config.Parameters.RpcConfiguration.User + ":" + config.Parameters.RpcConfiguration.Pass
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(login))
cfgAuthSha256 := sha256.Sum256([]byte(auth))
resultCmp := subtle.ConstantTimeCompare(authSha256[:], cfgAuthSha256[:])
if resultCmp == 1 {
return true
}
// Request's auth doesn't match user
return false
}
func RPCError(w http.ResponseWriter, httpStatus int, code elaErr.ErrCode, message string) {
data, _ := json.Marshal(map[string]interface{}{
"jsonrpc": "2.0",
"result": nil,
"error": map[string]interface{}{
"code": code,
"message": message,
"id": nil,
},
})
w.Header().Set("Content-type", "application/json")
w.WriteHeader(httpStatus)
w.Write(data)
}
func convertParams(method string, params []interface{}) Params {
switch method {
case "createauxblock":
return FromArray(params, "paytoaddress")
case "submitauxblock":
return FromArray(params, "blockhash", "auxpow")
case "getblockhash":
return FromArray(params, "height")
case "getblock":
return FromArray(params, "blockhash", "verbosity")
case "setloglevel":
return FromArray(params, "level")
case "getrawtransaction":
return FromArray(params, "txid", "verbose")
case "getarbitratorgroupbyheight":
return FromArray(params, "height")
case "togglemining":
return FromArray(params, "mining")
case "discretemining":
return FromArray(params, "count")
case "sendrawtransaction":
return FromArray(params, "data")
case "listunspent":
return FromArray(params, "addresses")
case "getreceivedbyaddress":
return FromArray(params, "address")
case "getblockbyheight":
return FromArray(params, "height")
case "estimatesmartfee":
return FromArray(params, "confirmations")
default:
return Params{}
}
}