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"
16 cfg "github.com/bytom/config"
17 "github.com/bytom/dashboard"
18 "github.com/bytom/errors"
19 "github.com/bytom/net/http/authn"
20 "github.com/bytom/net/http/gzip"
21 "github.com/bytom/net/http/httpjson"
22 "github.com/bytom/net/http/static"
23 "github.com/bytom/protocol"
24 "github.com/bytom/wallet"
28 errNotAuthenticated = errors.New("not authenticated")
29 httpReadTimeout = 2 * time.Minute
30 httpWriteTimeout = time.Hour
34 // SUCCESS indicates the rpc calling is successful.
36 // FAIL indicated the rpc calling is failed.
38 crosscoreRPCPrefix = "/rpc/"
41 // Response describes the response standard.
42 type Response struct {
43 Status string `json:"status,omitempty"`
44 Msg string `json:"msg,omitempty"`
45 Data interface{} `json:"data,omitempty"`
48 //NewSuccessResponse success response
49 func NewSuccessResponse(data interface{}) Response {
50 return Response{Status: SUCCESS, Data: data}
53 //NewErrorResponse error response
54 func NewErrorResponse(err error) Response {
55 return Response{Status: FAIL, Msg: err.Error()}
58 type waitHandler struct {
63 func (wh *waitHandler) Set(h http.Handler) {
68 func (wh *waitHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
70 wh.h.ServeHTTP(w, req)
73 // API is the scheduling center for server
75 bcr *blockchain.BlockchainReactor
77 accessTokens *accesstoken.CredentialStore
83 func (a *API) initServer(config *cfg.Config) {
84 // The waitHandler accepts incoming requests, but blocks until its underlying
85 // handler is set, when the second phase is complete.
86 var coreHandler waitHandler
87 var handler http.Handler
90 mux := http.NewServeMux()
91 mux.Handle("/", &coreHandler)
94 if config.Auth.Disable == false {
95 handler = AuthHandler(handler, a.accessTokens)
97 handler = RedirectHandler(handler)
99 secureheader.DefaultConfig.PermitClearLoopback = true
100 secureheader.DefaultConfig.HTTPSRedirect = false
101 secureheader.DefaultConfig.Next = handler
103 a.server = &http.Server{
104 // Note: we should not set TLSConfig here;
105 // we took care of TLS with the listener in maybeUseTLS.
106 Handler: secureheader.DefaultConfig,
107 ReadTimeout: httpReadTimeout,
108 WriteTimeout: httpWriteTimeout,
109 // Disable HTTP/2 for now until the Go implementation is more stable.
110 // https://github.com/golang/go/issues/16450
111 // https://github.com/golang/go/issues/17071
112 TLSNextProto: map[string]func(*http.Server, *tls.Conn, http.Handler){},
118 // StartServer start the server
119 func (a *API) StartServer(address string) {
120 log.WithField("api address:", address).Info("Rpc listen")
121 listener, err := net.Listen("tcp", address)
123 cmn.Exit(cmn.Fmt("Failed to register tcp port: %v", err))
126 // The `Serve` call has to happen in its own goroutine because
127 // it's blocking and we need to proceed to the rest of the core setup after
130 if err := a.server.Serve(listener); err != nil {
131 log.WithField("error", errors.Wrap(err, "Serve")).Error("Rpc server")
136 // NewAPI create and initialize the API
137 func NewAPI(bcr *blockchain.BlockchainReactor, wallet *wallet.Wallet, chain *protocol.Chain, config *cfg.Config, token *accesstoken.CredentialStore) *API {
145 api.initServer(config)
150 func (a *API) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
151 a.handler.ServeHTTP(rw, req)
154 // buildHandler is in charge of all the rpc handling.
155 func (a *API) buildHandler() {
156 walletEnable := false
157 m := http.NewServeMux()
161 m.Handle("/create-account", jsonHandler(a.createAccount))
162 m.Handle("/update-account-tags", jsonHandler(a.updateAccountTags))
163 m.Handle("/list-accounts", jsonHandler(a.listAccounts))
164 m.Handle("/delete-account", jsonHandler(a.deleteAccount))
166 m.Handle("/create-account-receiver", jsonHandler(a.createAccountReceiver))
167 m.Handle("/list-addresses", jsonHandler(a.listAddresses))
168 m.Handle("/validate-address", jsonHandler(a.validateAddress))
170 m.Handle("/create-asset", jsonHandler(a.createAsset))
171 m.Handle("/update-asset-alias", jsonHandler(a.updateAssetAlias))
172 m.Handle("/update-asset-tags", jsonHandler(a.updateAssetTags))
173 m.Handle("/list-assets", jsonHandler(a.listAssets))
175 m.Handle("/create-key", jsonHandler(a.pseudohsmCreateKey))
176 m.Handle("/list-keys", jsonHandler(a.pseudohsmListKeys))
177 m.Handle("/delete-key", jsonHandler(a.pseudohsmDeleteKey))
178 m.Handle("/reset-key-password", jsonHandler(a.pseudohsmResetPassword))
180 m.Handle("/export-private-key", jsonHandler(a.walletExportKey))
181 m.Handle("/import-private-key", jsonHandler(a.walletImportKey))
182 m.Handle("/import-key-progress", jsonHandler(a.keyImportProgress))
184 m.Handle("/build-transaction", jsonHandler(a.build))
185 m.Handle("/sign-transaction", jsonHandler(a.pseudohsmSignTemplates))
186 m.Handle("/submit-transaction", jsonHandler(a.submit))
187 m.Handle("/sign-submit-transaction", jsonHandler(a.signSubmit))
188 m.Handle("/get-transaction", jsonHandler(a.getTransaction))
189 m.Handle("/list-transactions", jsonHandler(a.listTransactions))
191 m.Handle("/list-balances", jsonHandler(a.listBalances))
192 m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
194 log.Warn("Please enable wallet")
197 m.Handle("/", alwaysError(errors.New("not Found")))
198 m.Handle("/error", jsonHandler(a.walletError))
200 m.Handle("/info", jsonHandler(a.bcr.Info))
201 m.Handle("/net-info", jsonHandler(a.getNetInfo))
203 m.Handle("/create-access-token", jsonHandler(a.createAccessToken))
204 m.Handle("/list-access-tokens", jsonHandler(a.listAccessTokens))
205 m.Handle("/delete-access-token", jsonHandler(a.deleteAccessToken))
206 m.Handle("/check-access-token", jsonHandler(a.checkAccessToken))
208 m.Handle("/create-transaction-feed", jsonHandler(a.createTxFeed))
209 m.Handle("/get-transaction-feed", jsonHandler(a.getTxFeed))
210 m.Handle("/update-transaction-feed", jsonHandler(a.updateTxFeed))
211 m.Handle("/delete-transaction-feed", jsonHandler(a.deleteTxFeed))
212 m.Handle("/list-transaction-feeds", jsonHandler(a.listTxFeeds))
214 m.Handle("/block-hash", jsonHandler(a.getBestBlockHash))
215 m.Handle("/get-block-header-by-hash", jsonHandler(a.getBlockHeaderByHash))
216 m.Handle("/get-block-header-by-height", jsonHandler(a.getBlockHeaderByHeight))
217 m.Handle("/get-block", jsonHandler(a.getBlock))
218 m.Handle("/get-block-count", jsonHandler(a.getBlockCount))
219 m.Handle("/get-block-transactions-count-by-hash", jsonHandler(a.getBlockTransactionsCountByHash))
220 m.Handle("/get-block-transactions-count-by-height", jsonHandler(a.getBlockTransactionsCountByHeight))
222 m.Handle("/is-mining", jsonHandler(a.isMining))
223 m.Handle("/gas-rate", jsonHandler(a.gasRate))
224 m.Handle("/get-work", jsonHandler(a.getWork))
225 m.Handle("/submit-work", jsonHandler(a.submitWork))
227 handler := latencyHandler(m, walletEnable)
228 handler = walletRedirectHandler(handler)
229 handler = maxBytesHandler(handler) // TODO(tessr): consider moving this to non-core specific mux
230 handler = webAssetsHandler(handler)
231 handler = gzip.Handler{Handler: handler}
236 func maxBytesHandler(h http.Handler) http.Handler {
237 const maxReqSize = 1e7 // 10MB
238 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
239 // A block can easily be bigger than maxReqSize, but everything
240 // else should be pretty small.
241 if req.URL.Path != crosscoreRPCPrefix+"signer/sign-block" {
242 req.Body = http.MaxBytesReader(w, req.Body, maxReqSize)
249 func jsonHandler(f interface{}) http.Handler {
250 h, err := httpjson.Handler(f, errorFormatter.Write)
258 func alwaysError(err error) http.Handler {
259 return jsonHandler(func() error { return err })
262 func webAssetsHandler(next http.Handler) http.Handler {
263 mux := http.NewServeMux()
264 mux.Handle("/dashboard/", http.StripPrefix("/dashboard/", static.Handler{
265 Assets: dashboard.Files,
266 Default: "index.html",
268 mux.Handle("/", next)
273 // AuthHandler access token auth Handler
274 func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore) http.Handler {
275 authenticator := authn.NewAPI(accessTokens)
277 return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
278 // TODO(tessr): check that this path exists; return early if this path isn't legit
279 req, err := authenticator.Authenticate(req)
281 log.WithField("error", errors.Wrap(err, "Serve")).Error("Authenticate fail")
282 err = errors.Sub(errNotAuthenticated, err)
283 errorFormatter.Write(req.Context(), rw, err)
286 handler.ServeHTTP(rw, req)
290 // RedirectHandler redirect to dashboard handler
291 func RedirectHandler(next http.Handler) http.Handler {
292 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
293 if req.URL.Path == "/" {
294 http.Redirect(w, req, "/dashboard/", http.StatusFound)
297 next.ServeHTTP(w, req)
301 // latencyHandler take latency for the request url path, and redirect url path to wait-disable when wallet is closed
302 func latencyHandler(m *http.ServeMux, walletEnable bool) http.Handler {
303 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
304 // latency for the request url path
305 if l := latency(m, req); l != nil {
306 defer l.RecordSince(time.Now())
309 // when the wallet is not been opened and the url path is not been found, modify url path to error,
310 // and after redirecting to the new url in func walletRedirectHandler
311 if _, pattern := m.Handler(req); pattern != req.URL.Path && !walletEnable {
312 req.URL.Path = "/error"
319 // walletRedirectHandler redirect to error when the wallet is closed
320 func walletRedirectHandler(handler http.Handler) http.Handler {
321 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
322 if req.URL.Path == "/error" {
323 http.Redirect(w, req, req.URL.String(), http.StatusOK)
326 handler.ServeHTTP(w, req)