OSDN Git Service

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