OSDN Git Service

Merge pull request #1046 from Bytom/dev
[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 //NewErrorResponse error response
59 func NewErrorResponse(err error) Response {
60         root := errors.Root(err)
61         if info, ok := respErrFormatter[root]; ok {
62                 return Response{
63                         Status:      FAIL,
64                         Code:        info.ChainCode,
65                         Msg:         info.Message,
66                         ErrorDetail: errors.Detail(err),
67                 }
68         }
69         return Response{
70                 Status:      FAIL,
71                 Msg:         errors.Detail(err),
72                 ErrorDetail: errors.Detail(err),
73         }
74 }
75
76 type waitHandler struct {
77         h  http.Handler
78         wg sync.WaitGroup
79 }
80
81 func (wh *waitHandler) Set(h http.Handler) {
82         wh.h = h
83         wh.wg.Done()
84 }
85
86 func (wh *waitHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
87         wh.wg.Wait()
88         wh.h.ServeHTTP(w, req)
89 }
90
91 // API is the scheduling center for server
92 type API struct {
93         sync          *netsync.SyncManager
94         wallet        *wallet.Wallet
95         accessTokens  *accesstoken.CredentialStore
96         chain         *protocol.Chain
97         server        *http.Server
98         handler       http.Handler
99         txFeedTracker *txfeed.Tracker
100         cpuMiner      *cpuminer.CPUMiner
101         miningPool    *miningpool.MiningPool
102 }
103
104 func (a *API) initServer(config *cfg.Config) {
105         // The waitHandler accepts incoming requests, but blocks until its underlying
106         // handler is set, when the second phase is complete.
107         var coreHandler waitHandler
108         var handler http.Handler
109
110         coreHandler.wg.Add(1)
111         mux := http.NewServeMux()
112         mux.Handle("/", &coreHandler)
113
114         handler = mux
115         if config.Auth.Disable == false {
116                 handler = AuthHandler(handler, a.accessTokens)
117         }
118         handler = RedirectHandler(handler)
119
120         secureheader.DefaultConfig.PermitClearLoopback = true
121         secureheader.DefaultConfig.HTTPSRedirect = false
122         secureheader.DefaultConfig.Next = handler
123
124         a.server = &http.Server{
125                 // Note: we should not set TLSConfig here;
126                 // we took care of TLS with the listener in maybeUseTLS.
127                 Handler:      secureheader.DefaultConfig,
128                 ReadTimeout:  httpReadTimeout,
129                 WriteTimeout: httpWriteTimeout,
130                 // Disable HTTP/2 for now until the Go implementation is more stable.
131                 // https://github.com/golang/go/issues/16450
132                 // https://github.com/golang/go/issues/17071
133                 TLSNextProto: map[string]func(*http.Server, *tls.Conn, http.Handler){},
134         }
135
136         coreHandler.Set(a)
137 }
138
139 // StartServer start the server
140 func (a *API) StartServer(address string) {
141         log.WithField("api address:", address).Info("Rpc listen")
142         listener, err := net.Listen("tcp", address)
143         if err != nil {
144                 cmn.Exit(cmn.Fmt("Failed to register tcp port: %v", err))
145         }
146
147         // The `Serve` call has to happen in its own goroutine because
148         // it's blocking and we need to proceed to the rest of the core setup after
149         // we call it.
150         go func() {
151                 if err := a.server.Serve(listener); err != nil {
152                         log.WithField("error", errors.Wrap(err, "Serve")).Error("Rpc server")
153                 }
154         }()
155 }
156
157 // NewAPI create and initialize the API
158 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 {
159         api := &API{
160                 sync:          sync,
161                 wallet:        wallet,
162                 chain:         chain,
163                 accessTokens:  token,
164                 txFeedTracker: txfeeds,
165                 cpuMiner:      cpuMiner,
166                 miningPool:    miningPool,
167         }
168         api.buildHandler()
169         api.initServer(config)
170
171         return api
172 }
173
174 func (a *API) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
175         a.handler.ServeHTTP(rw, req)
176 }
177
178 // buildHandler is in charge of all the rpc handling.
179 func (a *API) buildHandler() {
180         walletEnable := false
181         m := http.NewServeMux()
182         if a.wallet != nil {
183                 walletEnable = true
184
185                 m.Handle("/create-account", jsonHandler(a.createAccount))
186                 m.Handle("/list-accounts", jsonHandler(a.listAccounts))
187                 m.Handle("/delete-account", jsonHandler(a.deleteAccount))
188
189                 m.Handle("/create-account-receiver", jsonHandler(a.createAccountReceiver))
190                 m.Handle("/list-addresses", jsonHandler(a.listAddresses))
191                 m.Handle("/validate-address", jsonHandler(a.validateAddress))
192
193                 m.Handle("/create-asset", jsonHandler(a.createAsset))
194                 m.Handle("/update-asset-alias", jsonHandler(a.updateAssetAlias))
195                 m.Handle("/get-asset", jsonHandler(a.getAsset))
196                 m.Handle("/list-assets", jsonHandler(a.listAssets))
197
198                 m.Handle("/create-key", jsonHandler(a.pseudohsmCreateKey))
199                 m.Handle("/list-keys", jsonHandler(a.pseudohsmListKeys))
200                 m.Handle("/delete-key", jsonHandler(a.pseudohsmDeleteKey))
201                 m.Handle("/reset-key-password", jsonHandler(a.pseudohsmResetPassword))
202                 m.Handle("/sign-message", jsonHandler(a.signMessage))
203
204                 m.Handle("/build-transaction", jsonHandler(a.build))
205                 m.Handle("/sign-transaction", jsonHandler(a.pseudohsmSignTemplates))
206
207                 m.Handle("/get-transaction", jsonHandler(a.getTransaction))
208                 m.Handle("/list-transactions", jsonHandler(a.listTransactions))
209
210                 m.Handle("/list-balances", jsonHandler(a.listBalances))
211                 m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
212
213                 m.Handle("/backup-wallet", jsonHandler(a.backupWalletImage))
214                 m.Handle("/restore-wallet", jsonHandler(a.restoreWalletImage))
215         } else {
216                 log.Warn("Please enable wallet")
217         }
218
219         m.Handle("/", alwaysError(errors.New("not Found")))
220         m.Handle("/error", jsonHandler(a.walletError))
221
222         m.Handle("/create-access-token", jsonHandler(a.createAccessToken))
223         m.Handle("/list-access-tokens", jsonHandler(a.listAccessTokens))
224         m.Handle("/delete-access-token", jsonHandler(a.deleteAccessToken))
225         m.Handle("/check-access-token", jsonHandler(a.checkAccessToken))
226
227         m.Handle("/create-transaction-feed", jsonHandler(a.createTxFeed))
228         m.Handle("/get-transaction-feed", jsonHandler(a.getTxFeed))
229         m.Handle("/update-transaction-feed", jsonHandler(a.updateTxFeed))
230         m.Handle("/delete-transaction-feed", jsonHandler(a.deleteTxFeed))
231         m.Handle("/list-transaction-feeds", jsonHandler(a.listTxFeeds))
232
233         m.Handle("/submit-transaction", jsonHandler(a.submit))
234         m.Handle("/estimate-transaction-gas", jsonHandler(a.estimateTxGas))
235
236         m.Handle("/get-unconfirmed-transaction", jsonHandler(a.getUnconfirmedTx))
237         m.Handle("/list-unconfirmed-transactions", jsonHandler(a.listUnconfirmedTxs))
238         m.Handle("/decode-raw-transaction", jsonHandler(a.decodeRawTransaction))
239
240         m.Handle("/get-block-hash", jsonHandler(a.getBestBlockHash))
241         m.Handle("/get-block-header", jsonHandler(a.getBlockHeader))
242         m.Handle("/get-block", jsonHandler(a.getBlock))
243         m.Handle("/get-block-count", jsonHandler(a.getBlockCount))
244         m.Handle("/get-difficulty", jsonHandler(a.getDifficulty))
245         m.Handle("/get-hash-rate", jsonHandler(a.getHashRate))
246
247         m.Handle("/is-mining", jsonHandler(a.isMining))
248         m.Handle("/set-mining", jsonHandler(a.setMining))
249
250         m.Handle("/get-work", jsonHandler(a.getWork))
251         m.Handle("/get-work-json", jsonHandler(a.getWorkJSON))
252         m.Handle("/submit-work", jsonHandler(a.submitWork))
253         m.Handle("/submit-work-json", jsonHandler(a.submitWorkJSON))
254
255         m.Handle("/verify-message", jsonHandler(a.verifyMessage))
256         m.Handle("/decode-program", jsonHandler(a.decodeProgram))
257
258         m.Handle("/gas-rate", jsonHandler(a.gasRate))
259         m.Handle("/net-info", jsonHandler(a.getNetInfo))
260
261         handler := latencyHandler(m, walletEnable)
262         handler = maxBytesHandler(handler) // TODO(tessr): consider moving this to non-core specific mux
263         handler = webAssetsHandler(handler)
264         handler = gzip.Handler{Handler: handler}
265
266         a.handler = handler
267 }
268
269 func maxBytesHandler(h http.Handler) http.Handler {
270         const maxReqSize = 1e7 // 10MB
271         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
272                 // A block can easily be bigger than maxReqSize, but everything
273                 // else should be pretty small.
274                 if req.URL.Path != crosscoreRPCPrefix+"signer/sign-block" {
275                         req.Body = http.MaxBytesReader(w, req.Body, maxReqSize)
276                 }
277                 h.ServeHTTP(w, req)
278         })
279 }
280
281 // json Handler
282 func jsonHandler(f interface{}) http.Handler {
283         h, err := httpjson.Handler(f, errorFormatter.Write)
284         if err != nil {
285                 panic(err)
286         }
287         return h
288 }
289
290 // error Handler
291 func alwaysError(err error) http.Handler {
292         return jsonHandler(func() error { return err })
293 }
294
295 func webAssetsHandler(next http.Handler) http.Handler {
296         mux := http.NewServeMux()
297         mux.Handle("/dashboard/", http.StripPrefix("/dashboard/", static.Handler{
298                 Assets:  dashboard.Files,
299                 Default: "index.html",
300         }))
301         mux.Handle("/", next)
302
303         return mux
304 }
305
306 // AuthHandler access token auth Handler
307 func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore) http.Handler {
308         authenticator := authn.NewAPI(accessTokens)
309
310         return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
311                 // TODO(tessr): check that this path exists; return early if this path isn't legit
312                 req, err := authenticator.Authenticate(req)
313                 if err != nil {
314                         log.WithField("error", errors.Wrap(err, "Serve")).Error("Authenticate fail")
315                         err = errors.Sub(errNotAuthenticated, err)
316                         errorFormatter.Write(req.Context(), rw, err)
317                         return
318                 }
319                 handler.ServeHTTP(rw, req)
320         })
321 }
322
323 // RedirectHandler redirect to dashboard handler
324 func RedirectHandler(next http.Handler) http.Handler {
325         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
326                 if req.URL.Path == "/" {
327                         http.Redirect(w, req, "/dashboard/", http.StatusFound)
328                         return
329                 }
330                 next.ServeHTTP(w, req)
331         })
332 }
333
334 // latencyHandler take latency for the request url path, and redirect url path to wait-disable when wallet is closed
335 func latencyHandler(m *http.ServeMux, walletEnable bool) http.Handler {
336         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
337                 // latency for the request url path
338                 if l := latency(m, req); l != nil {
339                         defer l.RecordSince(time.Now())
340                 }
341
342                 // when the wallet is not been opened and the url path is not been found, modify url path to error,
343                 // and redirect handler to error
344                 if _, pattern := m.Handler(req); pattern != req.URL.Path && !walletEnable {
345                         req.URL.Path = "/error"
346                         walletRedirectHandler(w, req)
347                         return
348                 }
349
350                 m.ServeHTTP(w, req)
351         })
352 }
353
354 // walletRedirectHandler redirect to error when the wallet is closed
355 func walletRedirectHandler(w http.ResponseWriter, req *http.Request) {
356         h := http.RedirectHandler(req.URL.String(), http.StatusMovedPermanently)
357         h.ServeHTTP(w, req)
358 }