OSDN Git Service

Merge pull request #41 from Bytom/dev
[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/net/http/authn"
22         "github.com/vapor/net/http/gzip"
23         "github.com/vapor/net/http/httpjson"
24         "github.com/vapor/net/http/static"
25         "github.com/vapor/net/websocket"
26         "github.com/vapor/netsync"
27         "github.com/vapor/protocol"
28         "github.com/vapor/protocol/bc"
29         "github.com/vapor/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 )
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 = err.Error()
76         } else {
77                 response.Code = respErrFormatter[ErrDefault].ChainCode
78                 response.Msg = respErrFormatter[ErrDefault].Message
79                 response.ErrorDetail = err.Error()
80         }
81         return response
82 }
83
84 //NewErrorResponse error response
85 func NewErrorResponse(err error) Response {
86         response := FormatErrResp(err)
87         return response
88 }
89
90 type waitHandler struct {
91         h  http.Handler
92         wg sync.WaitGroup
93 }
94
95 func (wh *waitHandler) Set(h http.Handler) {
96         wh.h = h
97         wh.wg.Done()
98 }
99
100 func (wh *waitHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
101         wh.wg.Wait()
102         wh.h.ServeHTTP(w, req)
103 }
104
105 // API is the scheduling center for server
106 type API struct {
107         sync          *netsync.SyncManager
108         wallet        *wallet.Wallet
109         accessTokens  *accesstoken.CredentialStore
110         chain         *protocol.Chain
111         server        *http.Server
112         handler       http.Handler
113         txFeedTracker *txfeed.Tracker
114         //cpuMiner        *cpuminer.CPUMiner
115         miner           *miner.Miner
116         notificationMgr *websocket.WSNotificationManager
117         newBlockCh      chan *bc.Hash
118 }
119
120 func (a *API) initServer(config *cfg.Config) {
121         // The waitHandler accepts incoming requests, but blocks until its underlying
122         // handler is set, when the second phase is complete.
123         var coreHandler waitHandler
124         var handler http.Handler
125
126         coreHandler.wg.Add(1)
127         mux := http.NewServeMux()
128         mux.Handle("/", &coreHandler)
129
130         handler = AuthHandler(mux, a.accessTokens, config.Auth.Disable)
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, miner *miner.Miner, chain *protocol.Chain, config *cfg.Config, token *accesstoken.CredentialStore, newBlockCh chan *bc.Hash, notificationMgr *websocket.WSNotificationManager) *API {
172         api := &API{
173                 sync:          sync,
174                 wallet:        wallet,
175                 chain:         chain,
176                 accessTokens:  token,
177                 txFeedTracker: txfeeds,
178                 miner:         miner,
179
180                 newBlockCh:      newBlockCh,
181                 notificationMgr: notificationMgr,
182         }
183         api.buildHandler()
184         api.initServer(config)
185
186         return api
187 }
188
189 func (a *API) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
190         a.handler.ServeHTTP(rw, req)
191 }
192
193 // buildHandler is in charge of all the rpc handling.
194 func (a *API) buildHandler() {
195         walletEnable := false
196         m := http.NewServeMux()
197         if a.wallet != nil {
198                 walletEnable = true
199
200                 m.Handle("/create-account", jsonHandler(a.createAccount))
201                 m.Handle("/update-account-alias", jsonHandler(a.updateAccountAlias))
202                 m.Handle("/list-accounts", jsonHandler(a.listAccounts))
203                 m.Handle("/delete-account", jsonHandler(a.deleteAccount))
204
205                 m.Handle("/create-account-receiver", jsonHandler(a.createAccountReceiver))
206                 m.Handle("/list-addresses", jsonHandler(a.listAddresses))
207                 m.Handle("/validate-address", jsonHandler(a.validateAddress))
208                 m.Handle("/list-pubkeys", jsonHandler(a.listPubKeys))
209
210                 m.Handle("/get-mining-address", jsonHandler(a.getMiningAddress))
211                 m.Handle("/set-mining-address", jsonHandler(a.setMiningAddress))
212
213                 m.Handle("/get-coinbase-arbitrary", jsonHandler(a.getCoinbaseArbitrary))
214                 m.Handle("/set-coinbase-arbitrary", jsonHandler(a.setCoinbaseArbitrary))
215
216                 m.Handle("/create-asset", jsonHandler(a.createAsset))
217                 m.Handle("/update-asset-alias", jsonHandler(a.updateAssetAlias))
218                 m.Handle("/get-asset", jsonHandler(a.getAsset))
219                 m.Handle("/list-assets", jsonHandler(a.listAssets))
220
221                 m.Handle("/create-key", jsonHandler(a.pseudohsmCreateKey))
222                 m.Handle("/update-key-alias", jsonHandler(a.pseudohsmUpdateKeyAlias))
223                 m.Handle("/list-keys", jsonHandler(a.pseudohsmListKeys))
224                 m.Handle("/delete-key", jsonHandler(a.pseudohsmDeleteKey))
225                 m.Handle("/reset-key-password", jsonHandler(a.pseudohsmResetPassword))
226                 m.Handle("/check-key-password", jsonHandler(a.pseudohsmCheckPassword))
227                 m.Handle("/sign-message", jsonHandler(a.signMessage))
228
229                 m.Handle("/build-transaction", jsonHandler(a.build))
230                 m.Handle("/build-chain-transactions", jsonHandler(a.buildChainTxs))
231                 m.Handle("/sign-transaction", jsonHandler(a.signTemplate))
232                 m.Handle("/sign-transactions", jsonHandler(a.signTemplates))
233
234                 m.Handle("/get-transaction", jsonHandler(a.getTransaction))
235                 m.Handle("/list-transactions", jsonHandler(a.listTransactions))
236
237                 m.Handle("/list-balances", jsonHandler(a.listBalances))
238                 m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
239
240                 m.Handle("/decode-program", jsonHandler(a.decodeProgram))
241
242                 m.Handle("/backup-wallet", jsonHandler(a.backupWalletImage))
243                 m.Handle("/restore-wallet", jsonHandler(a.restoreWalletImage))
244                 m.Handle("/rescan-wallet", jsonHandler(a.rescanWallet))
245                 m.Handle("/wallet-info", jsonHandler(a.getWalletInfo))
246                 m.Handle("/recovery-wallet", jsonHandler(a.recoveryFromRootXPubs))
247
248                 m.Handle("/get-pegin-address", jsonHandler(a.getPeginAddress))
249                 m.Handle("/get-pegin-contract-address", jsonHandler(a.getPeginContractAddress))
250                 m.Handle("/claim-pegin-transaction", jsonHandler(a.claimContractPeginTx))
251                 m.Handle("/create-key-pair", jsonHandler(a.createXKeys))
252                 m.Handle("/get-utxo-from-transaction", jsonHandler(a.getUnspentOutputs))
253                 m.Handle("/get-side-raw-transaction", jsonHandler(a.getSideRawTransaction))
254                 m.Handle("/build-mainchain-tx", jsonHandler(a.buildMainChainTxForContract))
255                 m.Handle("/sign-with-key", jsonHandler(a.signWithKey))
256                 m.Handle("/sign-with-xprv", jsonHandler(a.signWithPriKey))
257                 // listdelegates
258                 m.Handle("/list-delegates", jsonHandler(a.listDelegates))
259                 // getdelegatevotes
260                 m.Handle("/get-delegate-votes", jsonHandler(a.getDelegateVotes))
261                 // listvoteddelegates
262                 m.Handle("/list-voted-delegates", jsonHandler(a.listVotedDelegates))
263                 // listreceivedvotes
264                 m.Handle("/list-received-votes", jsonHandler(a.listReceivedVotes))
265
266                 m.Handle("/get-address-balance", jsonHandler(a.getAddressBalance))
267         } else {
268                 log.Warn("Please enable wallet")
269         }
270
271         m.Handle("/", alwaysError(errors.New("not Found")))
272         m.Handle("/error", jsonHandler(a.walletError))
273
274         m.Handle("/create-access-token", jsonHandler(a.createAccessToken))
275         m.Handle("/list-access-tokens", jsonHandler(a.listAccessTokens))
276         m.Handle("/delete-access-token", jsonHandler(a.deleteAccessToken))
277         m.Handle("/check-access-token", jsonHandler(a.checkAccessToken))
278
279         m.Handle("/create-transaction-feed", jsonHandler(a.createTxFeed))
280         m.Handle("/get-transaction-feed", jsonHandler(a.getTxFeed))
281         m.Handle("/update-transaction-feed", jsonHandler(a.updateTxFeed))
282         m.Handle("/delete-transaction-feed", jsonHandler(a.deleteTxFeed))
283         m.Handle("/list-transaction-feeds", jsonHandler(a.listTxFeeds))
284
285         m.Handle("/submit-transaction", jsonHandler(a.submit))
286         m.Handle("/submit-transactions", jsonHandler(a.submitTxs))
287         m.Handle("/estimate-transaction-gas", jsonHandler(a.estimateTxGas))
288
289         m.Handle("/get-unconfirmed-transaction", jsonHandler(a.getUnconfirmedTx))
290         m.Handle("/list-unconfirmed-transactions", jsonHandler(a.listUnconfirmedTxs))
291         m.Handle("/decode-raw-transaction", jsonHandler(a.decodeRawTransaction))
292         m.Handle("/get-raw-transaction", jsonHandler(a.getRawTransaction))
293
294         m.Handle("/get-block", jsonHandler(a.getBlock))
295         m.Handle("/get-raw-block", jsonHandler(a.getRawBlock))
296         m.Handle("/get-block-hash", jsonHandler(a.getBestBlockHash))
297         m.Handle("/get-block-header", jsonHandler(a.getBlockHeader))
298         m.Handle("/get-block-count", jsonHandler(a.getBlockCount))
299         m.Handle("/get-difficulty", jsonHandler(a.getDifficulty))
300         m.Handle("/get-hash-rate", jsonHandler(a.getHashRate))
301
302         m.Handle("/is-mining", jsonHandler(a.isMining))
303         m.Handle("/set-mining", jsonHandler(a.setMining))
304
305         m.Handle("/verify-message", jsonHandler(a.verifyMessage))
306         m.Handle("/compile", jsonHandler(a.compileEquity))
307
308         m.Handle("/gas-rate", jsonHandler(a.gasRate))
309         m.Handle("/net-info", jsonHandler(a.getNetInfo))
310
311         m.Handle("/list-peers", jsonHandler(a.listPeers))
312         m.Handle("/disconnect-peer", jsonHandler(a.disconnectPeer))
313         m.Handle("/connect-peer", jsonHandler(a.connectPeer))
314
315         m.Handle("/get-merkle-proof", jsonHandler(a.getMerkleProof))
316
317         m.HandleFunc("/websocket-subscribe", a.websocketHandler)
318
319         handler := latencyHandler(m, walletEnable)
320         handler = webAssetsHandler(handler)
321         handler = gzip.Handler{Handler: handler}
322
323         a.handler = handler
324 }
325
326 // json Handler
327 func jsonHandler(f interface{}) http.Handler {
328         h, err := httpjson.Handler(f, errorFormatter.Write)
329         if err != nil {
330                 panic(err)
331         }
332         return h
333 }
334
335 // error Handler
336 func alwaysError(err error) http.Handler {
337         return jsonHandler(func() error { return err })
338 }
339
340 func webAssetsHandler(next http.Handler) http.Handler {
341         mux := http.NewServeMux()
342         mux.Handle("/dashboard/", http.StripPrefix("/dashboard/", static.Handler{
343                 Assets:  dashboard.Files,
344                 Default: "index.html",
345         }))
346         mux.Handle("/equity/", http.StripPrefix("/equity/", static.Handler{
347                 Assets:  equity.Files,
348                 Default: "index.html",
349         }))
350         mux.Handle("/", next)
351
352         return mux
353 }
354
355 // AuthHandler access token auth Handler
356 func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore, authDisable bool) http.Handler {
357         authenticator := authn.NewAPI(accessTokens, authDisable)
358
359         return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
360                 // TODO(tessr): check that this path exists; return early if this path isn't legit
361                 req, err := authenticator.Authenticate(req)
362                 if err != nil {
363                         log.WithField("error", errors.Wrap(err, "Serve")).Error("Authenticate fail")
364                         err = errors.WithDetail(errNotAuthenticated, err.Error())
365                         errorFormatter.Write(req.Context(), rw, err)
366                         return
367                 }
368                 handler.ServeHTTP(rw, req)
369         })
370 }
371
372 // RedirectHandler redirect to dashboard handler
373 func RedirectHandler(next http.Handler) http.Handler {
374         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
375                 if req.URL.Path == "/" {
376                         http.Redirect(w, req, "/dashboard/", http.StatusFound)
377                         return
378                 }
379                 next.ServeHTTP(w, req)
380         })
381 }
382
383 // latencyHandler take latency for the request url path, and redirect url path to wait-disable when wallet is closed
384 func latencyHandler(m *http.ServeMux, walletEnable bool) http.Handler {
385         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
386                 // latency for the request url path
387                 if l := latency(m, req); l != nil {
388                         defer l.RecordSince(time.Now())
389                 }
390
391                 // when the wallet is not been opened and the url path is not been found, modify url path to error,
392                 // and redirect handler to error
393                 if _, pattern := m.Handler(req); pattern != req.URL.Path && !walletEnable {
394                         req.URL.Path = "/error"
395                         walletRedirectHandler(w, req)
396                         return
397                 }
398
399                 m.ServeHTTP(w, req)
400         })
401 }
402
403 // walletRedirectHandler redirect to error when the wallet is closed
404 func walletRedirectHandler(w http.ResponseWriter, req *http.Request) {
405         h := http.RedirectHandler(req.URL.String(), http.StatusMovedPermanently)
406         h.ServeHTTP(w, req)
407 }