OSDN Git Service

Merge pull request #702 from Bytom/dev-pool
[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         } else {
202                 log.Warn("Please enable wallet")
203         }
204
205         m.Handle("/", alwaysError(errors.New("not Found")))
206         m.Handle("/error", jsonHandler(a.walletError))
207
208         m.Handle("/net-info", jsonHandler(a.getNetInfo))
209
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))
214
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))
220
221         m.Handle("/get-block-hash", jsonHandler(a.getBestBlockHash))
222         m.Handle("/get-block-header-by-hash", jsonHandler(a.getBlockHeaderByHash))
223         m.Handle("/get-block-header-by-height", jsonHandler(a.getBlockHeaderByHeight))
224         m.Handle("/get-block", jsonHandler(a.getBlock))
225         m.Handle("/get-block-count", jsonHandler(a.getBlockCount))
226         m.Handle("/get-block-transactions-count-by-hash", jsonHandler(a.getBlockTransactionsCountByHash))
227         m.Handle("/get-block-transactions-count-by-height", jsonHandler(a.getBlockTransactionsCountByHeight))
228
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))
234
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}
239
240         a.handler = handler
241 }
242
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)
250                 }
251                 h.ServeHTTP(w, req)
252         })
253 }
254
255 // json Handler
256 func jsonHandler(f interface{}) http.Handler {
257         h, err := httpjson.Handler(f, errorFormatter.Write)
258         if err != nil {
259                 panic(err)
260         }
261         return h
262 }
263
264 // error Handler
265 func alwaysError(err error) http.Handler {
266         return jsonHandler(func() error { return err })
267 }
268
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",
274         }))
275         mux.Handle("/", next)
276
277         return mux
278 }
279
280 // AuthHandler access token auth Handler
281 func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore) http.Handler {
282         authenticator := authn.NewAPI(accessTokens)
283
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)
287                 if err != nil {
288                         log.WithField("error", errors.Wrap(err, "Serve")).Error("Authenticate fail")
289                         err = errors.Sub(errNotAuthenticated, err)
290                         errorFormatter.Write(req.Context(), rw, err)
291                         return
292                 }
293                 handler.ServeHTTP(rw, req)
294         })
295 }
296
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)
302                         return
303                 }
304                 next.ServeHTTP(w, req)
305         })
306 }
307
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())
314                 }
315
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)
321                         return
322                 }
323
324                 m.ServeHTTP(w, req)
325         })
326 }
327
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)
331         h.ServeHTTP(w, req)
332 }