10 "github.com/kr/secureheader"
11 log "github.com/sirupsen/logrus"
12 cmn "github.com/tendermint/tmlibs/common"
14 "github.com/bytom/accesstoken"
15 "github.com/bytom/blockchain/txfeed"
16 cfg "github.com/bytom/config"
17 "github.com/bytom/dashboard"
18 "github.com/bytom/errors"
19 "github.com/bytom/mining/cpuminer"
20 "github.com/bytom/mining/miningpool"
21 "github.com/bytom/net/http/authn"
22 "github.com/bytom/net/http/gzip"
23 "github.com/bytom/net/http/httpjson"
24 "github.com/bytom/net/http/static"
25 "github.com/bytom/netsync"
26 "github.com/bytom/protocol"
27 "github.com/bytom/wallet"
31 errNotAuthenticated = errors.New("not authenticated")
32 httpReadTimeout = 2 * time.Minute
33 httpWriteTimeout = time.Hour
37 // SUCCESS indicates the rpc calling is successful.
39 // FAIL indicated the rpc calling is failed.
41 crosscoreRPCPrefix = "/rpc/"
44 // Response describes the response standard.
45 type Response struct {
46 Status string `json:"status,omitempty"`
47 Code string `json:"code,omitempty"`
48 Msg string `json:"msg,omitempty"`
49 ErrorDetail string `json:"error_detail,omitempty"`
50 Data interface{} `json:"data,omitempty"`
53 //NewSuccessResponse success response
54 func NewSuccessResponse(data interface{}) Response {
55 return Response{Status: SUCCESS, Data: data}
58 //FormatErrResp format error response
59 func FormatErrResp(err error) (response Response) {
60 response = Response{Status: FAIL}
61 root := errors.Root(err)
62 // Some types cannot be used as map keys, for example slices.
63 // If an error's underlying type is one of these, don't panic.
64 // Just treat it like any other missing entry.
66 if err := recover(); err != nil {
67 response.ErrorDetail = ""
71 if info, ok := respErrFormatter[root]; ok {
72 response.Code = info.ChainCode
73 response.Msg = info.Message
74 response.ErrorDetail = errors.Detail(err)
79 //NewErrorResponse error response
80 func NewErrorResponse(err error) Response {
81 response := FormatErrResp(err)
82 if response.Msg == "" {
83 response.Msg = err.Error()
88 type waitHandler struct {
93 func (wh *waitHandler) Set(h http.Handler) {
98 func (wh *waitHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
100 wh.h.ServeHTTP(w, req)
103 // API is the scheduling center for server
105 sync *netsync.SyncManager
106 wallet *wallet.Wallet
107 accessTokens *accesstoken.CredentialStore
108 chain *protocol.Chain
111 txFeedTracker *txfeed.Tracker
112 cpuMiner *cpuminer.CPUMiner
113 miningPool *miningpool.MiningPool
116 func (a *API) initServer(config *cfg.Config) {
117 // The waitHandler accepts incoming requests, but blocks until its underlying
118 // handler is set, when the second phase is complete.
119 var coreHandler waitHandler
120 var handler http.Handler
122 coreHandler.wg.Add(1)
123 mux := http.NewServeMux()
124 mux.Handle("/", &coreHandler)
127 if config.Auth.Disable == false {
128 handler = AuthHandler(handler, a.accessTokens)
130 handler = RedirectHandler(handler)
132 secureheader.DefaultConfig.PermitClearLoopback = true
133 secureheader.DefaultConfig.HTTPSRedirect = false
134 secureheader.DefaultConfig.Next = handler
136 a.server = &http.Server{
137 // Note: we should not set TLSConfig here;
138 // we took care of TLS with the listener in maybeUseTLS.
139 Handler: secureheader.DefaultConfig,
140 ReadTimeout: httpReadTimeout,
141 WriteTimeout: httpWriteTimeout,
142 // Disable HTTP/2 for now until the Go implementation is more stable.
143 // https://github.com/golang/go/issues/16450
144 // https://github.com/golang/go/issues/17071
145 TLSNextProto: map[string]func(*http.Server, *tls.Conn, http.Handler){},
151 // StartServer start the server
152 func (a *API) StartServer(address string) {
153 log.WithField("api address:", address).Info("Rpc listen")
154 listener, err := net.Listen("tcp", address)
156 cmn.Exit(cmn.Fmt("Failed to register tcp port: %v", err))
159 // The `Serve` call has to happen in its own goroutine because
160 // it's blocking and we need to proceed to the rest of the core setup after
163 if err := a.server.Serve(listener); err != nil {
164 log.WithField("error", errors.Wrap(err, "Serve")).Error("Rpc server")
169 // NewAPI create and initialize the API
170 func NewAPI(sync *netsync.SyncManager, wallet *wallet.Wallet, txfeeds *txfeed.Tracker, cpuMiner *cpuminer.CPUMiner, miningPool *miningpool.MiningPool, chain *protocol.Chain, config *cfg.Config, token *accesstoken.CredentialStore) *API {
176 txFeedTracker: txfeeds,
178 miningPool: miningPool,
181 api.initServer(config)
186 func (a *API) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
187 a.handler.ServeHTTP(rw, req)
190 // buildHandler is in charge of all the rpc handling.
191 func (a *API) buildHandler() {
192 walletEnable := false
193 m := http.NewServeMux()
197 m.Handle("/create-account", jsonHandler(a.createAccount))
198 m.Handle("/list-accounts", jsonHandler(a.listAccounts))
199 m.Handle("/delete-account", jsonHandler(a.deleteAccount))
201 m.Handle("/create-account-receiver", jsonHandler(a.createAccountReceiver))
202 m.Handle("/list-addresses", jsonHandler(a.listAddresses))
203 m.Handle("/validate-address", jsonHandler(a.validateAddress))
204 m.Handle("/list-pubkeys", jsonHandler(a.listPubKeys))
206 m.Handle("/create-asset", jsonHandler(a.createAsset))
207 m.Handle("/update-asset-alias", jsonHandler(a.updateAssetAlias))
208 m.Handle("/get-asset", jsonHandler(a.getAsset))
209 m.Handle("/list-assets", jsonHandler(a.listAssets))
211 m.Handle("/create-key", jsonHandler(a.pseudohsmCreateKey))
212 m.Handle("/list-keys", jsonHandler(a.pseudohsmListKeys))
213 m.Handle("/delete-key", jsonHandler(a.pseudohsmDeleteKey))
214 m.Handle("/reset-key-password", jsonHandler(a.pseudohsmResetPassword))
215 m.Handle("/sign-message", jsonHandler(a.signMessage))
217 m.Handle("/build-transaction", jsonHandler(a.build))
218 m.Handle("/sign-transaction", jsonHandler(a.pseudohsmSignTemplates))
220 m.Handle("/get-transaction", jsonHandler(a.getTransaction))
221 m.Handle("/list-transactions", jsonHandler(a.listTransactions))
223 m.Handle("/list-balances", jsonHandler(a.listBalances))
224 m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
226 m.Handle("/backup-wallet", jsonHandler(a.backupWalletImage))
227 m.Handle("/restore-wallet", jsonHandler(a.restoreWalletImage))
228 m.Handle("/rescan-wallet", jsonHandler(a.rescanWallet))
229 m.Handle("/wallet-info", jsonHandler(a.getWalletInfo))
231 log.Warn("Please enable wallet")
234 m.Handle("/", alwaysError(errors.New("not Found")))
235 m.Handle("/error", jsonHandler(a.walletError))
237 m.Handle("/create-access-token", jsonHandler(a.createAccessToken))
238 m.Handle("/list-access-tokens", jsonHandler(a.listAccessTokens))
239 m.Handle("/delete-access-token", jsonHandler(a.deleteAccessToken))
240 m.Handle("/check-access-token", jsonHandler(a.checkAccessToken))
242 m.Handle("/create-transaction-feed", jsonHandler(a.createTxFeed))
243 m.Handle("/get-transaction-feed", jsonHandler(a.getTxFeed))
244 m.Handle("/update-transaction-feed", jsonHandler(a.updateTxFeed))
245 m.Handle("/delete-transaction-feed", jsonHandler(a.deleteTxFeed))
246 m.Handle("/list-transaction-feeds", jsonHandler(a.listTxFeeds))
248 m.Handle("/submit-transaction", jsonHandler(a.submit))
249 m.Handle("/estimate-transaction-gas", jsonHandler(a.estimateTxGas))
251 m.Handle("/get-unconfirmed-transaction", jsonHandler(a.getUnconfirmedTx))
252 m.Handle("/list-unconfirmed-transactions", jsonHandler(a.listUnconfirmedTxs))
253 m.Handle("/decode-raw-transaction", jsonHandler(a.decodeRawTransaction))
255 m.Handle("/get-block-hash", jsonHandler(a.getBestBlockHash))
256 m.Handle("/get-block-header", jsonHandler(a.getBlockHeader))
257 m.Handle("/get-block", jsonHandler(a.getBlock))
258 m.Handle("/get-block-count", jsonHandler(a.getBlockCount))
259 m.Handle("/get-difficulty", jsonHandler(a.getDifficulty))
260 m.Handle("/get-hash-rate", jsonHandler(a.getHashRate))
262 m.Handle("/is-mining", jsonHandler(a.isMining))
263 m.Handle("/set-mining", jsonHandler(a.setMining))
265 m.Handle("/get-work", jsonHandler(a.getWork))
266 m.Handle("/get-work-json", jsonHandler(a.getWorkJSON))
267 m.Handle("/submit-work", jsonHandler(a.submitWork))
268 m.Handle("/submit-work-json", jsonHandler(a.submitWorkJSON))
270 m.Handle("/verify-message", jsonHandler(a.verifyMessage))
271 m.Handle("/decode-program", jsonHandler(a.decodeProgram))
273 m.Handle("/gas-rate", jsonHandler(a.gasRate))
274 m.Handle("/net-info", jsonHandler(a.getNetInfo))
276 m.Handle("/list-peers", jsonHandler(a.listPeers))
277 m.Handle("/disconnect-peer", jsonHandler(a.disconnectPeer))
278 m.Handle("/connect-peer", jsonHandler(a.connectPeer))
280 handler := latencyHandler(m, walletEnable)
281 handler = maxBytesHandler(handler) // TODO(tessr): consider moving this to non-core specific mux
282 handler = webAssetsHandler(handler)
283 handler = gzip.Handler{Handler: handler}
288 func maxBytesHandler(h http.Handler) http.Handler {
289 const maxReqSize = 1e7 // 10MB
290 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
291 // A block can easily be bigger than maxReqSize, but everything
292 // else should be pretty small.
293 if req.URL.Path != crosscoreRPCPrefix+"signer/sign-block" {
294 req.Body = http.MaxBytesReader(w, req.Body, maxReqSize)
301 func jsonHandler(f interface{}) http.Handler {
302 h, err := httpjson.Handler(f, errorFormatter.Write)
310 func alwaysError(err error) http.Handler {
311 return jsonHandler(func() error { return err })
314 func webAssetsHandler(next http.Handler) http.Handler {
315 mux := http.NewServeMux()
316 mux.Handle("/dashboard/", http.StripPrefix("/dashboard/", static.Handler{
317 Assets: dashboard.Files,
318 Default: "index.html",
320 mux.Handle("/", next)
325 // AuthHandler access token auth Handler
326 func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore) http.Handler {
327 authenticator := authn.NewAPI(accessTokens)
329 return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
330 // TODO(tessr): check that this path exists; return early if this path isn't legit
331 req, err := authenticator.Authenticate(req)
333 log.WithField("error", errors.Wrap(err, "Serve")).Error("Authenticate fail")
334 err = errors.Sub(errNotAuthenticated, err)
335 errorFormatter.Write(req.Context(), rw, err)
338 handler.ServeHTTP(rw, req)
342 // RedirectHandler redirect to dashboard handler
343 func RedirectHandler(next http.Handler) http.Handler {
344 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
345 if req.URL.Path == "/" {
346 http.Redirect(w, req, "/dashboard/", http.StatusFound)
349 next.ServeHTTP(w, req)
353 // latencyHandler take latency for the request url path, and redirect url path to wait-disable when wallet is closed
354 func latencyHandler(m *http.ServeMux, walletEnable bool) http.Handler {
355 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
356 // latency for the request url path
357 if l := latency(m, req); l != nil {
358 defer l.RecordSince(time.Now())
361 // when the wallet is not been opened and the url path is not been found, modify url path to error,
362 // and redirect handler to error
363 if _, pattern := m.Handler(req); pattern != req.URL.Path && !walletEnable {
364 req.URL.Path = "/error"
365 walletRedirectHandler(w, req)
373 // walletRedirectHandler redirect to error when the wallet is closed
374 func walletRedirectHandler(w http.ResponseWriter, req *http.Request) {
375 h := http.RedirectHandler(req.URL.String(), http.StatusMovedPermanently)