OSDN Git Service

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