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 Msg string `json:"msg,omitempty"`
48 Data interface{} `json:"data,omitempty"`
51 //NewSuccessResponse success response
52 func NewSuccessResponse(data interface{}) Response {
53 return Response{Status: SUCCESS, Data: data}
56 //NewErrorResponse error response
57 func NewErrorResponse(err error) Response {
58 return Response{Status: FAIL, Msg: err.Error()}
61 type waitHandler struct {
66 func (wh *waitHandler) Set(h http.Handler) {
71 func (wh *waitHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
73 wh.h.ServeHTTP(w, req)
76 // API is the scheduling center for server
78 sync *netsync.SyncManager
80 accessTokens *accesstoken.CredentialStore
84 txFeedTracker *txfeed.Tracker
85 cpuMiner *cpuminer.CPUMiner
86 miningPool *miningpool.MiningPool
89 func (a *API) initServer(config *cfg.Config) {
90 // The waitHandler accepts incoming requests, but blocks until its underlying
91 // handler is set, when the second phase is complete.
92 var coreHandler waitHandler
93 var handler http.Handler
96 mux := http.NewServeMux()
97 mux.Handle("/", &coreHandler)
100 if config.Auth.Disable == false {
101 handler = AuthHandler(handler, a.accessTokens)
103 handler = RedirectHandler(handler)
105 secureheader.DefaultConfig.PermitClearLoopback = true
106 secureheader.DefaultConfig.HTTPSRedirect = false
107 secureheader.DefaultConfig.Next = handler
109 a.server = &http.Server{
110 // Note: we should not set TLSConfig here;
111 // we took care of TLS with the listener in maybeUseTLS.
112 Handler: secureheader.DefaultConfig,
113 ReadTimeout: httpReadTimeout,
114 WriteTimeout: httpWriteTimeout,
115 // Disable HTTP/2 for now until the Go implementation is more stable.
116 // https://github.com/golang/go/issues/16450
117 // https://github.com/golang/go/issues/17071
118 TLSNextProto: map[string]func(*http.Server, *tls.Conn, http.Handler){},
124 // StartServer start the server
125 func (a *API) StartServer(address string) {
126 log.WithField("api address:", address).Info("Rpc listen")
127 listener, err := net.Listen("tcp", address)
129 cmn.Exit(cmn.Fmt("Failed to register tcp port: %v", err))
132 // The `Serve` call has to happen in its own goroutine because
133 // it's blocking and we need to proceed to the rest of the core setup after
136 if err := a.server.Serve(listener); err != nil {
137 log.WithField("error", errors.Wrap(err, "Serve")).Error("Rpc server")
142 // NewAPI create and initialize the API
143 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 {
149 txFeedTracker: txfeeds,
151 miningPool: miningPool,
154 api.initServer(config)
159 func (a *API) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
160 a.handler.ServeHTTP(rw, req)
163 // buildHandler is in charge of all the rpc handling.
164 func (a *API) buildHandler() {
165 walletEnable := false
166 m := http.NewServeMux()
170 m.Handle("/create-account", jsonHandler(a.createAccount))
171 m.Handle("/list-accounts", jsonHandler(a.listAccounts))
172 m.Handle("/delete-account", jsonHandler(a.deleteAccount))
174 m.Handle("/create-account-receiver", jsonHandler(a.createAccountReceiver))
175 m.Handle("/list-addresses", jsonHandler(a.listAddresses))
176 m.Handle("/validate-address", jsonHandler(a.validateAddress))
178 m.Handle("/create-asset", jsonHandler(a.createAsset))
179 m.Handle("/update-asset-alias", jsonHandler(a.updateAssetAlias))
180 m.Handle("/list-assets", jsonHandler(a.listAssets))
182 m.Handle("/create-key", jsonHandler(a.pseudohsmCreateKey))
183 m.Handle("/list-keys", jsonHandler(a.pseudohsmListKeys))
184 m.Handle("/delete-key", jsonHandler(a.pseudohsmDeleteKey))
185 m.Handle("/reset-key-password", jsonHandler(a.pseudohsmResetPassword))
187 m.Handle("/build-transaction", jsonHandler(a.build))
188 m.Handle("/sign-transaction", jsonHandler(a.pseudohsmSignTemplates))
189 m.Handle("/submit-transaction", jsonHandler(a.submit))
190 m.Handle("/estimate-transaction-gas", jsonHandler(a.estimateTxGas))
191 // TODO remove this api, separate sign and submit process
192 m.Handle("/sign-submit-transaction", jsonHandler(a.signSubmit))
194 m.Handle("/get-transaction", jsonHandler(a.getTransaction))
195 m.Handle("/list-transactions", jsonHandler(a.listTransactions))
197 m.Handle("/get-unconfirmed-transaction", jsonHandler(a.getUnconfirmedTx))
198 m.Handle("/list-unconfirmed-transactions", jsonHandler(a.listUnconfirmedTxs))
200 m.Handle("/list-balances", jsonHandler(a.listBalances))
201 m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
203 log.Warn("Please enable wallet")
206 m.Handle("/", alwaysError(errors.New("not Found")))
207 m.Handle("/error", jsonHandler(a.walletError))
209 m.Handle("/net-info", jsonHandler(a.getNetInfo))
211 m.Handle("/create-access-token", jsonHandler(a.createAccessToken))
212 m.Handle("/list-access-tokens", jsonHandler(a.listAccessTokens))
213 m.Handle("/delete-access-token", jsonHandler(a.deleteAccessToken))
214 m.Handle("/check-access-token", jsonHandler(a.checkAccessToken))
216 m.Handle("/create-transaction-feed", jsonHandler(a.createTxFeed))
217 m.Handle("/get-transaction-feed", jsonHandler(a.getTxFeed))
218 m.Handle("/update-transaction-feed", jsonHandler(a.updateTxFeed))
219 m.Handle("/delete-transaction-feed", jsonHandler(a.deleteTxFeed))
220 m.Handle("/list-transaction-feeds", jsonHandler(a.listTxFeeds))
222 m.Handle("/get-block-hash", jsonHandler(a.getBestBlockHash))
223 m.Handle("/get-block-header-by-hash", jsonHandler(a.getBlockHeaderByHash))
224 m.Handle("/get-block-header-by-height", jsonHandler(a.getBlockHeaderByHeight))
225 m.Handle("/get-block", jsonHandler(a.getBlock))
226 m.Handle("/get-block-count", jsonHandler(a.getBlockCount))
227 m.Handle("/get-block-transactions-count-by-hash", jsonHandler(a.getBlockTransactionsCountByHash))
228 m.Handle("/get-block-transactions-count-by-height", jsonHandler(a.getBlockTransactionsCountByHeight))
230 m.Handle("/is-mining", jsonHandler(a.isMining))
231 m.Handle("/gas-rate", jsonHandler(a.gasRate))
232 m.Handle("/get-work", jsonHandler(a.getWork))
233 m.Handle("/submit-work", jsonHandler(a.submitWork))
234 m.Handle("/set-mining", jsonHandler(a.setMining))
236 handler := latencyHandler(m, walletEnable)
237 handler = maxBytesHandler(handler) // TODO(tessr): consider moving this to non-core specific mux
238 handler = webAssetsHandler(handler)
239 handler = gzip.Handler{Handler: handler}
244 func maxBytesHandler(h http.Handler) http.Handler {
245 const maxReqSize = 1e7 // 10MB
246 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
247 // A block can easily be bigger than maxReqSize, but everything
248 // else should be pretty small.
249 if req.URL.Path != crosscoreRPCPrefix+"signer/sign-block" {
250 req.Body = http.MaxBytesReader(w, req.Body, maxReqSize)
257 func jsonHandler(f interface{}) http.Handler {
258 h, err := httpjson.Handler(f, errorFormatter.Write)
266 func alwaysError(err error) http.Handler {
267 return jsonHandler(func() error { return err })
270 func webAssetsHandler(next http.Handler) http.Handler {
271 mux := http.NewServeMux()
272 mux.Handle("/dashboard/", http.StripPrefix("/dashboard/", static.Handler{
273 Assets: dashboard.Files,
274 Default: "index.html",
276 mux.Handle("/", next)
281 // AuthHandler access token auth Handler
282 func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore) http.Handler {
283 authenticator := authn.NewAPI(accessTokens)
285 return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
286 // TODO(tessr): check that this path exists; return early if this path isn't legit
287 req, err := authenticator.Authenticate(req)
289 log.WithField("error", errors.Wrap(err, "Serve")).Error("Authenticate fail")
290 err = errors.Sub(errNotAuthenticated, err)
291 errorFormatter.Write(req.Context(), rw, err)
294 handler.ServeHTTP(rw, req)
298 // RedirectHandler redirect to dashboard handler
299 func RedirectHandler(next http.Handler) http.Handler {
300 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
301 if req.URL.Path == "/" {
302 http.Redirect(w, req, "/dashboard/", http.StatusFound)
305 next.ServeHTTP(w, req)
309 // latencyHandler take latency for the request url path, and redirect url path to wait-disable when wallet is closed
310 func latencyHandler(m *http.ServeMux, walletEnable bool) http.Handler {
311 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
312 // latency for the request url path
313 if l := latency(m, req); l != nil {
314 defer l.RecordSince(time.Now())
317 // when the wallet is not been opened and the url path is not been found, modify url path to error,
318 // and redirect handler to error
319 if _, pattern := m.Handler(req); pattern != req.URL.Path && !walletEnable {
320 req.URL.Path = "/error"
321 walletRedirectHandler(w, req)
329 // walletRedirectHandler redirect to error when the wallet is closed
330 func walletRedirectHandler(w http.ResponseWriter, req *http.Request) {
331 h := http.RedirectHandler(req.URL.String(), http.StatusMovedPermanently)