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 //NewErrorResponse error response
59 func NewErrorResponse(err error) Response {
60 root := errors.Root(err)
61 if info, ok := respErrFormatter[root]; ok {
66 ErrorDetail: errors.Detail(err),
71 Msg: errors.Detail(err),
72 ErrorDetail: errors.Detail(err),
76 type waitHandler struct {
81 func (wh *waitHandler) Set(h http.Handler) {
86 func (wh *waitHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
88 wh.h.ServeHTTP(w, req)
91 // API is the scheduling center for server
93 sync *netsync.SyncManager
95 accessTokens *accesstoken.CredentialStore
99 txFeedTracker *txfeed.Tracker
100 cpuMiner *cpuminer.CPUMiner
101 miningPool *miningpool.MiningPool
104 func (a *API) initServer(config *cfg.Config) {
105 // The waitHandler accepts incoming requests, but blocks until its underlying
106 // handler is set, when the second phase is complete.
107 var coreHandler waitHandler
108 var handler http.Handler
110 coreHandler.wg.Add(1)
111 mux := http.NewServeMux()
112 mux.Handle("/", &coreHandler)
115 if config.Auth.Disable == false {
116 handler = AuthHandler(handler, a.accessTokens)
118 handler = RedirectHandler(handler)
120 secureheader.DefaultConfig.PermitClearLoopback = true
121 secureheader.DefaultConfig.HTTPSRedirect = false
122 secureheader.DefaultConfig.Next = handler
124 a.server = &http.Server{
125 // Note: we should not set TLSConfig here;
126 // we took care of TLS with the listener in maybeUseTLS.
127 Handler: secureheader.DefaultConfig,
128 ReadTimeout: httpReadTimeout,
129 WriteTimeout: httpWriteTimeout,
130 // Disable HTTP/2 for now until the Go implementation is more stable.
131 // https://github.com/golang/go/issues/16450
132 // https://github.com/golang/go/issues/17071
133 TLSNextProto: map[string]func(*http.Server, *tls.Conn, http.Handler){},
139 // StartServer start the server
140 func (a *API) StartServer(address string) {
141 log.WithField("api address:", address).Info("Rpc listen")
142 listener, err := net.Listen("tcp", address)
144 cmn.Exit(cmn.Fmt("Failed to register tcp port: %v", err))
147 // The `Serve` call has to happen in its own goroutine because
148 // it's blocking and we need to proceed to the rest of the core setup after
151 if err := a.server.Serve(listener); err != nil {
152 log.WithField("error", errors.Wrap(err, "Serve")).Error("Rpc server")
157 // NewAPI create and initialize the API
158 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 {
164 txFeedTracker: txfeeds,
166 miningPool: miningPool,
169 api.initServer(config)
174 func (a *API) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
175 a.handler.ServeHTTP(rw, req)
178 // buildHandler is in charge of all the rpc handling.
179 func (a *API) buildHandler() {
180 walletEnable := false
181 m := http.NewServeMux()
185 m.Handle("/create-account", jsonHandler(a.createAccount))
186 m.Handle("/list-accounts", jsonHandler(a.listAccounts))
187 m.Handle("/delete-account", jsonHandler(a.deleteAccount))
189 m.Handle("/create-account-receiver", jsonHandler(a.createAccountReceiver))
190 m.Handle("/list-addresses", jsonHandler(a.listAddresses))
191 m.Handle("/validate-address", jsonHandler(a.validateAddress))
193 m.Handle("/create-asset", jsonHandler(a.createAsset))
194 m.Handle("/update-asset-alias", jsonHandler(a.updateAssetAlias))
195 m.Handle("/get-asset", jsonHandler(a.getAsset))
196 m.Handle("/list-assets", jsonHandler(a.listAssets))
198 m.Handle("/create-key", jsonHandler(a.pseudohsmCreateKey))
199 m.Handle("/list-keys", jsonHandler(a.pseudohsmListKeys))
200 m.Handle("/delete-key", jsonHandler(a.pseudohsmDeleteKey))
201 m.Handle("/reset-key-password", jsonHandler(a.pseudohsmResetPassword))
202 m.Handle("/sign-message", jsonHandler(a.signMessage))
204 m.Handle("/build-transaction", jsonHandler(a.build))
205 m.Handle("/sign-transaction", jsonHandler(a.pseudohsmSignTemplates))
207 m.Handle("/get-transaction", jsonHandler(a.getTransaction))
208 m.Handle("/list-transactions", jsonHandler(a.listTransactions))
210 m.Handle("/list-balances", jsonHandler(a.listBalances))
211 m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
213 m.Handle("/backup-wallet", jsonHandler(a.backupWalletImage))
214 m.Handle("/restore-wallet", jsonHandler(a.restoreWalletImage))
216 log.Warn("Please enable wallet")
219 m.Handle("/", alwaysError(errors.New("not Found")))
220 m.Handle("/error", jsonHandler(a.walletError))
222 m.Handle("/create-access-token", jsonHandler(a.createAccessToken))
223 m.Handle("/list-access-tokens", jsonHandler(a.listAccessTokens))
224 m.Handle("/delete-access-token", jsonHandler(a.deleteAccessToken))
225 m.Handle("/check-access-token", jsonHandler(a.checkAccessToken))
227 m.Handle("/create-transaction-feed", jsonHandler(a.createTxFeed))
228 m.Handle("/get-transaction-feed", jsonHandler(a.getTxFeed))
229 m.Handle("/update-transaction-feed", jsonHandler(a.updateTxFeed))
230 m.Handle("/delete-transaction-feed", jsonHandler(a.deleteTxFeed))
231 m.Handle("/list-transaction-feeds", jsonHandler(a.listTxFeeds))
233 m.Handle("/submit-transaction", jsonHandler(a.submit))
234 m.Handle("/estimate-transaction-gas", jsonHandler(a.estimateTxGas))
236 m.Handle("/get-unconfirmed-transaction", jsonHandler(a.getUnconfirmedTx))
237 m.Handle("/list-unconfirmed-transactions", jsonHandler(a.listUnconfirmedTxs))
238 m.Handle("/decode-raw-transaction", jsonHandler(a.decodeRawTransaction))
240 m.Handle("/get-block-hash", jsonHandler(a.getBestBlockHash))
241 m.Handle("/get-block-header", jsonHandler(a.getBlockHeader))
242 m.Handle("/get-block", jsonHandler(a.getBlock))
243 m.Handle("/get-block-count", jsonHandler(a.getBlockCount))
244 m.Handle("/get-difficulty", jsonHandler(a.getDifficulty))
245 m.Handle("/get-hash-rate", jsonHandler(a.getHashRate))
247 m.Handle("/is-mining", jsonHandler(a.isMining))
248 m.Handle("/set-mining", jsonHandler(a.setMining))
250 m.Handle("/get-work", jsonHandler(a.getWork))
251 m.Handle("/get-work-json", jsonHandler(a.getWorkJSON))
252 m.Handle("/submit-work", jsonHandler(a.submitWork))
253 m.Handle("/submit-work-json", jsonHandler(a.submitWorkJSON))
255 m.Handle("/verify-message", jsonHandler(a.verifyMessage))
256 m.Handle("/decode-program", jsonHandler(a.decodeProgram))
258 m.Handle("/gas-rate", jsonHandler(a.gasRate))
259 m.Handle("/net-info", jsonHandler(a.getNetInfo))
261 handler := latencyHandler(m, walletEnable)
262 handler = maxBytesHandler(handler) // TODO(tessr): consider moving this to non-core specific mux
263 handler = webAssetsHandler(handler)
264 handler = gzip.Handler{Handler: handler}
269 func maxBytesHandler(h http.Handler) http.Handler {
270 const maxReqSize = 1e7 // 10MB
271 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
272 // A block can easily be bigger than maxReqSize, but everything
273 // else should be pretty small.
274 if req.URL.Path != crosscoreRPCPrefix+"signer/sign-block" {
275 req.Body = http.MaxBytesReader(w, req.Body, maxReqSize)
282 func jsonHandler(f interface{}) http.Handler {
283 h, err := httpjson.Handler(f, errorFormatter.Write)
291 func alwaysError(err error) http.Handler {
292 return jsonHandler(func() error { return err })
295 func webAssetsHandler(next http.Handler) http.Handler {
296 mux := http.NewServeMux()
297 mux.Handle("/dashboard/", http.StripPrefix("/dashboard/", static.Handler{
298 Assets: dashboard.Files,
299 Default: "index.html",
301 mux.Handle("/", next)
306 // AuthHandler access token auth Handler
307 func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore) http.Handler {
308 authenticator := authn.NewAPI(accessTokens)
310 return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
311 // TODO(tessr): check that this path exists; return early if this path isn't legit
312 req, err := authenticator.Authenticate(req)
314 log.WithField("error", errors.Wrap(err, "Serve")).Error("Authenticate fail")
315 err = errors.Sub(errNotAuthenticated, err)
316 errorFormatter.Write(req.Context(), rw, err)
319 handler.ServeHTTP(rw, req)
323 // RedirectHandler redirect to dashboard handler
324 func RedirectHandler(next http.Handler) http.Handler {
325 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
326 if req.URL.Path == "/" {
327 http.Redirect(w, req, "/dashboard/", http.StatusFound)
330 next.ServeHTTP(w, req)
334 // latencyHandler take latency for the request url path, and redirect url path to wait-disable when wallet is closed
335 func latencyHandler(m *http.ServeMux, walletEnable bool) http.Handler {
336 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
337 // latency for the request url path
338 if l := latency(m, req); l != nil {
339 defer l.RecordSince(time.Now())
342 // when the wallet is not been opened and the url path is not been found, modify url path to error,
343 // and redirect handler to error
344 if _, pattern := m.Handler(req); pattern != req.URL.Path && !walletEnable {
345 req.URL.Path = "/error"
346 walletRedirectHandler(w, req)
354 // walletRedirectHandler redirect to error when the wallet is closed
355 func walletRedirectHandler(w http.ResponseWriter, req *http.Request) {
356 h := http.RedirectHandler(req.URL.String(), http.StatusMovedPermanently)