OSDN Git Service

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