OSDN Git Service

make some fields of BlockchainReactor public to facilitate separate API (#477)
authorYongfeng LI <wliyongfeng@gmail.com>
Sat, 24 Mar 2018 07:21:48 +0000 (15:21 +0800)
committerPaladz <yzhu101@uottawa.ca>
Sat, 24 Mar 2018 07:21:48 +0000 (15:21 +0800)
* move maxBytesHandler to api.go

* move Response to api.go

* call chain from api directly

* not call BlockchainReactor inner methods from API

* make BlockchainReactor txFeedTracker public

api/types.go [new file with mode: 0644]
blockchain/api.go
blockchain/blockchain_reactor.go
blockchain/miner.go
blockchain/reactor.go
blockchain/txfeeds.go
cmd/miner/main.go
node/node.go

diff --git a/api/types.go b/api/types.go
new file mode 100644 (file)
index 0000000..b7a5218
--- /dev/null
@@ -0,0 +1,27 @@
+package api
+
+import (
+       "github.com/bytom/protocol/bc"
+       "github.com/bytom/protocol/bc/types"
+)
+
+// BlockHeaderByHeight is resp struct for API
+type BlockHeaderByHeight struct {
+       BlockHeader *types.BlockHeader `json:"block_header"`
+       Reward      uint64             `json:"reward"`
+}
+
+// GetWorkResp is resp struct for API
+type GetWorkResp struct {
+       BlockHeader *types.BlockHeader `json:"block_header"`
+       Seed        *bc.Hash           `json:"seed"`
+}
+
+type NetInfo struct {
+       Listening    bool   `json:"listening"`
+       Syncing      bool   `json:"syncing"`
+       Mining       bool   `json:"mining"`
+       PeerCount    int    `json:"peer_count"`
+       CurrentBlock uint64 `json:"current_block"`
+       HighestBlock uint64 `json:"highest_block"`
+}
index 66dc219..4da6e4e 100644 (file)
@@ -28,6 +28,20 @@ var (
        httpWriteTimeout    = time.Hour
 )
 
+const (
+       // SUCCESS indicates the rpc calling is successful.
+       SUCCESS = "success"
+       // FAIL indicated the rpc calling is failed.
+       FAIL = "fail"
+)
+
+// Response describes the response standard.
+type Response struct {
+       Status string      `json:"status,omitempty"`
+       Msg    string      `json:"msg,omitempty"`
+       Data   interface{} `json:"data,omitempty"`
+}
+
 //NewSuccessResponse success response
 func NewSuccessResponse(data interface{}) Response {
        return Response{Status: SUCCESS, Data: data}
@@ -170,7 +184,7 @@ func (a *API) buildHandler() {
        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("/info", jsonHandler(a.bcr.Info))
 
        m.Handle("/create-access-token", jsonHandler(a.createAccessToken))
        m.Handle("/list-access-tokens", jsonHandler(a.listAccessTokens))
@@ -203,12 +217,24 @@ func (a *API) buildHandler() {
                }
                m.ServeHTTP(w, req)
        })
-       handler := maxBytes(latencyHandler) // TODO(tessr): consider moving this to non-core specific mux
+       handler := maxBytesHandler(latencyHandler) // TODO(tessr): consider moving this to non-core specific mux
        handler = webAssetsHandler(handler)
 
        a.handler = handler
 }
 
