OSDN Git Service

when wallet disable, wallet related api redirect to error (#483)
authoroysheng <33340252+oysheng@users.noreply.github.com>
Mon, 26 Mar 2018 09:34:44 +0000 (17:34 +0800)
committerYongfeng LI <wliyongfeng@gmail.com>
Mon, 26 Mar 2018 09:34:44 +0000 (17:34 +0800)
*  *when wallet disable, accesstoken can be call
 *redirect url path to wait-disable when wallet is closed

* fix redirect path to error when wallet is disable

*  move accesstoken from wallet into API

* modify handler value

* add function walletRedirectHandler for latencyHandler

api/accesstokens.go
api/api.go
api/wallet.go
blockchain/reactor.go
node/node.go
wallet/wallet.go

index 3754e09..c0ed7c3 100644 (file)
@@ -10,7 +10,7 @@ func (a *API) createAccessToken(ctx context.Context, x struct {
        ID   string `json:"id"`
        Type string `json:"type"`
 }) Response {
-       token, err := a.wallet.Tokens.Create(ctx, x.ID, x.Type)
+       token, err := a.accessTokens.Create(ctx, x.ID, x.Type)
        if err != nil {
                return NewErrorResponse(err)
        }
@@ -18,7 +18,7 @@ func (a *API) createAccessToken(ctx context.Context, x struct {
 }
 
 func (a *API) listAccessTokens(ctx context.Context) Response {
-       tokens, err := a.wallet.Tokens.List(ctx)
+       tokens, err := a.accessTokens.List(ctx)
        if err != nil {
                log.Errorf("listAccessTokens: %v", err)
                return NewErrorResponse(err)
@@ -32,7 +32,7 @@ func (a *API) deleteAccessToken(ctx context.Context, x struct {
        Token string `json:"token"`
 }) Response {
        //TODO Add delete permission verify.
-       if err := a.wallet.Tokens.Delete(ctx, x.ID); err != nil {
+       if err := a.accessTokens.Delete(ctx, x.ID); err != nil {
                return NewErrorResponse(err)
        }
        return NewSuccessResponse(nil)
@@ -42,7 +42,7 @@ func (a *API) checkAccessToken(ctx context.Context, x struct {
        ID     string `json:"id"`
        Secret string `json:"secret"`
 }) Response {
-       if _, err := a.wallet.Tokens.Check(ctx, x.ID, x.Secret); err != nil {
+       if _, err := a.accessTokens.Check(ctx, x.ID, x.Secret); err != nil {
                return NewErrorResponse(err)
        }
 
index 2ddd718..a242b89 100644 (file)
@@ -69,26 +69,29 @@ func (wh *waitHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
        wh.h.ServeHTTP(w, req)
 }
 
+// API is the scheduling center for server
 type API struct {
-       bcr     *blockchain.BlockchainReactor
-       wallet  *wallet.Wallet
-       chain   *protocol.Chain
-       server  *http.Server
-       handler http.Handler
+       bcr          *blockchain.BlockchainReactor
+       wallet       *wallet.Wallet
+       accessTokens *accesstoken.CredentialStore
+       chain        *protocol.Chain
+       server       *http.Server
+       handler      http.Handler
 }
 
 func (a *API) initServer(config *cfg.Config) {
        // The waitHandler accepts incoming requests, but blocks until its underlying
        // handler is set, when the second phase is complete.
        var coreHandler waitHandler
+       var handler http.Handler
+
        coreHandler.wg.Add(1)
        mux := http.NewServeMux()
        mux.Handle("/", &coreHandler)
 
-       var handler http.Handler = mux
-
+       handler = mux
        if config.Auth.Disable == false {
-               handler = AuthHandler(handler, a.wallet.Tokens)
+               handler = AuthHandler(handler, a.accessTokens)
        }
        handler = RedirectHandler(handler)
 
@@ -111,6 +114,7 @@ func (a *API) initServer(config *cfg.Config) {
        coreHandler.Set(a)
 }
 
+// StartServer start the server
 func (a *API) StartServer(address string) {
        log.WithField("api address:", address).Info("Rpc listen")
        listener, err := net.Listen("tcp", address)
@@ -128,11 +132,13 @@ func (a *API) StartServer(address string) {
        }()
 }
 
-func NewAPI(bcr *blockchain.BlockchainReactor, wallet *wallet.Wallet, chain *protocol.Chain, config *cfg.Config) *API {
+// NewAPI create and initialize the API
+func NewAPI(bcr *blockchain.BlockchainReactor, wallet *wallet.Wallet, chain *protocol.Chain, config *cfg.Config, token *accesstoken.CredentialStore) *API {
        api := &API{
-               bcr:    bcr,
-               wallet: wallet,
-               chain:  chain,
+               bcr:          bcr,
+               wallet:       wallet,
+               chain:        chain,
+               accessTokens: token,
        }
        api.buildHandler()
        api.initServer(config)
@@ -146,14 +152,18 @@ func (a *API) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
 
 // buildHandler is in charge of all the rpc handling.
 func (a *API) buildHandler() {
+       walletEnable := false
        m := http.NewServeMux()
-       if a.wallet != nil && a.wallet.AccountMgr != nil && a.wallet.AssetReg != nil {
+       if a.wallet != nil {
+               walletEnable = true
+
                m.Handle("/create-account", jsonHandler(a.createAccount))
                m.Handle("/update-account-tags", jsonHandler(a.updateAccountTags))
-               m.Handle("/create-account-receiver", jsonHandler(a.createAccountReceiver))
                m.Handle("/list-accounts", jsonHandler(a.listAccounts))
-               m.Handle("/list-addresses", jsonHandler(a.listAddresses))
                m.Handle("/delete-account", jsonHandler(a.deleteAccount))
+
+               m.Handle("/create-account-receiver", jsonHandler(a.createAccountReceiver))
+               m.Handle("/list-addresses", jsonHandler(a.listAddresses))
                m.Handle("/validate-address", jsonHandler(a.validateAddress))
 
                m.Handle("/create-asset", jsonHandler(a.createAsset))
@@ -166,39 +176,41 @@ func (a *API) buildHandler() {
                m.Handle("/delete-key", jsonHandler(a.pseudohsmDeleteKey))
                m.Handle("/reset-key-password", jsonHandler(a.pseudohsmResetPassword))
 
+               m.Handle("/export-private-key", jsonHandler(a.walletExportKey))
+               m.Handle("/import-private-key", jsonHandler(a.walletImportKey))
+               m.Handle("/import-key-progress", jsonHandler(a.keyImportProgress))
+
+               m.Handle("/build-transaction", jsonHandler(a.build))
+               m.Handle("/sign-transaction", jsonHandler(a.pseudohsmSignTemplates))
+               m.Handle("/submit-transaction", jsonHandler(a.submit))
+               m.Handle("/sign-submit-transaction", jsonHandler(a.signSubmit))
                m.Handle("/get-transaction", jsonHandler(a.getTransaction))
                m.Handle("/list-transactions", jsonHandler(a.listTransactions))
+
                m.Handle("/list-balances", jsonHandler(a.listBalances))
+               m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
        } else {
                log.Warn("Please enable wallet")
        }
 
        m.Handle("/", alwaysError(errors.New("not Found")))
+       m.Handle("/error", jsonHandler(a.walletError))
 
-       m.Handle("/build-transaction", jsonHandler(a.build))
-       m.Handle("/sign-transaction", jsonHandler(a.pseudohsmSignTemplates))
-       m.Handle("/submit-transaction", jsonHandler(a.submit))
-       m.Handle("/sign-submit-transaction", jsonHandler(a.signSubmit))
-
-       m.Handle("/create-transaction-feed", jsonHandler(a.createTxFeed))
-       m.Handle("/get-transaction-feed", jsonHandler(a.getTxFeed))
-       m.Handle("/update-transaction-feed", jsonHandler(a.updateTxFeed))
-       m.Handle("/delete-transaction-feed", jsonHandler(a.deleteTxFeed))
-       m.Handle("/list-transaction-feeds", jsonHandler(a.listTxFeeds))
-       m.Handle("/list-unspent-outputs", jsonHandler(a.listUnspentOutputs))
        m.Handle("/info", jsonHandler(a.bcr.Info))
+       m.Handle("/net-info", jsonHandler(a.getNetInfo))
 
        m.Handle("/create-access-token", jsonHandler(a.createAccessToken))
        m.Handle("/list-access-tokens", jsonHandler(a.listAccessTokens))
        m.Handle("/delete-access-token", jsonHandler(a.deleteAccessToken))
        m.Handle("/check-access-token", jsonHandler(a.checkAccessToken))
 
-       m.Handle("/block-hash", jsonHandler(a.getBestBlockHash))
-
-       m.Handle("/export-private-key", jsonHandler(a.walletExportKey))
-       m.Handle("/import-private-key", jsonHandler(a.walletImportKey))
-       m.Handle("/import-key-progress", jsonHandler(a.keyImportProgress))
+       m.Handle("/create-transaction-feed", jsonHandler(a.createTxFeed))
+       m.Handle("/get-transaction-feed", jsonHandler(a.getTxFeed))
+       m.Handle("/update-transaction-feed", jsonHandler(a.updateTxFeed))
+       m.Handle("/delete-transaction-feed", jsonHandler(a.deleteTxFeed))
+       m.Handle("/list-transaction-feeds", jsonHandler(a.listTxFeeds))
 
+       m.Handle("/block-hash", jsonHandler(a.getBestBlockHash))
        m.Handle("/get-block-header-by-hash", jsonHandler(a.getBlockHeaderByHash))
        m.Handle("/get-block-header-by-height", jsonHandler(a.getBlockHeaderByHeight))
        m.Handle("/get-block", jsonHandler(a.getBlock))
@@ -206,20 +218,13 @@ func (a *API) buildHandler() {
        m.Handle("/get-block-transactions-count-by-hash", jsonHandler(a.getBlockTransactionsCountByHash))
        m.Handle("/get-block-transactions-count-by-height", jsonHandler(a.getBlockTransactionsCountByHeight))
 
-       m.Handle("/net-info", jsonHandler(a.getNetInfo))
-
        m.Handle("/is-mining", jsonHandler(a.isMining))
        m.Handle("/gas-rate", jsonHandler(a.gasRate))
        m.Handle("/getwork", jsonHandler(a.getWork))
        m.Handle("/submitwork", jsonHandler(a.submitWork))
 
-       latencyHandler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
-               if l := latency(m, req); l != nil {
-                       defer l.RecordSince(time.Now())
-               }
-               m.ServeHTTP(w, req)
-       })
-       handler := maxBytesHandler(latencyHandler) // TODO(tessr): consider moving this to non-core specific mux
+       handler := latencyHandler(m, walletEnable)
+       handler = maxBytesHandler(handler) // TODO(tessr): consider moving this to non-core specific mux
        handler = webAssetsHandler(handler)
 
        a.handler = handler
@@ -262,7 +267,7 @@ func webAssetsHandler(next http.Handler) http.Handler {
        return mux
 }
 
-//AuthHandler access token auth Handler
+// AuthHandler access token auth Handler
 func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore) http.Handler {
        authenticator := authn.NewAPI(accessTokens)
 
@@ -279,6 +284,7 @@ func AuthHandler(handler http.Handler, accessTokens *accesstoken.CredentialStore
        })
 }
 
+// RedirectHandler redirect to dashboard handler
 func RedirectHandler(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
                if req.URL.Path == "/" {
@@ -288,3 +294,27 @@ func RedirectHandler(next http.Handler) http.Handler {
                next.ServeHTTP(w, req)
        })
 }
+
+// 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 {
+       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, redirect url path to error
+               walletRedirectHandler(m, walletEnable, w, req)
+
+               m.ServeHTTP(w, req)
+       })
+}
+
+// walletRedirectHandler redirect to error when the wallet is closed
+func walletRedirectHandler(m *http.ServeMux, walletEnable bool, w http.ResponseWriter, req *http.Request) {
+       if _, pattern := m.Handler(req); pattern != req.URL.Path && !walletEnable {
+               url := req.URL
+               url.Path = "/error"
+               http.Redirect(w, req, url.String(), http.StatusOK)
+       }
+}
index 1519170..ec950c0 100644 (file)
@@ -68,3 +68,8 @@ func (a *API) keyImportProgress(ctx context.Context) Response {
        }
        return NewSuccessResponse(data)
 }
+
+// POST /wallet error
+func (a *API) walletError() Response {
+       return NewErrorResponse(errors.New("wallet not found, please check that the wallet is open"))
+}
index 485ddc8..ab346c4 100755 (executable)
@@ -9,7 +9,6 @@ import (
        cmn "github.com/tendermint/tmlibs/common"
 
        "github.com/bytom/blockchain/txfeed"
-       "github.com/bytom/wallet"
        "github.com/bytom/mining/cpuminer"
        "github.com/bytom/mining/miningpool"
        "github.com/bytom/p2p"
@@ -18,6 +17,7 @@ import (
        "github.com/bytom/protocol/bc"
        protocolTypes "github.com/bytom/protocol/bc/types"
        "github.com/bytom/types"
+       "github.com/bytom/wallet"
 )
 
 const (
@@ -30,7 +30,7 @@ const (
        crosscoreRPCPrefix          = "/rpc/"
 )
 
-//BlockchainReactor handles long-term catchup syncing.
+// BlockchainReactor handles long-term catchup syncing.
 type BlockchainReactor struct {
        p2p.BaseReactor
 
@@ -47,6 +47,7 @@ type BlockchainReactor struct {
        miningEnable  bool
 }
 
+// Info return the server information
 func (bcr *BlockchainReactor) Info(ctx context.Context) (map[string]interface{}, error) {
        return map[string]interface{}{
                "is_configured": false,
index dc8d131..0c8dbdc 100755 (executable)
@@ -13,15 +13,15 @@ import (
        cmn "github.com/tendermint/tmlibs/common"
        dbm "github.com/tendermint/tmlibs/db"
 
-       "github.com/bytom/api"
-       "github.com/bytom/crypto/ed25519/chainkd"
-       bc "github.com/bytom/blockchain"
        "github.com/bytom/accesstoken"
        "github.com/bytom/account"
+       "github.com/bytom/api"
        "github.com/bytom/asset"
+       bc "github.com/bytom/blockchain"
        "github.com/bytom/blockchain/pseudohsm"
        "github.com/bytom/blockchain/txfeed"
        cfg "github.com/bytom/config"
+       "github.com/bytom/crypto/ed25519/chainkd"
        "github.com/bytom/database/leveldb"
        "github.com/bytom/env"
        "github.com/bytom/p2p"
@@ -118,7 +118,7 @@ func NewNode(config *cfg.Config) *Node {
                walletDB := dbm.NewDB("wallet", config.DBBackend, config.DBDir())
                accounts = account.NewManager(walletDB, chain)
                assets = asset.NewRegistry(walletDB, chain)
-               wallet, err = w.NewWallet(walletDB, accounts, assets, hsm, accessTokens, chain)
+               wallet, err = w.NewWallet(walletDB, accounts, assets, hsm, chain)
                if err != nil {
                        log.WithField("error", err).Error("init NewWallet")
                }
@@ -211,7 +211,7 @@ func lanchWebBroser() {
 }
 
 func (n *Node) initAndstartApiServer() {
-       n.api = api.NewAPI(n.bcReactor, n.wallet, n.chain, n.config)
+       n.api = api.NewAPI(n.bcReactor, n.wallet, n.chain, n.config, n.accessTokens)
 
        listenAddr := env.String("LISTEN", n.config.ApiAddress)
        n.api.StartServer(*listenAddr)
index 8150020..0f08a08 100755 (executable)
@@ -8,7 +8,6 @@ import (
        "github.com/tendermint/go-wire/data/base58"
        "github.com/tendermint/tmlibs/db"
 
-       "github.com/bytom/accesstoken"
        "github.com/bytom/account"
        "github.com/bytom/asset"
        "github.com/bytom/blockchain/pseudohsm"
@@ -51,7 +50,6 @@ type Wallet struct {
        AccountMgr     *account.Manager
        AssetReg       *asset.Registry
        Hsm            *pseudohsm.HSM
-       Tokens             *accesstoken.CredentialStore
        chain          *protocol.Chain
        rescanProgress chan struct{}
        ImportPrivKey  bool
@@ -59,15 +57,13 @@ type Wallet struct {
 }
 
 //NewWallet return a new wallet instance
-func NewWallet(walletDB db.DB, account *account.Manager, asset *asset.Registry, hsm *pseudohsm.HSM,
-       accessTokens *accesstoken.CredentialStore, chain *protocol.Chain) (*Wallet, error) {
+func NewWallet(walletDB db.DB, account *account.Manager, asset *asset.Registry, hsm *pseudohsm.HSM, chain *protocol.Chain) (*Wallet, error) {
        w := &Wallet{
                DB:             walletDB,
                AccountMgr:     account,
                AssetReg:       asset,
                chain:          chain,
                Hsm:            hsm,
-               Tokens:         accessTokens,
                rescanProgress: make(chan struct{}, 1),
                keysInfo:       make([]KeyInfo, 0),
        }