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("/get-asset", jsonHandler(a.getAsset))
181 m.Handle("/list-assets", jsonHandler(a.listAssets))
183 m.Handle("/create-key", jsonHandler(a.pseudohsmCreateKey))
184 m.Handle("/list-keys", jsonHandler(a.pseudohsmListKeys))
185 m.Handle("/delete-key", jsonHandler(a.pseudohsmDeleteKey))
186 m.Handle("/reset-key-password", jsonHandler(a.pseudohsmResetPassword))
188 m.Handle("/build-transaction", jsonHandler(a.build))
189 m.Handle("/sign-transaction", jsonHandler(a.pseudohsmSignTemplates))
190 m.Handle("/submit-transaction", jsonHandler(a.submit))
191 m.Handle("/estimate-transaction-gas", jsonHandler(a.estimateTxGas))
193 m.Handle("/get-transaction", jsonHandler(a.getTransaction))
194 m.Handle("/list-transactions", jsonHandler(a.listTransactions))
196 m.Handle("/list-balances", jsonHandler(a.listBalances))
197 m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
199 m.Handle("/backup-wallet", jsonHandler(a.backupWalletImage))
200 m.Handle("/restore-wallet", jsonHandler(a.restoreWalletImage))
202 log.Warn("Please enable wallet")
205 m.Handle("/", alwaysError(errors.New("not Found")))
206 m.Handle("/error", jsonHandler(a.walletError))
208 m.Handle("/net-info", jsonHandler(a.getNetInfo))
210 m.Handle("/create-access-token", jsonHandler(a.createAccessToken))
211 m.Handle("/list-access-tokens", jsonHandler(a.listAccessTokens))
212 m.Handle("/delete-access-token", jsonHandler(a.deleteAccessToken))
213 m.Handle("/check-access-token", jsonHandler(a.checkAccessToken))
215 m.Handle("/create-transaction-feed", jsonHandler(a.createTxFeed))
216 m.Handle("/get-transaction-feed", jsonHandler(a.getTxFeed))
217 m.Handle("/update-transaction-feed", jsonHandler(a.updateTxFeed))
218 m.Handle("/delete-transaction-feed", jsonHandler(a.deleteTxFeed))
219 m.Handle("/list-transaction-feeds", jsonHandler(a.listTxFeeds))
221 m.Handle("/get-unconfirmed-transaction", jsonHandler(a.getUnconfirmedTx))
222 m.Handle("/list-unconfirmed-transactions", jsonHandler(a.listUnconfirmedTxs))
224 m.Handle("/get-block-hash", jsonHandler(a.getBestBlockHash))
225 m.Handle("/get-block-header", jsonHandler(a.getBlockHeader))
226 m.Handle("/get-block", jsonHandler(a.getBlock))
227 m.Handle("/get-block-count", jsonHandler(a.getBlockCount))
229 m.Handle("/is-mining", jsonHandler(a.isMining))
230 m.Handle("/gas-rate", jsonHandler(a.gasRate))
231 m.Handle("/get-work", jsonHandler(a.getWork))
232 m.Handle("/submit-work", jsonHandler(a.submitWork))
233 m.Handle("/set-mining", jsonHandler(a.setMining))
235 handler := latencyHandler(m, walletEnable)
236 handler = maxBytesHandler(handler) // TODO(tessr): consider moving this to non-core specific mux
237 handler = webAssetsHandler(handler)
238 handler = gzip.Handler{Handler: handler}
243 func maxBytesHandler(h http.Handler) http.Handler {
244 const maxReqSize = 1e7 // 10MB
245 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
246 // A block can easily be bigger than maxReqSize, but everything
247 // else should be pretty small.
248 if req.URL.Path != crosscoreRPCPrefix+"signer/sign-block" {
249 req.Body = http.MaxBytesReader(w, req.Body, maxReqSize)
256 func jsonHandler(f interface{}) http.Handler {
257 h, err := httpjson.Handler(f, errorFormatter.Write)
265 func alwaysError(err error) http.Handler {
266 return jsonHandler(func() error { return err })
269 func webAssetsHandler(next http.Handler) http.Handler {
270 mux := http.NewServeMux()
271 mux.Handle("/dashboard/", http.StripPrefix("/dashboard/", static.Handler{
272 Assets: dashboard.Files,
273 Default: "index.html",
275 mux.Handle("/", next)
280 // AuthHandler access token auth Handler
281 func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore) http.Handler {
282 authenticator := authn.NewAPI(accessTokens)
284 return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
285 // TODO(tessr): check that this path exists; return early if this path isn't legit
286 req, err := authenticator.Authenticate(req)
288 log.WithField("error", errors.Wrap(err, "Serve")).Error("Authenticate fail")
289 err = errors.Sub(errNotAuthenticated, err)
290 errorFormatter.Write(req.Context(), rw, err)
293 handler.ServeHTTP(rw, req)
297 // RedirectHandler redirect to dashboard handler
298 func RedirectHandler(next http.Handler) http.Handler {
299 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
300 if req.URL.Path == "/" {
301 http.Redirect(w, req, "/dashboard/", http.StatusFound)
304 next.ServeHTTP(w, req)
308 // latencyHandler take latency for the request url path, and redirect url path to wait-disable when wallet is closed
309 func latencyHandler(m *http.ServeMux, walletEnable bool) http.Handler {
310 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
311 // latency for the request url path
312 if l := latency(m, req); l != nil {
313 defer l.RecordSince(time.Now())
316 // when the wallet is not been opened and the url path is not been found, modify url path to error,
317 // and redirect handler to error
318 if _, pattern := m.Handler(req); pattern != req.URL.Path && !walletEnable {
319 req.URL.Path = "/error"
320 walletRedirectHandler(w, req)
328 // walletRedirectHandler redirect to error when the wallet is closed
329 func walletRedirectHandler(w http.ResponseWriter, req *http.Request) {
330 h := http.RedirectHandler(req.URL.String(), http.StatusMovedPermanently)