X-Git-Url: http://git.osdn.net/view?p=bytom%2Fvapor.git;a=blobdiff_plain;f=api%2Fapi.go;h=30e71522a50f239708dca23b2ec3c2443f2189d3;hp=937f8f86b2a915fc20557121eaaaef9f7f70796d;hb=2d27cad41ef79da3a46142401b5efcf92133ea1a;hpb=163f05e973d0b209833dc0065588dc07ccc0fe1b diff --git a/api/api.go b/api/api.go index 937f8f86..30e71522 100644 --- a/api/api.go +++ b/api/api.go @@ -17,16 +17,17 @@ import ( "github.com/vapor/dashboard/dashboard" "github.com/vapor/dashboard/equity" "github.com/vapor/errors" - "github.com/vapor/mining/miner" + "github.com/vapor/event" "github.com/vapor/net/http/authn" "github.com/vapor/net/http/gzip" "github.com/vapor/net/http/httpjson" "github.com/vapor/net/http/static" "github.com/vapor/net/websocket" - "github.com/vapor/netsync" + "github.com/vapor/netsync/peers" + "github.com/vapor/p2p" "github.com/vapor/protocol" - "github.com/vapor/protocol/bc" "github.com/vapor/wallet" + "github.com/vapor/proposal/blockproposer" ) var ( @@ -39,7 +40,8 @@ const ( // SUCCESS indicates the rpc calling is successful. SUCCESS = "success" // FAIL indicated the rpc calling is failed. - FAIL = "fail" + FAIL = "fail" + logModule = "api" ) // Response describes the response standard. @@ -104,17 +106,16 @@ func (wh *waitHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { // API is the scheduling center for server type API struct { - sync *netsync.SyncManager - wallet *wallet.Wallet - accessTokens *accesstoken.CredentialStore - chain *protocol.Chain - server *http.Server - handler http.Handler - txFeedTracker *txfeed.Tracker - //cpuMiner *cpuminer.CPUMiner - miner *miner.Miner + sync NetSync + wallet *wallet.Wallet + accessTokens *accesstoken.CredentialStore + chain *protocol.Chain + server *http.Server + handler http.Handler + txFeedTracker *txfeed.Tracker + blockProposer *blockproposer.BlockProposer notificationMgr *websocket.WSNotificationManager - newBlockCh chan *bc.Hash + eventDispatcher *event.Dispatcher } func (a *API) initServer(config *cfg.Config) { @@ -151,7 +152,7 @@ func (a *API) initServer(config *cfg.Config) { // StartServer start the server func (a *API) StartServer(address string) { - log.WithField("api address:", address).Info("Rpc listen") + log.WithFields(log.Fields{"module": logModule, "api address:": address}).Info("Rpc listen") listener, err := net.Listen("tcp", address) if err != nil { cmn.Exit(cmn.Fmt("Failed to register tcp port: %v", err)) @@ -162,22 +163,32 @@ func (a *API) StartServer(address string) { // we call it. go func() { if err := a.server.Serve(listener); err != nil { - log.WithField("error", errors.Wrap(err, "Serve")).Error("Rpc server") + log.WithFields(log.Fields{"module": logModule, "error": errors.Wrap(err, "Serve")}).Error("Rpc server") } }() } +type NetSync interface { + IsListening() bool + IsCaughtUp() bool + PeerCount() int + GetNetwork() string + BestPeer() *peers.PeerInfo + DialPeerWithAddress(addr *p2p.NetAddress) error + GetPeerInfos() []*peers.PeerInfo + StopPeer(peerID string) error +} + // NewAPI create and initialize the API -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 { +func NewAPI(sync NetSync, wallet *wallet.Wallet, txfeeds *txfeed.Tracker, blockProposer *blockproposer.BlockProposer, chain *protocol.Chain, config *cfg.Config, token *accesstoken.CredentialStore, dispatcher *event.Dispatcher, notificationMgr *websocket.WSNotificationManager) *API { api := &API{ - sync: sync, - wallet: wallet, - chain: chain, - accessTokens: token, - txFeedTracker: txfeeds, - miner: miner, - - newBlockCh: newBlockCh, + sync: sync, + wallet: wallet, + chain: chain, + accessTokens: token, + txFeedTracker: txfeeds, + blockProposer: blockProposer, + eventDispatcher: dispatcher, notificationMgr: notificationMgr, } api.buildHandler() @@ -196,7 +207,6 @@ func (a *API) buildHandler() { m := http.NewServeMux() if a.wallet != nil { walletEnable = true - m.Handle("/create-account", jsonHandler(a.createAccount)) m.Handle("/update-account-alias", jsonHandler(a.updateAccountAlias)) m.Handle("/list-accounts", jsonHandler(a.listAccounts)) @@ -213,7 +223,6 @@ func (a *API) buildHandler() { m.Handle("/get-coinbase-arbitrary", jsonHandler(a.getCoinbaseArbitrary)) m.Handle("/set-coinbase-arbitrary", jsonHandler(a.setCoinbaseArbitrary)) - m.Handle("/create-asset", jsonHandler(a.createAsset)) m.Handle("/update-asset-alias", jsonHandler(a.updateAssetAlias)) m.Handle("/get-asset", jsonHandler(a.getAsset)) m.Handle("/list-assets", jsonHandler(a.listAssets)) @@ -244,16 +253,6 @@ func (a *API) buildHandler() { m.Handle("/rescan-wallet", jsonHandler(a.rescanWallet)) m.Handle("/wallet-info", jsonHandler(a.getWalletInfo)) m.Handle("/recovery-wallet", jsonHandler(a.recoveryFromRootXPubs)) - - m.Handle("/get-pegin-address", jsonHandler(a.getPeginAddress)) - m.Handle("/get-pegin-contract-address", jsonHandler(a.getPeginContractAddress)) - m.Handle("/claim-pegin-transaction", jsonHandler(a.claimContractPeginTx)) - m.Handle("/create-key-pair", jsonHandler(a.createXKeys)) - m.Handle("/get-utxo-from-transaction", jsonHandler(a.getUnspentOutputs)) - m.Handle("/get-side-raw-transaction", jsonHandler(a.getSideRawTransaction)) - m.Handle("/build-mainchain-tx", jsonHandler(a.buildMainChainTxForContract)) - m.Handle("/sign-with-key", jsonHandler(a.signWithKey)) - m.Handle("/dpos", jsonHandler(a.dpos)) } else { log.Warn("Please enable wallet") } @@ -279,15 +278,12 @@ func (a *API) buildHandler() { m.Handle("/get-unconfirmed-transaction", jsonHandler(a.getUnconfirmedTx)) m.Handle("/list-unconfirmed-transactions", jsonHandler(a.listUnconfirmedTxs)) m.Handle("/decode-raw-transaction", jsonHandler(a.decodeRawTransaction)) - m.Handle("/get-raw-transaction", jsonHandler(a.getRawTransaction)) m.Handle("/get-block", jsonHandler(a.getBlock)) m.Handle("/get-raw-block", jsonHandler(a.getRawBlock)) m.Handle("/get-block-hash", jsonHandler(a.getBestBlockHash)) m.Handle("/get-block-header", jsonHandler(a.getBlockHeader)) m.Handle("/get-block-count", jsonHandler(a.getBlockCount)) - m.Handle("/get-difficulty", jsonHandler(a.getDifficulty)) - m.Handle("/get-hash-rate", jsonHandler(a.getHashRate)) m.Handle("/is-mining", jsonHandler(a.isMining)) m.Handle("/set-mining", jsonHandler(a.setMining)) @@ -306,10 +302,9 @@ func (a *API) buildHandler() { m.HandleFunc("/websocket-subscribe", a.websocketHandler) - handler := latencyHandler(m, walletEnable) + handler := walletHandler(m, walletEnable) handler = webAssetsHandler(handler) handler = gzip.Handler{Handler: handler} - a.handler = handler } @@ -350,7 +345,7 @@ func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore // TODO(tessr): check that this path exists; return early if this path isn't legit req, err := authenticator.Authenticate(req) if err != nil { - log.WithField("error", errors.Wrap(err, "Serve")).Error("Authenticate fail") + log.WithFields(log.Fields{"module": logModule, "error": errors.Wrap(err, "Serve")}).Error("Authenticate fail") err = errors.WithDetail(errNotAuthenticated, err.Error()) errorFormatter.Write(req.Context(), rw, err) return @@ -370,14 +365,8 @@ func RedirectHandler(next http.Handler) http.Handler { }) } -// latencyHandler take latency for the request url path, and redirect url path to wait-disable when wallet is closed -func latencyHandler(m *http.ServeMux, walletEnable bool) http.Handler { +func walletHandler(m *http.ServeMux, walletEnable bool) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - // latency for the request url path - if l := latency(m, req); l != nil { - defer l.RecordSince(time.Now()) - } - // when the wallet is not been opened and the url path is not been found, modify url path to error, // and redirect handler to error if _, pattern := m.Handler(req); pattern != req.URL.Path && !walletEnable {