OSDN Git Service

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