OSDN Git Service

Merge pull request #1072 from Bytom/prod
[bytom/bytom.git] / api / api.go
1 package api
2
3 import (
4         "crypto/tls"
5         "net"
6         "net/http"
7         "sync"
8         "time"
9
10         "github.com/kr/secureheader"
11         log "github.com/sirupsen/logrus"
12         cmn "github.com/tendermint/tmlibs/common"
13
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"
28 )
29
30 var (
31         errNotAuthenticated = errors.New("not authenticated")
32         httpReadTimeout     = 2 * time.Minute
33         httpWriteTimeout    = time.Hour
34 )
35
36 const (
37         // SUCCESS indicates the rpc calling is successful.
38         SUCCESS = "success"
39         // FAIL indicated the rpc calling is failed.
40         FAIL               = "fail"
41         crosscoreRPCPrefix = "/rpc/"
42 )
43
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"`
51 }
52
53 //NewSuccessResponse success response
54 func NewSuccessResponse(data interface{}) Response {
55         return Response{Status: SUCCESS, Data: data}
56 }
57
58 //FormatErrResp format error response
59 func FormatErrResp(err error) (response Response) {
60         response = Response{Status: FAIL}
61         root := errors.Root(err)
62         // Some types cannot be used as map keys, for example slices.
63         // If an error's underlying type is one of these, don't panic.
64         // Just treat it like any other missing entry.
65         defer func() {
66                 if err := recover(); err != nil {
67                         response.ErrorDetail = ""
68                 }
69         }()
70
71         if info, ok := respErrFormatter[root]; ok {
72                 response.Code = info.ChainCode
73                 response.Msg = info.Message
74                 response.ErrorDetail = errors.Detail(err)
75         }
76         return response
77 }
78
79 //NewErrorResponse error response
80 func NewErrorResponse(err error) Response {
81         response := FormatErrResp(err)
82         if response.Msg == "" {
83                 response.Msg = err.Error()
84         }
85         return response
86 }
87
88 type waitHandler struct {
89         h  http.Handler
90         wg sync.WaitGroup
91 }
92
93 func (wh *waitHandler) Set(h http.Handler) {
94         wh.h = h
95         wh.wg.Done()
96 }
97
98 func (wh *waitHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
99         wh.wg.Wait()
100         wh.h.ServeHTTP(w, req)
101 }
102
103 // API is the scheduling center for server
104 type API struct {
105         sync          *netsync.SyncManager
106         wallet        *wallet.Wallet
107         accessTokens  *accesstoken.CredentialStore
108         chain         *protocol.Chain
109         server        *http.Server
110         handler       http.Handler
111         txFeedTracker *txfeed.Tracker
112         cpuMiner      *cpuminer.CPUMiner
113         miningPool    *miningpool.MiningPool
114 }
115
116 func (a *API) initServer(config *cfg.Config) {
117         // The waitHandler accepts incoming requests, but blocks until its underlying
118         // handler is set, when the second phase is complete.
119         var coreHandler waitHandler
120         var handler http.Handler
121
122         coreHandler.wg.Add(1)
123         mux := http.NewServeMux()
124         mux.Handle("/", &coreHandler)
125
126         handler = mux
127         if config.Auth.Disable == false {
128                 handler = AuthHandler(handler, a.accessTokens)
129         }
130         handler = RedirectHandler(handler)
131
132         secureheader.DefaultConfig.PermitClearLoopback = true
133         secureheader.DefaultConfig.HTTPSRedirect = false
134         secureheader.DefaultConfig.Next = handler
135
136         a.server = &http.Server{
137                 // Note: we should not set TLSConfig here;
138                 // we took care of TLS with the listener in maybeUseTLS.
139                 Handler:      secureheader.DefaultConfig,
140                 ReadTimeout:  httpReadTimeout,
141                 WriteTimeout: httpWriteTimeout,
142                 // Disable HTTP/2 for now until the Go implementation is more stable.
143                 // https://github.com/golang/go/issues/16450
144                 // https://github.com/golang/go/issues/17071
145                 TLSNextProto: map[string]func(*http.Server, *tls.Conn, http.Handler){},
146         }
147
148         coreHandler.Set(a)
149 }
150
151 // StartServer start the server
152 func (a *API) StartServer(address string) {
153         log.WithField("api address:", address).Info("Rpc listen")
154         listener, err := net.Listen("tcp", address)
155         if err != nil {
156                 cmn.Exit(cmn.Fmt("Failed to register tcp port: %v", err))
157         }
158
159         // The `Serve` call has to happen in its own goroutine because
160         // it's blocking and we need to proceed to the rest of the core setup after
161         // we call it.
162         go func() {
163                 if err := a.server.Serve(listener); err != nil {
164                         log.WithField("error", errors.Wrap(err, "Serve")).Error("Rpc server")
165                 }
166         }()
167 }
168
169 // NewAPI create and initialize the API
170 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 {
171         api := &API{
172                 sync:          sync,
173                 wallet:        wallet,
174                 chain:         chain,
175                 accessTokens:  token,
176                 txFeedTracker: txfeeds,
177                 cpuMiner:      cpuMiner,
178                 miningPool:    miningPool,
179         }
180         api.buildHandler()
181         api.initServer(config)
182
183         return api
184 }
185
186 func (a *API) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
187         a.handler.ServeHTTP(rw, req)
188 }
189
190 // buildHandler is in charge of all the rpc handling.
191 func (a *API) buildHandler() {
192         walletEnable := false
193         m := http.NewServeMux()
194         if a.wallet != nil {
195                 walletEnable = true
196
197                 m.Handle("/create-account", jsonHandler(a.createAccount))
198                 m.Handle("/list-accounts", jsonHandler(a.listAccounts))
199                 m.Handle("/delete-account", jsonHandler(a.deleteAccount))
200
201                 m.Handle("/create-account-receiver", jsonHandler(a.createAccountReceiver))
202                 m.Handle("/list-addresses", jsonHandler(a.listAddresses))
203                 m.Handle("/validate-address", jsonHandler(a.validateAddress))
204
205                 m.Handle("/create-asset", jsonHandler(a.createAsset))
206                 m.Handle("/update-asset-alias", jsonHandler(a.updateAssetAlias))
207                 m.Handle("/get-asset", jsonHandler(a.getAsset))
208                 m.Handle("/list-assets", jsonHandler(a.listAssets))
209
210                 m.Handle("/create-key", jsonHandler(a.pseudohsmCreateKey))
211                 m.Handle("/list-keys", jsonHandler(a.pseudohsmListKeys))
212                 m.Handle("/delete-key", jsonHandler(a.pseudohsmDeleteKey))
213                 m.Handle("/reset-key-password", jsonHandler(a.pseudohsmResetPassword))
214                 m.Handle("/sign-message", jsonHandler(a.signMessage))
215
216                 m.Handle("/build-transaction", jsonHandler(a.build))
217                 m.Handle("/sign-transaction", jsonHandler(a.pseudohsmSignTemplates))
218
219                 m.Handle("/get-transaction", jsonHandler(a.getTransaction))
220                 m.Handle("/list-transactions", jsonHandler(a.listTransactions))
221
222                 m.Handle("/list-balances", jsonHandler(a.listBalances))
223                 m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
224
225                 m.Handle("/backup-wallet", jsonHandler(a.backupWalletImage))
226                 m.Handle("/restore-wallet", jsonHandler(a.restoreWalletImage))
227                 m.Handle("/rescan-wallet", jsonHandler(a.rescanWallet))
228         } else {
229                 log.Warn("Please enable wallet")
230         }
231
232         m.Handle("/", alwaysError(errors.New("not Found")))
233         m.Handle("/error", jsonHandler(a.walletError))
234
235         m.Handle("/create-access-token", jsonHandler(a.createAccessToken))
236         m.Handle("/list-access-tokens", jsonHandler(a.listAccessTokens))
237         m.Handle("/delete-access-token", jsonHandler(a.deleteAccessToken))
238         m.Handle("/check-access-token", jsonHandler(a.checkAccessToken))
239
240         m.Handle("/create-transaction-feed", jsonHandler(a.createTxFeed))
241         m.Handle("/get-transaction-feed", jsonHandler(a.getTxFeed))
242         m.Handle("/update-transaction-feed", jsonHandler(a.updateTxFeed))
243         m.Handle("/delete-transaction-feed", jsonHandler(a.deleteTxFeed))
244         m.Handle("/list-transaction-feeds", jsonHandler(a.listTxFeeds))
245
246         m.Handle("/submit-transaction", jsonHandler(a.submit))
247         m.Handle("/estimate-transaction-gas", jsonHandler(a.estimateTxGas))
248
249         m.Handle("/get-unconfirmed-transaction", jsonHandler(a.getUnconfirmedTx))
250         m.Handle("/list-unconfirmed-transactions", jsonHandler(a.listUnconfirmedTxs))
251         m.Handle("/decode-raw-transaction", jsonHandler(a.decodeRawTransaction))
252
253         m.Handle("/get-block-hash", jsonHandler(a.getBestBlockHash))
254         m.Handle("/get-block-header", jsonHandler(a.getBlockHeader))
255         m.Handle("/get-block", jsonHandler(a.getBlock))
256         m.Handle("/get-block-count", jsonHandler(a.getBlockCount))
257         m.Handle("/get-difficulty", jsonHandler(a.getDifficulty))
258         m.Handle("/get-hash-rate", jsonHandler(a.getHashRate))
259
260         m.Handle("/is-mining", jsonHandler(a.isMining))
261         m.Handle("/set-mining", jsonHandler(a.setMining))
262
263         m.Handle("/get-work", jsonHandler(a.getWork))
264         m.Handle("/get-work-json", jsonHandler(a.getWorkJSON))
265         m.Handle("/submit-work", jsonHandler(a.submitWork))
266         m.Handle("/submit-work-json", jsonHandler(a.submitWorkJSON))
267
268         m.Handle("/verify-message", jsonHandler(a.verifyMessage))
269         m.Handle("/decode-program", jsonHandler(a.decodeProgram))
270
271         m.Handle("/gas-rate", jsonHandler(a.gasRate))
272         m.Handle("/net-info", jsonHandler(a.getNetInfo))
273
274         handler := latencyHandler(m, walletEnable)
275         handler = maxBytesHandler(handler) // TODO(tessr): consider moving this to non-core specific mux
276         handler = webAssetsHandler(handler)
277         handler = gzip.Handler{Handler: handler}
278
279         a.handler = handler
280 }
281
282 func maxBytesHandler(h http.Handler) http.Handler {
283         const maxReqSize = 1e7 // 10MB
284         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
285                 // A block can easily be bigger than maxReqSize, but everything
286                 // else should be pretty small.
287                 if req.URL.Path != crosscoreRPCPrefix+"signer/sign-block" {
288                         req.Body = http.MaxBytesReader(w, req.Body, maxReqSize)
289                 }
290                 h.ServeHTTP(w, req)
291         })
292 }
293
294 // json Handler
295 func jsonHandler(f interface{}) http.Handler {
296         h, err := httpjson.Handler(f, errorFormatter.Write)
297         if err != nil {
298                 panic(err)
299         }
300         return h
301 }
302
303 // error Handler
304 func alwaysError(err error) http.Handler {
305         return jsonHandler(func() error { return err })
306 }
307
308 func webAssetsHandler(next http.Handler) http.Handler {
309         mux := http.NewServeMux()
310         mux.Handle("/dashboard/", http.StripPrefix("/dashboard/", static.Handler{
311                 Assets:  dashboard.Files,
312                 Default: "index.html",
313         }))
314         mux.Handle("/", next)
315
316         return mux
317 }
318
319 // AuthHandler access token auth Handler
320 func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore) http.Handler {
321         authenticator := authn.NewAPI(accessTokens)
322
323         return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
324                 // TODO(tessr): check that this path exists; return early if this path isn't legit
325                 req, err := authenticator.Authenticate(req)
326                 if err != nil {
327                         log.WithField("error", errors.Wrap(err, "Serve")).Error("Authenticate fail")
328                         err = errors.Sub(errNotAuthenticated, err)
329                         errorFormatter.Write(req.Context(), rw, err)
330                         return
331                 }
332                 handler.ServeHTTP(rw, req)
333         })
334 }
335
336 // RedirectHandler redirect to dashboard handler
337 func RedirectHandler(next http.Handler) http.Handler {
338         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
339                 if req.URL.Path == "/" {
340                         http.Redirect(w, req, "/dashboard/", http.StatusFound)
341                         return
342                 }
343                 next.ServeHTTP(w, req)
344         })
345 }
346
347 // latencyHandler take latency for the request url path, and redirect url path to wait-disable when wallet is closed
348 func latencyHandler(m *http.ServeMux, walletEnable bool) http.Handler {
349         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
350                 // latency for the request url path
351                 if l := latency(m, req); l != nil {
352                         defer l.RecordSince(time.Now())
353                 }
354
355                 // when the wallet is not been opened and the url path is not been found, modify url path to error,
356                 // and redirect handler to error
357                 if _, pattern := m.Handler(req); pattern != req.URL.Path && !walletEnable {
358                         req.URL.Path = "/error"
359                         walletRedirectHandler(w, req)
360                         return
361                 }
362
363                 m.ServeHTTP(w, req)
364         })
365 }
366
367 // walletRedirectHandler redirect to error when the wallet is closed
368 func walletRedirectHandler(w http.ResponseWriter, req *http.Request) {
369         h := http.RedirectHandler(req.URL.String(), http.StatusMovedPermanently)
370         h.ServeHTTP(w, req)
371 }