OSDN Git Service

merge with dev
[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         Msg    string      `json:"msg,omitempty"`
48         Data   interface{} `json:"data,omitempty"`
49 }
50
51 //NewSuccessResponse success response
52 func NewSuccessResponse(data interface{}) Response {
53         return Response{Status: SUCCESS, Data: data}
54 }
55
56 //NewErrorResponse error response
57 func NewErrorResponse(err error) Response {
58         return Response{Status: FAIL, Msg: err.Error()}
59 }
60
61 type waitHandler struct {
62         h  http.Handler
63         wg sync.WaitGroup
64 }
65
66 func (wh *waitHandler) Set(h http.Handler) {
67         wh.h = h
68         wh.wg.Done()
69 }
70
71 func (wh *waitHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
72         wh.wg.Wait()
73         wh.h.ServeHTTP(w, req)
74 }
75
76 // API is the scheduling center for server
77 type API struct {
78         sync          *netsync.SyncManager
79         wallet        *wallet.Wallet
80         accessTokens  *accesstoken.CredentialStore
81         chain         *protocol.Chain
82         server        *http.Server
83         handler       http.Handler
84         txFeedTracker *txfeed.Tracker
85         cpuMiner      *cpuminer.CPUMiner
86         miningPool    *miningpool.MiningPool
87 }
88
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
94
95         coreHandler.wg.Add(1)
96         mux := http.NewServeMux()
97         mux.Handle("/", &coreHandler)
98
99         handler = mux
100         if config.Auth.Disable == false {
101                 handler = AuthHandler(handler, a.accessTokens)
102         }
103         handler = RedirectHandler(handler)
104
105         secureheader.DefaultConfig.PermitClearLoopback = true
106         secureheader.DefaultConfig.HTTPSRedirect = false
107         secureheader.DefaultConfig.Next = handler
108
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){},
119         }
120
121         coreHandler.Set(a)
122 }
123
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)
128         if err != nil {
129                 cmn.Exit(cmn.Fmt("Failed to register tcp port: %v", err))
130         }
131
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
134         // we call it.
135         go func() {
136                 if err := a.server.Serve(listener); err != nil {
137                         log.WithField("error", errors.Wrap(err, "Serve")).Error("Rpc server")
138                 }
139         }()
140 }
141
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 {
144         api := &API{
145                 sync:          sync,
146                 wallet:        wallet,
147                 chain:         chain,
148                 accessTokens:  token,
149                 txFeedTracker: txfeeds,
150                 cpuMiner:      cpuMiner,
151                 miningPool:    miningPool,
152         }
153         api.buildHandler()
154         api.initServer(config)
155
156         return api
157 }
158
159 func (a *API) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
160         a.handler.ServeHTTP(rw, req)
161 }
162
163 // buildHandler is in charge of all the rpc handling.
164 func (a *API) buildHandler() {
165         walletEnable := false
166         m := http.NewServeMux()
167         if a.wallet != nil {
168                 walletEnable = true
169
170                 m.Handle("/create-account", jsonHandler(a.createAccount))
171                 m.Handle("/list-accounts", jsonHandler(a.listAccounts))
172                 m.Handle("/delete-account", jsonHandler(a.deleteAccount))
173
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))
177
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))
182
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
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))
192
193                 m.Handle("/get-transaction", jsonHandler(a.getTransaction))
194                 m.Handle("/list-transactions", jsonHandler(a.listTransactions))
195
196                 m.Handle("/get-unconfirmed-transaction", jsonHandler(a.getUnconfirmedTx))
197                 m.Handle("/list-unconfirmed-transactions", jsonHandler(a.listUnconfirmedTxs))
198
199                 m.Handle("/list-balances", jsonHandler(a.listBalances))
200                 m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
201
202                 m.Handle("/backup-wallet", jsonHandler(a.backupWalletImage))
203                 m.Handle("/restore-wallet", jsonHandler(a.restoreWalletImage))
204         } else {
205                 log.Warn("Please enable wallet")
206         }
207
208         m.Handle("/", alwaysError(errors.New("not Found")))
209         m.Handle("/error", jsonHandler(a.walletError))
210
211         m.Handle("/net-info", jsonHandler(a.getNetInfo))
212
213         m.Handle("/create-access-token", jsonHandler(a.createAccessToken))
214         m.Handle("/list-access-tokens", jsonHandler(a.listAccessTokens))
215         m.Handle("/delete-access-token", jsonHandler(a.deleteAccessToken))
216         m.Handle("/check-access-token", jsonHandler(a.checkAccessToken))
217
218         m.Handle("/create-transaction-feed", jsonHandler(a.createTxFeed))
219         m.Handle("/get-transaction-feed", jsonHandler(a.getTxFeed))
220         m.Handle("/update-transaction-feed", jsonHandler(a.updateTxFeed))
221         m.Handle("/delete-transaction-feed", jsonHandler(a.deleteTxFeed))
222         m.Handle("/list-transaction-feeds", jsonHandler(a.listTxFeeds))
223
224         m.Handle("/get-block-hash", jsonHandler(a.getBestBlockHash))
225         m.Handle("/get-block-header-by-hash", jsonHandler(a.getBlockHeaderByHash))
226         m.Handle("/get-block-header-by-height", jsonHandler(a.getBlockHeaderByHeight))
227         m.Handle("/get-block", jsonHandler(a.getBlock))
228         m.Handle("/get-block-count", jsonHandler(a.getBlockCount))
229         m.Handle("/get-block-transactions-count-by-hash", jsonHandler(a.getBlockTransactionsCountByHash))
230         m.Handle("/get-block-transactions-count-by-height", jsonHandler(a.getBlockTransactionsCountByHeight))
231
232         m.Handle("/is-mining", jsonHandler(a.isMining))
233         m.Handle("/gas-rate", jsonHandler(a.gasRate))
234         m.Handle("/get-work", jsonHandler(a.getWork))
235         m.Handle("/submit-work", jsonHandler(a.submitWork))
236         m.Handle("/set-mining", jsonHandler(a.setMining))
237
238         handler := latencyHandler(m, walletEnable)
239         handler = maxBytesHandler(handler) // TODO(tessr): consider moving this to non-core specific mux
240         handler = webAssetsHandler(handler)
241         handler = gzip.Handler{Handler: handler}
242
243         a.handler = handler
244 }
245
246 func maxBytesHandler(h http.Handler) http.Handler {
247         const maxReqSize = 1e7 // 10MB
248         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
249                 // A block can easily be bigger than maxReqSize, but everything
250                 // else should be pretty small.
251                 if req.URL.Path != crosscoreRPCPrefix+"signer/sign-block" {
252                         req.Body = http.MaxBytesReader(w, req.Body, maxReqSize)
253                 }
254                 h.ServeHTTP(w, req)
255         })
256 }
257
258 // json Handler
259 func jsonHandler(f interface{}) http.Handler {
260         h, err := httpjson.Handler(f, errorFormatter.Write)
261         if err != nil {
262                 panic(err)
263         }
264         return h
265 }
266
267 // error Handler
268 func alwaysError(err error) http.Handler {
269         return jsonHandler(func() error { return err })
270 }
271
272 func webAssetsHandler(next http.Handler) http.Handler {
273         mux := http.NewServeMux()
274         mux.Handle("/dashboard/", http.StripPrefix("/dashboard/", static.Handler{
275                 Assets:  dashboard.Files,
276                 Default: "index.html",
277         }))
278         mux.Handle("/", next)
279
280         return mux
281 }
282
283 // AuthHandler access token auth Handler
284 func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore) http.Handler {
285         authenticator := authn.NewAPI(accessTokens)
286
287         return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
288                 // TODO(tessr): check that this path exists; return early if this path isn't legit
289                 req, err := authenticator.Authenticate(req)
290                 if err != nil {
291                         log.WithField("error", errors.Wrap(err, "Serve")).Error("Authenticate fail")
292                         err = errors.Sub(errNotAuthenticated, err)
293                         errorFormatter.Write(req.Context(), rw, err)
294                         return
295                 }
296                 handler.ServeHTTP(rw, req)
297         })
298 }
299
300 // RedirectHandler redirect to dashboard handler
301 func RedirectHandler(next http.Handler) http.Handler {
302         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
303                 if req.URL.Path == "/" {
304                         http.Redirect(w, req, "/dashboard/", http.StatusFound)
305                         return
306                 }
307                 next.ServeHTTP(w, req)
308         })
309 }
310
311 // latencyHandler take latency for the request url path, and redirect url path to wait-disable when wallet is closed
312 func latencyHandler(m *http.ServeMux, walletEnable bool) http.Handler {
313         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
314                 // latency for the request url path
315                 if l := latency(m, req); l != nil {
316                         defer l.RecordSince(time.Now())
317                 }
318
319                 // when the wallet is not been opened and the url path is not been found, modify url path to error,
320                 // and redirect handler to error
321                 if _, pattern := m.Handler(req); pattern != req.URL.Path && !walletEnable {
322                         req.URL.Path = "/error"
323                         walletRedirectHandler(w, req)
324                         return
325                 }
326
327                 m.ServeHTTP(w, req)
328         })
329 }
330
331 // walletRedirectHandler redirect to error when the wallet is closed
332 func walletRedirectHandler(w http.ResponseWriter, req *http.Request) {
333         h := http.RedirectHandler(req.URL.String(), http.StatusMovedPermanently)
334         h.ServeHTTP(w, req)
335 }