+func maxBytesHandler(h http.Handler) http.Handler {
+       const maxReqSize = 1e7 // 10MB
+       return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+               // A block can easily be bigger than maxReqSize, but everything
+               // else should be pretty small.
+               if req.URL.Path != crosscoreRPCPrefix+"signer/sign-block" {
+                       req.Body = http.MaxBytesReader(w, req.Body, maxReqSize)
+               }
+               h.ServeHTTP(w, req)
+       })
+}
+
 // json Handler
 func jsonHandler(f interface{}) http.Handler {
        h, err := httpjson.Handler(f, errorFormatter.Write)
index e2a56c4..4108efe 100644 (file)
@@ -3,6 +3,7 @@ package blockchain
 import (
        log "github.com/sirupsen/logrus"
 
+       "github.com/bytom/api"
        "github.com/bytom/blockchain/query"
        "github.com/bytom/wallet"
        "github.com/bytom/consensus"
@@ -12,25 +13,24 @@ import (
        "github.com/bytom/protocol/bc/types"
 )
 
+func (bcr *BlockchainReactor) GetNodeInfo() *api.NetInfo {
+       return &api.NetInfo{
+               Listening:    bcr.sw.IsListening(),
+               Syncing:      bcr.blockKeeper.IsCaughtUp(),
+               Mining:       bcr.mining.IsMining(),
+               PeerCount:    len(bcr.sw.Peers().List()),
+               CurrentBlock: bcr.blockKeeper.chainHeight,
+               HighestBlock: bcr.blockKeeper.maxPeerHeight,
+       }
+}
+
+func (bcr *BlockchainReactor) IsMining() bool {
+       return bcr.mining.IsMining()
+}
+
 // return network infomation
 func (a *API) getNetInfo() Response {
-       type netInfo struct {
-               Listening    bool   `json:"listening"`
-               Syncing      bool   `json:"syncing"`
-               Mining       bool   `json:"mining"`
-               PeerCount    int    `json:"peer_count"`
-               CurrentBlock uint64 `json:"current_block"`
-               HighestBlock uint64 `json:"highest_block"`
-       }
-       net := &netInfo{}
-       net.Listening = a.bcr.sw.IsListening()
-       net.Syncing = a.bcr.blockKeeper.IsCaughtUp()
-       net.Mining = a.bcr.mining.IsMining()
-       net.PeerCount = len(a.bcr.sw.Peers().List())
-       net.CurrentBlock = a.bcr.blockKeeper.chainHeight
-       net.HighestBlock = a.bcr.blockKeeper.maxPeerHeight
-
-       return NewSuccessResponse(net)
+       return NewSuccessResponse(a.bcr.GetNodeInfo())
 }
 
 // return best block hash
@@ -190,7 +190,7 @@ func (a *API) getBlockCount() Response {
 
 // return is in mining or not
 func (a *API) isMining() Response {
-       IsMining := map[string]bool{"isMining": a.bcr.mining.IsMining()}
+       IsMining := map[string]bool{"isMining": a.bcr.IsMining()}
        return NewSuccessResponse(IsMining)
 }
 
index f379968..a8d2c5d 100644 (file)
@@ -3,54 +3,52 @@ package blockchain
 import (
        "context"
 
-       "github.com/bytom/protocol/bc"
+       "github.com/bytom/api"
        "github.com/bytom/protocol/bc/types"
 )
 
-// BlockHeaderByHeight is resp struct for API
-type BlockHeaderByHeight struct {
-       BlockHeader *types.BlockHeader `json:"block_header"`
-       Reward      uint64             `json:"reward"`
-}
-
-// GetWorkResp is resp struct for API
-type GetWorkResp struct {
-       BlockHeader *types.BlockHeader `json:"block_header"`
-       Seed        *bc.Hash           `json:"seed"`
-}
-
-func (a *API) getWork() Response {
-       bh, err := a.bcr.miningPool.GetWork()
+func (bcr *BlockchainReactor) GetWork() (*api.GetWorkResp, error) {
+       bh, err := bcr.miningPool.GetWork()
        if err != nil {
-               return NewErrorResponse(err)
+               return nil, err
        }
 
-       seed, err := a.bcr.chain.GetSeed(bh.Height, &bh.PreviousBlockHash)
+       seed, err := bcr.chain.GetSeed(bh.Height, &bh.PreviousBlockHash)
        if err != nil {
-               return NewErrorResponse(err)
+               return nil, err
        }
 
-       resp := &GetWorkResp{
+       return &api.GetWorkResp{
                BlockHeader: bh,
                Seed:        seed,
+       }, nil
+}
+
+func (bcr *BlockchainReactor) SubmitWork(bh *types.BlockHeader) bool {
+       return bcr.miningPool.SubmitWork(bh)
+}
+
+func (a *API) getWork() Response {
+       work, err := a.bcr.GetWork()
+       if err != nil {
+               return NewErrorResponse(err)
        }
-       return NewSuccessResponse(resp)
+       return NewSuccessResponse(work)
 }
 
 func (a *API) submitWork(bh *types.BlockHeader) Response {
-       success := a.bcr.miningPool.SubmitWork(bh)
-       return NewSuccessResponse(success)
+       return NewSuccessResponse(a.bcr.SubmitWork(bh))
 }
 
 func (a *API) getBlockHeaderByHeight(ctx context.Context, req struct {
        Height uint64 `json:"block_height"`
 }) Response {
-       block, err := a.bcr.chain.GetBlockByHeight(req.Height)
+       block, err := a.chain.GetBlockByHeight(req.Height)
        if err != nil {
                return NewErrorResponse(err)
        }
 
-       resp := &BlockHeaderByHeight{
+       resp := &api.BlockHeaderByHeight{
                BlockHeader: &block.BlockHeader,
                Reward:      block.Transactions[0].Outputs[0].Amount,
        }
index 4083f81..485ddc8 100755 (executable)
@@ -2,7 +2,6 @@ package blockchain
 
 import (
        "context"
-       "net/http"
        "reflect"
        "time"
 
@@ -31,27 +30,13 @@ const (
        crosscoreRPCPrefix          = "/rpc/"
 )
 
-const (
-       // SUCCESS indicates the rpc calling is successful.
-       SUCCESS = "success"
-       // FAIL indicated the rpc calling is failed.
-       FAIL = "fail"
-)
-
-// Response describes the response standard.
-type Response struct {
-       Status string      `json:"status,omitempty"`
-       Msg    string      `json:"msg,omitempty"`
-       Data   interface{} `json:"data,omitempty"`
-}
-
 //BlockchainReactor handles long-term catchup syncing.
 type BlockchainReactor struct {
        p2p.BaseReactor
 
        chain         *protocol.Chain
        wallet        *wallet.Wallet
-       txFeedTracker *txfeed.Tracker
+       TxFeedTracker *txfeed.Tracker // TODO: move it out from BlockchainReactor
        blockKeeper   *blockKeeper
        txPool        *protocol.TxPool
        mining        *cpuminer.CPUMiner
@@ -62,7 +47,7 @@ type BlockchainReactor struct {
        miningEnable  bool
 }
 
-func (bcr *BlockchainReactor) info(ctx context.Context) (map[string]interface{}, error) {
+func (bcr *BlockchainReactor) Info(ctx context.Context) (map[string]interface{}, error) {
        return map[string]interface{}{
                "is_configured": false,
                "version":       "0.001",
@@ -72,18 +57,6 @@ func (bcr *BlockchainReactor) info(ctx context.Context) (map[string]interface{},
        }, nil
 }
 
-func maxBytes(h http.Handler) http.Handler {
-       const maxReqSize = 1e7 // 10MB
-       return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
-               // A block can easily be bigger than maxReqSize, but everything
-               // else should be pretty small.
-               if req.URL.Path != crosscoreRPCPrefix+"signer/sign-block" {
-                       req.Body = http.MaxBytesReader(w, req.Body, maxReqSize)
-               }
-               h.ServeHTTP(w, req)
-       })
-}
-
 // NewBlockchainReactor returns the reactor of whole blockchain.
 func NewBlockchainReactor(chain *protocol.Chain, txPool *protocol.TxPool, sw *p2p.Switch, wallet *wallet.Wallet, txfeeds *txfeed.Tracker, miningEnable bool) *BlockchainReactor {
        newBlockCh := make(chan *bc.Hash, maxNewBlockChSize)
@@ -93,7 +66,7 @@ func NewBlockchainReactor(chain *protocol.Chain, txPool *protocol.TxPool, sw *p2
                blockKeeper:   newBlockKeeper(chain, sw),
                txPool:        txPool,
                sw:            sw,
-               txFeedTracker: txfeeds,
+               TxFeedTracker: txfeeds,
                miningEnable:  miningEnable,
                newBlockCh:    newBlockCh,
        }
@@ -224,7 +197,7 @@ func (bcr *BlockchainReactor) syncRoutine() {
                        }
                        log.WithFields(log.Fields{"Hash": blockHash, "height": block.Height}).Info("Boardcast my new block")
                case newTx := <-newTxCh:
-                       bcr.txFeedTracker.TxFilter(newTx)
+                       bcr.TxFeedTracker.TxFilter(newTx)
                        go bcr.BroadcastTransaction(newTx)
                case _ = <-statusUpdateTicker.C:
                        go bcr.BroadcastStatusResponse()
index 5486742..3d8207b 100644 (file)
@@ -15,7 +15,7 @@ func (a *API) createTxFeed(ctx context.Context, in struct {
        Alias  string `json:"alias"`
        Filter string `json:"filter"`
 }) Response {
-       if err := a.bcr.txFeedTracker.Create(ctx, in.Alias, in.Filter); err != nil {
+       if err := a.bcr.TxFeedTracker.Create(ctx, in.Alias, in.Filter); err != nil {
                log.WithField("error", err).Error("Add TxFeed Failed")
                return NewErrorResponse(err)
        }
@@ -28,7 +28,7 @@ func (bcr *BlockchainReactor) getTxFeedByAlias(ctx context.Context, filter strin
                return nil, err
        }
 
-       value := bcr.txFeedTracker.DB.Get(jf)
+       value := bcr.TxFeedTracker.DB.Get(jf)
        if value == nil {
                return nil, errors.New("No transaction feed")
        }
@@ -57,7 +57,7 @@ func (a *API) getTxFeed(ctx context.Context, in struct {
 func (a *API) deleteTxFeed(ctx context.Context, in struct {
        Alias string `json:"alias,omitempty"`
 }) Response {
-       if err := a.bcr.txFeedTracker.Delete(ctx, in.Alias); err != nil {
+       if err := a.bcr.TxFeedTracker.Delete(ctx, in.Alias); err != nil {
                return NewErrorResponse(err)
        }
        return NewSuccessResponse(nil)
@@ -68,10 +68,10 @@ func (a *API) updateTxFeed(ctx context.Context, in struct {
        Alias  string `json:"alias"`
        Filter string `json:"filter"`
 }) Response {
-       if err := a.bcr.txFeedTracker.Delete(ctx, in.Alias); err != nil {
+       if err := a.bcr.TxFeedTracker.Delete(ctx, in.Alias); err != nil {
                return NewErrorResponse(err)
        }
-       if err := a.bcr.txFeedTracker.Create(ctx, in.Alias, in.Filter); err != nil {
+       if err := a.bcr.TxFeedTracker.Create(ctx, in.Alias, in.Filter); err != nil {
                log.WithField("error", err).Error("Update TxFeed Failed")
                return NewErrorResponse(err)
        }
@@ -82,7 +82,7 @@ func (a *API) getTxFeeds() ([]txfeed.TxFeed, error) {
        txFeed := txfeed.TxFeed{}
        txFeeds := make([]txfeed.TxFeed, 0)
 
-       iter := a.bcr.txFeedTracker.DB.Iterator()
+       iter := a.bcr.TxFeedTracker.DB.Iterator()
        defer iter.Release()
 
        for iter.Next() {
index ecccf3e..2f65a10 100644 (file)
@@ -5,7 +5,7 @@ import (
        "fmt"
        "os"
 
-       "github.com/bytom/blockchain"
+       "github.com/bytom/api"
        "github.com/bytom/consensus/difficulty"
        "github.com/bytom/protocol/bc"
        "github.com/bytom/protocol/bc/types"
@@ -61,7 +61,7 @@ func main() {
                fmt.Println(err)
                os.Exit(1)
        }
-       resp := &blockchain.GetWorkResp{}
+       resp := &api.GetWorkResp{}
        if err = json.Unmarshal(rawData, resp); err != nil {
                fmt.Println(err)
                os.Exit(1)
index 6236fc8..502034e 100755 (executable)
@@ -49,6 +49,7 @@ type Node struct {
 
        evsw         types.EventSwitch // pub/sub for services
        bcReactor    *bc.BlockchainReactor
+       wallet       *w.Wallet
        accessTokens *accesstoken.CredentialStore
        api          *bc.API
 }
@@ -160,6 +161,7 @@ func NewNode(config *cfg.Config) *Node {
                evsw:         eventSwitch,
                bcReactor:    bcReactor,
                accessTokens: accessTokens,
+               wallet:       wallet,
        }
        node.BaseService = *cmn.NewBaseService(nil, "Node", node)