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))
187 m.Handle("/sign-message", jsonHandler(a.signMessage))
189 m.Handle("/build-transaction", jsonHandler(a.build))
190 m.Handle("/sign-transaction", jsonHandler(a.pseudohsmSignTemplates))
192 m.Handle("/get-transaction", jsonHandler(a.getTransaction))
193 m.Handle("/list-transactions", jsonHandler(a.listTransactions))
195 m.Handle("/list-balances", jsonHandler(a.listBalances))
196 m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
198 m.Handle("/backup-wallet", jsonHandler(a.backupWalletImage))
199 m.Handle("/restore-wallet", jsonHandler(a.restoreWalletImage))
201 log.Warn("Please enable wallet")
204 m.Handle("/", alwaysError(errors.New("not Found")))
205 m.Handle("/error", jsonHandler(a.walletError))
207 m.Handle("/create-access-token", jsonHandler(a.createAccessToken))
208 m.Handle("/list-access-tokens", jsonHandler(a.listAccessTokens))
209 m.Handle("/delete-access-token", jsonHandler(a.deleteAccessToken))
210 m.Handle("/check-access-token", jsonHandler(a.checkAccessToken))
212 m.Handle("/create-transaction-feed", jsonHandler(a.createTxFeed))
213 m.Handle("/get-transaction-feed", jsonHandler(a.getTxFeed))
214 m.Handle("/update-transaction-feed", jsonHandler(a.updateTxFeed))
215 m.Handle("/delete-transaction-feed", jsonHandler(a.deleteTxFeed))
216 m.Handle("/list-transaction-feeds", jsonHandler(a.listTxFeeds))
218 m.Handle("/submit-transaction", jsonHandler(a.submit))
219 m.Handle("/estimate-transaction-gas", jsonHandler(a.estimateTxGas))
221 m.Handle("/get-unconfirmed-transaction", jsonHandler(a.getUnconfirmedTx))
222 m.Handle("/list-unconfirmed-transactions", jsonHandler(a.listUnconfirmedTxs))
223 m.Handle("/decode-raw-transaction", jsonHandler(a.decodeRawTransaction))
225 m.Handle("/get-block-hash", jsonHandler(a.getBestBlockHash))
226 m.Handle("/get-block-header", jsonHandler(a.getBlockHeader))
227 m.Handle("/get-block", jsonHandler(a.getBlock))
228 m.Handle("/get-block-count", jsonHandler(a.getBlockCount))
229 m.Handle("/get-difficulty", jsonHandler(a.getDifficulty))
230 m.Handle("/get-hash-rate", jsonHandler(a.getHashRate))
232 m.Handle("/is-mining", jsonHandler(a.isMining))
233 m.Handle("/set-mining", jsonHandler(a.setMining))
235 m.Handle("/get-work", jsonHandler(a.getWork))
236 m.Handle("/submit-work", jsonHandler(a.submitWork))
238 m.Handle("/verify-message", jsonHandler(a.verifyMessage))
239 m.Handle("/decode-program", jsonHandler(a.decodeProgram))
241 m.Handle("/gas-rate", jsonHandler(a.gasRate))
242 m.Handle("/net-info", jsonHandler(a.getNetInfo))
244 handler := latencyHandler(m, walletEnable)
245 handler = maxBytesHandler(handler) // TODO(tessr): consider moving this to non-core specific mux
246 handler = webAssetsHandler(handler)
247 handler = gzip.Handler{Handler: handler}
252 func maxBytesHandler(h http.Handler) http.Handler {
253 const maxReqSize = 1e7 // 10MB
254 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
255 // A block can easily be bigger than maxReqSize, but everything
256 // else should be pretty small.
257 if req.URL.Path != crosscoreRPCPrefix+"signer/sign-block" {
258 req.Body = http.MaxBytesReader(w, req.Body, maxReqSize)
265 func jsonHandler(f interface{}) http.Handler {
266 h, err := httpjson.Handler(f, errorFormatter.Write)
274 func alwaysError(err error) http.Handler {
275 return jsonHandler(func() error { return err })
278 func webAssetsHandler(next http.Handler) http.Handler {
279 mux := http.NewServeMux()
280 mux.Handle("/dashboard/", http.StripPrefix("/dashboard/", static.Handler{
281 Assets: dashboard.Files,
282 Default: "index.html",
284 mux.Handle("/", next)
289 // AuthHandler access token auth Handler
290 func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore) http.Handler {
291 authenticator := authn.NewAPI(accessTokens)
293 return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
294 // TODO(tessr): check that this path exists; return early if this path isn't legit
295 req, err := authenticator.Authenticate(req)
297 log.WithField("error", errors.Wrap(err, "Serve")).Error("Authenticate fail")
298 err = errors.Sub(errNotAuthenticated, err)
299 errorFormatter.Write(req.Context(), rw, err)
302 handler.ServeHTTP(rw, req)
306 // RedirectHandler redirect to dashboard handler
307 func RedirectHandler(next http.Handler) http.Handler {
308 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
309 if req.URL.Path == "/" {
310 http.Redirect(w, req, "/dashboard/", http.StatusFound)
313 next.ServeHTTP(w, req)
317 // latencyHandler take latency for the request url path, and redirect url path to wait-disable when wallet is closed
318 func latencyHandler(m *http.ServeMux, walletEnable bool) http.Handler {
319 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
320 // latency for the request url path
321 if l := latency(m, req); l != nil {
322 defer l.RecordSince(time.Now())
325 // when the wallet is not been opened and the url path is not been found, modify url path to error,
326 // and redirect handler to error
327 if _, pattern := m.Handler(req); pattern != req.URL.Path && !walletEnable {
328 req.URL.Path = "/error"
329 walletRedirectHandler(w, req)
337 // walletRedirectHandler redirect to error when the wallet is closed
338 func walletRedirectHandler(w http.ResponseWriter, req *http.Request) {
339 h := http.RedirectHandler(req.URL.String(), http.StatusMovedPermanently)