OSDN Git Service

Add /submit-block
[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/protocol/bc"
29         "github.com/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         crosscoreRPCPrefix = "/rpc/"
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.SyncManager
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         cpuMiner      *cpuminer.CPUMiner
116         miningPool    *miningpool.MiningPool
117
118         newBlockCh chan *bc.Hash
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 = mux
132         if config.Auth.Disable == false {
133                 handler = AuthHandler(handler, a.accessTokens)
134         }
135         handler = RedirectHandler(handler)
136
137         secureheader.DefaultConfig.PermitClearLoopback = true
138         secureheader.DefaultConfig.HTTPSRedirect = false
139         secureheader.DefaultConfig.Next = handler
140
141         a.server = &http.Server{
142                 // Note: we should not set TLSConfig here;
143                 // we took care of TLS with the listener in maybeUseTLS.
144                 Handler:      secureheader.DefaultConfig,
145                 ReadTimeout:  httpReadTimeout,
146                 WriteTimeout: httpWriteTimeout,
147                 // Disable HTTP/2 for now until the Go implementation is more stable.
148                 // https://github.com/golang/go/issues/16450
149                 // https://github.com/golang/go/issues/17071
150                 TLSNextProto: map[string]func(*http.Server, *tls.Conn, http.Handler){},
151         }
152
153         coreHandler.Set(a)
154 }
155
156 // StartServer start the server
157 func (a *API) StartServer(address string) {
158         log.WithField("api address:", address).Info("Rpc listen")
159         listener, err := net.Listen("tcp", address)
160         if err != nil {
161                 cmn.Exit(cmn.Fmt("Failed to register tcp port: %v", err))
162         }
163
164         // The `Serve` call has to happen in its own goroutine because
165         // it's blocking and we need to proceed to the rest of the core setup after
166         // we call it.
167         go func() {
168                 if err := a.server.Serve(listener); err != nil {
169                         log.WithField("error", errors.Wrap(err, "Serve")).Error("Rpc server")
170                 }
171         }()
172 }
173
174 // NewAPI create and initialize the API
175 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, newBlockCh chan *bc.Hash) *API {
176         api := &API{
177                 sync:          sync,
178                 wallet:        wallet,
179                 chain:         chain,
180                 accessTokens:  token,
181                 txFeedTracker: txfeeds,
182                 cpuMiner:      cpuMiner,
183                 miningPool:    miningPool,
184
185                 newBlockCh: newBlockCh,
186         }
187         api.buildHandler()
188         api.initServer(config)
189
190         return api
191 }
192
193 func (a *API) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
194         a.handler.ServeHTTP(rw, req)
195 }
196
197 // buildHandler is in charge of all the rpc handling.
198 func (a *API) buildHandler() {
199         walletEnable := false
200         m := http.NewServeMux()
201         if a.wallet != nil {
202                 walletEnable = true
203
204                 m.Handle("/create-account", jsonHandler(a.createAccount))
205                 m.Handle("/list-accounts", jsonHandler(a.listAccounts))
206                 m.Handle("/delete-account", jsonHandler(a.deleteAccount))
207
208                 m.Handle("/create-account-receiver", jsonHandler(a.createAccountReceiver))
209                 m.Handle("/list-addresses", jsonHandler(a.listAddresses))
210                 m.Handle("/validate-address", jsonHandler(a.validateAddress))
211                 m.Handle("/list-pubkeys", jsonHandler(a.listPubKeys))
212
213                 m.Handle("/get-mining-address", jsonHandler(a.getMiningAddress))
214                 m.Handle("/set-mining-address", jsonHandler(a.setMiningAddress))
215
216                 m.Handle("/get-coinbase-arbitrary", jsonHandler(a.getCoinbaseArbitrary))
217                 m.Handle("/set-coinbase-arbitrary", jsonHandler(a.setCoinbaseArbitrary))
218
219                 m.Handle("/create-asset", jsonHandler(a.createAsset))
220                 m.Handle("/update-asset-alias", jsonHandler(a.updateAssetAlias))
221                 m.Handle("/get-asset", jsonHandler(a.getAsset))
222                 m.Handle("/list-assets", jsonHandler(a.listAssets))
223
224                 m.Handle("/create-key", jsonHandler(a.pseudohsmCreateKey))
225                 m.Handle("/list-keys", jsonHandler(a.pseudohsmListKeys))
226                 m.Handle("/delete-key", jsonHandler(a.pseudohsmDeleteKey))
227                 m.Handle("/reset-key-password", jsonHandler(a.pseudohsmResetPassword))
228                 m.Handle("/check-key-password", jsonHandler(a.pseudohsmCheckPassword))
229                 m.Handle("/sign-message", jsonHandler(a.signMessage))
230
231                 m.Handle("/build-transaction", jsonHandler(a.build))
232                 m.Handle("/build-chain-transactions", jsonHandler(a.buildChainTxs))
233                 m.Handle("/sign-transaction", jsonHandler(a.signTemplate))
234                 m.Handle("/sign-transactions", jsonHandler(a.signTemplates))
235
236                 m.Handle("/get-transaction", jsonHandler(a.getTransaction))
237                 m.Handle("/list-transactions", jsonHandler(a.listTransactions))
238
239                 m.Handle("/list-balances", jsonHandler(a.listBalances))
240                 m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
241
242                 m.Handle("/decode-program", jsonHandler(a.decodeProgram))
243
244                 m.Handle("/backup-wallet", jsonHandler(a.backupWalletImage))
245                 m.Handle("/restore-wallet", jsonHandler(a.restoreWalletImage))
246                 m.Handle("/rescan-wallet", jsonHandler(a.rescanWallet))
247                 m.Handle("/wallet-info", jsonHandler(a.getWalletInfo))
248         } else {
249                 log.Warn("Please enable wallet")
250         }
251
252         m.Handle("/", alwaysError(errors.New("not Found")))
253         m.Handle("/error", jsonHandler(a.walletError))
254
255         m.Handle("/create-access-token", jsonHandler(a.createAccessToken))
256         m.Handle("/list-access-tokens", jsonHandler(a.listAccessTokens))
257         m.Handle("/delete-access-token", jsonHandler(a.deleteAccessToken))
258         m.Handle("/check-access-token", jsonHandler(a.checkAccessToken))
259
260         m.Handle("/create-transaction-feed", jsonHandler(a.createTxFeed))
261         m.Handle("/get-transaction-feed", jsonHandler(a.getTxFeed))
262         m.Handle("/update-transaction-feed", jsonHandler(a.updateTxFeed))
263         m.Handle("/delete-transaction-feed", jsonHandler(a.deleteTxFeed))
264         m.Handle("/list-transaction-feeds", jsonHandler(a.listTxFeeds))
265
266         m.Handle("/submit-transaction", jsonHandler(a.submit))
267         m.Handle("/submit-transactions", jsonHandler(a.submitTxs))
268         m.Handle("/estimate-transaction-gas", jsonHandler(a.estimateTxGas))
269
270         m.Handle("/get-unconfirmed-transaction", jsonHandler(a.getUnconfirmedTx))
271         m.Handle("/list-unconfirmed-transactions", jsonHandler(a.listUnconfirmedTxs))
272         m.Handle("/decode-raw-transaction", jsonHandler(a.decodeRawTransaction))
273
274         m.Handle("/get-block", jsonHandler(a.getBlock))
275         m.Handle("/get-raw-block", jsonHandler(a.getRawBlock))
276         m.Handle("/get-block-hash", jsonHandler(a.getBestBlockHash))
277         m.Handle("/get-block-header", jsonHandler(a.getBlockHeader))
278         m.Handle("/get-block-count", jsonHandler(a.getBlockCount))
279         m.Handle("/get-difficulty", jsonHandler(a.getDifficulty))
280         m.Handle("/get-hash-rate", jsonHandler(a.getHashRate))
281
282         m.Handle("/is-mining", jsonHandler(a.isMining))
283         m.Handle("/set-mining", jsonHandler(a.setMining))
284
285         m.Handle("/get-work", jsonHandler(a.getWork))
286         m.Handle("/get-work-json", jsonHandler(a.getWorkJSON))
287         m.Handle("/submit-block", jsonHandler(a.submitBlock))
288         m.Handle("/submit-work", jsonHandler(a.submitWork))
289         m.Handle("/submit-work-json", jsonHandler(a.submitWorkJSON))
290
291         m.Handle("/verify-message", jsonHandler(a.verifyMessage))
292         m.Handle("/compile", jsonHandler(a.compileEquity))
293
294         m.Handle("/gas-rate", jsonHandler(a.gasRate))
295         m.Handle("/net-info", jsonHandler(a.getNetInfo))
296
297         m.Handle("/list-peers", jsonHandler(a.listPeers))
298         m.Handle("/disconnect-peer", jsonHandler(a.disconnectPeer))
299         m.Handle("/connect-peer", jsonHandler(a.connectPeer))
300
301         m.Handle("/get-merkle-proof", jsonHandler(a.getMerkleProof))
302
303         handler := latencyHandler(m, walletEnable)
304         handler = maxBytesHandler(handler) // TODO(tessr): consider moving this to non-core specific mux
305         handler = webAssetsHandler(handler)
306         handler = gzip.Handler{Handler: handler}
307
308         a.handler = handler
309 }
310
311 func maxBytesHandler(h http.Handler) http.Handler {
312         const maxReqSize = 1e7 // 10MB
313         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
314                 // A block can easily be bigger than maxReqSize, but everything
315                 // else should be pretty small.
316                 if req.URL.Path != crosscoreRPCPrefix+"signer/sign-block" {
317                         req.Body = http.MaxBytesReader(w, req.Body, maxReqSize)
318                 }
319                 h.ServeHTTP(w, req)
320         })
321 }
322
323 // json Handler
324 func jsonHandler(f interface{}) http.Handler {
325         h, err := httpjson.Handler(f, errorFormatter.Write)
326         if err != nil {
327                 panic(err)
328         }
329         return h
330 }
331
332 // error Handler
333 func alwaysError(err error) http.Handler {
334         return jsonHandler(func() error { return err })
335 }
336
337 func webAssetsHandler(next http.Handler) http.Handler {
338         mux := http.NewServeMux()
339         mux.Handle("/dashboard/", http.StripPrefix("/dashboard/", static.Handler{
340                 Assets:  dashboard.Files,
341                 Default: "index.html",
342         }))
343         mux.Handle("/equity/", http.StripPrefix("/equity/", static.Handler{
344                 Assets:  equity.Files,
345                 Default: "index.html",
346         }))
347         mux.Handle("/", next)
348
349         return mux
350 }
351
352 // AuthHandler access token auth Handler
353 func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore) http.Handler {
354         authenticator := authn.NewAPI(accessTokens)
355
356         return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
357                 // TODO(tessr): check that this path exists; return early if this path isn't legit
358                 req, err := authenticator.Authenticate(req)
359                 if err != nil {
360                         log.WithField("error", errors.Wrap(err, "Serve")).Error("Authenticate fail")
361                         err = errors.Sub(errNotAuthenticated, err)
362                         errorFormatter.Write(req.Context(), rw, err)
363                         return
364                 }
365                 handler.ServeHTTP(rw, req)
366         })
367 }
368
369 // RedirectHandler redirect to dashboard handler
370 func RedirectHandler(next http.Handler) http.Handler {
371         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
372                 if req.URL.Path == "/" {
373                         http.Redirect(w, req, "/dashboard/", http.StatusFound)
374                         return
375                 }
376                 next.ServeHTTP(w, req)
377         })
378 }
379
380 // latencyHandler take latency for the request url path, and redirect url path to wait-disable when wallet is closed
381 func latencyHandler(m *http.ServeMux, walletEnable bool) http.Handler {
382         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
383                 // latency for the request url path
384                 if l := latency(m, req); l != nil {
385                         defer l.RecordSince(time.Now())
386                 }
387
388                 // when the wallet is not been opened and the url path is not been found, modify url path to error,
389                 // and redirect handler to error
390                 if _, pattern := m.Handler(req); pattern != req.URL.Path && !walletEnable {
391                         req.URL.Path = "/error"
392                         walletRedirectHandler(w, req)
393                         return
394                 }
395
396                 m.ServeHTTP(w, req)
397         })
398 }
399
400 // walletRedirectHandler redirect to error when the wallet is closed
401 func walletRedirectHandler(w http.ResponseWriter, req *http.Request) {
402         h := http.RedirectHandler(req.URL.String(), http.StatusMovedPermanently)
403         h.ServeHTTP(w, req)
404 }