OSDN Git Service

edit api for get-work and submit work (#507)
[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"
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"
25 )
26
27 var (
28         errNotAuthenticated = errors.New("not authenticated")
29         httpReadTimeout     = 2 * time.Minute
30         httpWriteTimeout    = time.Hour
31 )
32
33 const (
34         // SUCCESS indicates the rpc calling is successful.
35         SUCCESS = "success"
36         // FAIL indicated the rpc calling is failed.
37         FAIL               = "fail"
38         crosscoreRPCPrefix = "/rpc/"
39 )
40
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"`
46 }
47
48 //NewSuccessResponse success response
49 func NewSuccessResponse(data interface{}) Response {
50         return Response{Status: SUCCESS, Data: data}
51 }
52
53 //NewErrorResponse error response
54 func NewErrorResponse(err error) Response {
55         return Response{Status: FAIL, Msg: err.Error()}
56 }
57
58 type waitHandler struct {
59         h  http.Handler
60         wg sync.WaitGroup
61 }
62
63 func (wh *waitHandler) Set(h http.Handler) {
64         wh.h = h
65         wh.wg.Done()
66 }
67
68 func (wh *waitHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
69         wh.wg.Wait()
70         wh.h.ServeHTTP(w, req)
71 }
72
73 // API is the scheduling center for server
74 type API struct {
75         bcr          *blockchain.BlockchainReactor
76         wallet       *wallet.Wallet
77         accessTokens *accesstoken.CredentialStore
78         chain        *protocol.Chain
79         server       *http.Server
80         handler      http.Handler
81 }
82
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
88
89         coreHandler.wg.Add(1)
90         mux := http.NewServeMux()
91         mux.Handle("/", &coreHandler)
92
93         handler = mux
94         if config.Auth.Disable == false {
95                 handler = AuthHandler(handler, a.accessTokens)
96         }
97         handler = RedirectHandler(handler)
98
99         secureheader.DefaultConfig.PermitClearLoopback = true
100         secureheader.DefaultConfig.HTTPSRedirect = false
101         secureheader.DefaultConfig.Next = handler
102
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){},
113         }
114
115         coreHandler.Set(a)
116 }
117
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)
122         if err != nil {
123                 cmn.Exit(cmn.Fmt("Failed to register tcp port: %v", err))
124         }
125
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
128         // we call it.
129         go func() {
130                 if err := a.server.Serve(listener); err != nil {
131                         log.WithField("error", errors.Wrap(err, "Serve")).Error("Rpc server")
132                 }
133         }()
134 }
135
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 {
138         api := &API{
139                 bcr:          bcr,
140                 wallet:       wallet,
141                 chain:        chain,
142                 accessTokens: token,
143         }
144         api.buildHandler()
145         api.initServer(config)
146
147         return api
148 }
149
150 func (a *API) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
151         a.handler.ServeHTTP(rw, req)
152 }
153
154 // buildHandler is in charge of all the rpc handling.
155 func (a *API) buildHandler() {
156         walletEnable := false
157         m := http.NewServeMux()
158         if a.wallet != nil {
159                 walletEnable = true
160
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))
165
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))
169
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))
174
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))
179
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))
183
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))
190
191                 m.Handle("/list-balances", jsonHandler(a.listBalances))
192                 m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
193         } else {
194                 log.Warn("Please enable wallet")
195         }
196
197         m.Handle("/", alwaysError(errors.New("not Found")))
198         m.Handle("/error", jsonHandler(a.walletError))
199
200         m.Handle("/info", jsonHandler(a.bcr.Info))
201         m.Handle("/net-info", jsonHandler(a.getNetInfo))
202
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))
207
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))
213
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))
221
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))
226
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}
232
233         a.handler = handler
234 }
235
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)
243                 }
244                 h.ServeHTTP(w, req)
245         })
246 }
247
248 // json Handler
249 func jsonHandler(f interface{}) http.Handler {
250         h, err := httpjson.Handler(f, errorFormatter.Write)
251         if err != nil {
252                 panic(err)
253         }
254         return h
255 }
256
257 // error Handler
258 func alwaysError(err error) http.Handler {
259         return jsonHandler(func() error { return err })
260 }
261
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",
267         }))
268         mux.Handle("/", next)
269
270         return mux
271 }
272
273 // AuthHandler access token auth Handler
274 func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore) http.Handler {
275         authenticator := authn.NewAPI(accessTokens)
276
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)
280                 if err != nil {
281                         log.WithField("error", errors.Wrap(err, "Serve")).Error("Authenticate fail")
282                         err = errors.Sub(errNotAuthenticated, err)
283                         errorFormatter.Write(req.Context(), rw, err)
284                         return
285                 }
286                 handler.ServeHTTP(rw, req)
287         })
288 }
289
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)
295                         return
296                 }
297                 next.ServeHTTP(w, req)
298         })
299 }
300
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())
307                 }
308
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"
313                 }
314
315                 m.ServeHTTP(w, req)
316         })
317 }
318
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)
324                         return
325                 }
326                 handler.ServeHTTP(w, req)
327         })
328 }