OSDN Git Service

add dpos consensus
[bytom/vapor.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/vapor/accesstoken"
15         "github.com/vapor/blockchain/txfeed"
16         cfg "github.com/vapor/config"
17         "github.com/vapor/dashboard/dashboard"
18         "github.com/vapor/dashboard/equity"
19         "github.com/vapor/errors"
20         "github.com/vapor/mining/miner"
21         "github.com/vapor/mining/miningpool"
22         "github.com/vapor/net/http/authn"
23         "github.com/vapor/net/http/gzip"
24         "github.com/vapor/net/http/httpjson"
25         "github.com/vapor/net/http/static"
26         "github.com/vapor/net/websocket"
27         "github.com/vapor/netsync"
28         "github.com/vapor/protocol"
29         "github.com/vapor/protocol/bc"
30         "github.com/vapor/wallet"
31 )
32
33 var (
34         errNotAuthenticated = errors.New("not authenticated")
35         httpReadTimeout     = 2 * time.Minute
36         httpWriteTimeout    = time.Hour
37 )
38
39 const (
40         // SUCCESS indicates the rpc calling is successful.
41         SUCCESS = "success"
42         // FAIL indicated the rpc calling is failed.
43         FAIL = "fail"
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         miner           *miner.Miner
117         miningPool      *miningpool.MiningPool
118         notificationMgr *websocket.WSNotificationManager
119         newBlockCh      chan *bc.Hash
120 }
121
122 func (a *API) initServer(config *cfg.Config) {
123         // The waitHandler accepts incoming requests, but blocks until its underlying
124         // handler is set, when the second phase is complete.
125         var coreHandler waitHandler
126         var handler http.Handler
127
128         coreHandler.wg.Add(1)
129         mux := http.NewServeMux()
130         mux.Handle("/", &coreHandler)
131
132         handler = AuthHandler(mux, a.accessTokens, config.Auth.Disable)
133         handler = RedirectHandler(handler)
134
135         secureheader.DefaultConfig.PermitClearLoopback = true
136         secureheader.DefaultConfig.HTTPSRedirect = false
137         secureheader.DefaultConfig.Next = handler
138
139         a.server = &http.Server{
140                 // Note: we should not set TLSConfig here;
141                 // we took care of TLS with the listener in maybeUseTLS.
142                 Handler:      secureheader.DefaultConfig,
143                 ReadTimeout:  httpReadTimeout,
144                 WriteTimeout: httpWriteTimeout,
145                 // Disable HTTP/2 for now until the Go implementation is more stable.
146                 // https://github.com/golang/go/issues/16450
147                 // https://github.com/golang/go/issues/17071
148                 TLSNextProto: map[string]func(*http.Server, *tls.Conn, http.Handler){},
149         }
150
151         coreHandler.Set(a)
152 }
153
154 // StartServer start the server
155 func (a *API) StartServer(address string) {
156         log.WithField("api address:", address).Info("Rpc listen")
157         listener, err := net.Listen("tcp", address)
158         if err != nil {
159                 cmn.Exit(cmn.Fmt("Failed to register tcp port: %v", err))
160         }
161
162         // The `Serve` call has to happen in its own goroutine because
163         // it's blocking and we need to proceed to the rest of the core setup after
164         // we call it.
165         go func() {
166                 if err := a.server.Serve(listener); err != nil {
167                         log.WithField("error", errors.Wrap(err, "Serve")).Error("Rpc server")
168                 }
169         }()
170 }
171
172 // NewAPI create and initialize the API
173 func NewAPI(sync *netsync.SyncManager, wallet *wallet.Wallet, txfeeds *txfeed.Tracker, miner *miner.Miner, miningPool *miningpool.MiningPool, chain *protocol.Chain, config *cfg.Config, token *accesstoken.CredentialStore, newBlockCh chan *bc.Hash, notificationMgr *websocket.WSNotificationManager) *API {
174         api := &API{
175                 sync:          sync,
176                 wallet:        wallet,
177                 chain:         chain,
178                 accessTokens:  token,
179                 txFeedTracker: txfeeds,
180                 miner:         miner,
181                 miningPool:    miningPool,
182
183                 newBlockCh:      newBlockCh,
184                 notificationMgr: notificationMgr,
185         }
186         api.buildHandler()
187         api.initServer(config)
188
189         return api
190 }
191
192 func (a *API) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
193         a.handler.ServeHTTP(rw, req)
194 }
195
196 // buildHandler is in charge of all the rpc handling.
197 func (a *API) buildHandler() {
198         walletEnable := false
199         m := http.NewServeMux()
200         if a.wallet != nil {
201                 walletEnable = true
202
203                 m.Handle("/create-account", jsonHandler(a.createAccount))
204                 m.Handle("/update-account-alias", jsonHandler(a.updateAccountAlias))
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("/update-key-alias", jsonHandler(a.pseudohsmUpdateKeyAlias))
226                 m.Handle("/list-keys", jsonHandler(a.pseudohsmListKeys))
227                 m.Handle("/delete-key", jsonHandler(a.pseudohsmDeleteKey))
228                 m.Handle("/reset-key-password", jsonHandler(a.pseudohsmResetPassword))
229                 m.Handle("/check-key-password", jsonHandler(a.pseudohsmCheckPassword))
230                 m.Handle("/sign-message", jsonHandler(a.signMessage))
231
232                 m.Handle("/build-transaction", jsonHandler(a.build))
233                 m.Handle("/build-chain-transactions", jsonHandler(a.buildChainTxs))
234                 m.Handle("/sign-transaction", jsonHandler(a.signTemplate))
235                 m.Handle("/sign-transactions", jsonHandler(a.signTemplates))
236
237                 m.Handle("/get-transaction", jsonHandler(a.getTransaction))
238                 m.Handle("/list-transactions", jsonHandler(a.listTransactions))
239
240                 m.Handle("/list-balances", jsonHandler(a.listBalances))
241                 m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
242
243                 m.Handle("/decode-program", jsonHandler(a.decodeProgram))
244
245                 m.Handle("/backup-wallet", jsonHandler(a.backupWalletImage))
246                 m.Handle("/restore-wallet", jsonHandler(a.restoreWalletImage))
247                 m.Handle("/rescan-wallet", jsonHandler(a.rescanWallet))
248                 m.Handle("/wallet-info", jsonHandler(a.getWalletInfo))
249                 m.Handle("/recovery-wallet", jsonHandler(a.recoveryFromRootXPubs))
250
251                 m.Handle("/get-pegin-address", jsonHandler(a.getPeginAddress))
252                 m.Handle("/get-pegin-contract-address", jsonHandler(a.getPeginContractAddress))
253                 m.Handle("/claim-pegin-transaction", jsonHandler(a.claimContractPeginTx))
254                 m.Handle("/create-key-pair", jsonHandler(a.createXKeys))
255                 m.Handle("/get-utxo-from-transaction", jsonHandler(a.getUnspentOutputs))
256                 m.Handle("/get-side-raw-transaction", jsonHandler(a.getSideRawTransaction))
257                 m.Handle("/build-mainchain-tx", jsonHandler(a.buildMainChainTxForContract))
258                 m.Handle("/sign-with-key", jsonHandler(a.signWithKey))
259                 m.Handle("/dpos", jsonHandler(a.dpos))
260         } else {
261                 log.Warn("Please enable wallet")
262         }
263
264         m.Handle("/", alwaysError(errors.New("not Found")))
265         m.Handle("/error", jsonHandler(a.walletError))
266
267         m.Handle("/create-access-token", jsonHandler(a.createAccessToken))
268         m.Handle("/list-access-tokens", jsonHandler(a.listAccessTokens))
269         m.Handle("/delete-access-token", jsonHandler(a.deleteAccessToken))
270         m.Handle("/check-access-token", jsonHandler(a.checkAccessToken))
271
272         m.Handle("/create-transaction-feed", jsonHandler(a.createTxFeed))
273         m.Handle("/get-transaction-feed", jsonHandler(a.getTxFeed))
274         m.Handle("/update-transaction-feed", jsonHandler(a.updateTxFeed))
275         m.Handle("/delete-transaction-feed", jsonHandler(a.deleteTxFeed))
276         m.Handle("/list-transaction-feeds", jsonHandler(a.listTxFeeds))
277
278         m.Handle("/submit-transaction", jsonHandler(a.submit))
279         m.Handle("/submit-transactions", jsonHandler(a.submitTxs))
280         m.Handle("/estimate-transaction-gas", jsonHandler(a.estimateTxGas))
281
282         m.Handle("/get-unconfirmed-transaction", jsonHandler(a.getUnconfirmedTx))
283         m.Handle("/list-unconfirmed-transactions", jsonHandler(a.listUnconfirmedTxs))
284         m.Handle("/decode-raw-transaction", jsonHandler(a.decodeRawTransaction))
285         m.Handle("/get-raw-transaction", jsonHandler(a.getRawTransaction))
286
287         m.Handle("/get-block", jsonHandler(a.getBlock))
288         m.Handle("/get-raw-block", jsonHandler(a.getRawBlock))
289         m.Handle("/get-block-hash", jsonHandler(a.getBestBlockHash))
290         m.Handle("/get-block-header", jsonHandler(a.getBlockHeader))
291         m.Handle("/get-block-count", jsonHandler(a.getBlockCount))
292         m.Handle("/get-difficulty", jsonHandler(a.getDifficulty))
293         m.Handle("/get-hash-rate", jsonHandler(a.getHashRate))
294
295         m.Handle("/is-mining", jsonHandler(a.isMining))
296         m.Handle("/set-mining", jsonHandler(a.setMining))
297
298         m.Handle("/get-work", jsonHandler(a.getWork))
299         m.Handle("/get-work-json", jsonHandler(a.getWorkJSON))
300         m.Handle("/submit-block", jsonHandler(a.submitBlock))
301         m.Handle("/submit-work", jsonHandler(a.submitWork))
302         m.Handle("/submit-work-json", jsonHandler(a.submitWorkJSON))
303
304         m.Handle("/verify-message", jsonHandler(a.verifyMessage))
305         m.Handle("/compile", jsonHandler(a.compileEquity))
306
307         m.Handle("/gas-rate", jsonHandler(a.gasRate))
308         m.Handle("/net-info", jsonHandler(a.getNetInfo))
309
310         m.Handle("/list-peers", jsonHandler(a.listPeers))
311         m.Handle("/disconnect-peer", jsonHandler(a.disconnectPeer))
312         m.Handle("/connect-peer", jsonHandler(a.connectPeer))
313
314         m.Handle("/get-merkle-proof", jsonHandler(a.getMerkleProof))
315
316         m.HandleFunc("/websocket-subscribe", a.websocketHandler)
317
318         handler := latencyHandler(m, walletEnable)
319         handler = webAssetsHandler(handler)
320         handler = gzip.Handler{Handler: handler}
321
322         a.handler = handler
323 }
324
325 // json Handler
326 func jsonHandler(f interface{}) http.Handler {
327         h, err := httpjson.Handler(f, errorFormatter.Write)
328         if err != nil {
329                 panic(err)
330         }
331         return h
332 }
333
334 // error Handler
335 func alwaysError(err error) http.Handler {
336         return jsonHandler(func() error { return err })
337 }
338
339 func webAssetsHandler(next http.Handler) http.Handler {
340         mux := http.NewServeMux()
341         mux.Handle("/dashboard/", http.StripPrefix("/dashboard/", static.Handler{
342                 Assets:  dashboard.Files,
343                 Default: "index.html",
344         }))
345         mux.Handle("/equity/", http.StripPrefix("/equity/", static.Handler{
346                 Assets:  equity.Files,
347                 Default: "index.html",
348         }))
349         mux.Handle("/", next)
350
351         return mux
352 }
353
354 // AuthHandler access token auth Handler
355 func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore, authDisable bool) http.Handler {
356         authenticator := authn.NewAPI(accessTokens, authDisable)
357
358         return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
359                 // TODO(tessr): check that this path exists; return early if this path isn't legit
360                 req, err := authenticator.Authenticate(req)
361                 if err != nil {
362                         log.WithField("error", errors.Wrap(err, "Serve")).Error("Authenticate fail")
363                         err = errors.WithDetail(errNotAuthenticated, err.Error())
364                         errorFormatter.Write(req.Context(), rw, err)
365                         return
366                 }
367                 handler.ServeHTTP(rw, req)
368         })
369 }
370
371 // RedirectHandler redirect to dashboard handler
372 func RedirectHandler(next http.Handler) http.Handler {
373         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
374                 if req.URL.Path == "/" {
375                         http.Redirect(w, req, "/dashboard/", http.StatusFound)
376                         return
377                 }
378                 next.ServeHTTP(w, req)
379         })
380 }
381
382 // latencyHandler take latency for the request url path, and redirect url path to wait-disable when wallet is closed
383 func latencyHandler(m *http.ServeMux, walletEnable bool) http.Handler {
384         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
385                 // latency for the request url path
386                 if l := latency(m, req); l != nil {
387                         defer l.RecordSince(time.Now())
388                 }
389
390                 // when the wallet is not been opened and the url path is not been found, modify url path to error,
391                 // and redirect handler to error
392                 if _, pattern := m.Handler(req); pattern != req.URL.Path && !walletEnable {
393                         req.URL.Path = "/error"
394                         walletRedirectHandler(w, req)
395                         return
396                 }
397
398                 m.ServeHTTP(w, req)
399         })
400 }
401
402 // walletRedirectHandler redirect to error when the wallet is closed
403 func walletRedirectHandler(w http.ResponseWriter, req *http.Request) {
404         h := http.RedirectHandler(req.URL.String(), http.StatusMovedPermanently)
405         h.ServeHTTP(w, req)
406 }