OSDN Git Service

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