OSDN Git Service

opt code
authorshenao78 <shenao.78@163.com>
Wed, 30 Oct 2019 02:17:09 +0000 (10:17 +0800)
committershenao78 <shenao.78@163.com>
Wed, 30 Oct 2019 02:17:09 +0000 (10:17 +0800)
consensus/general.go
node/node.go
proposal/blockproposer/blockproposer.go
proposal/proposal.go
proposal/sort.go [moved from proposal/blockproposer/sort.go with 92% similarity]
protocol/block.go
protocol/protocol.go

index 279b4ad..b34f19d 100644 (file)
@@ -103,7 +103,6 @@ type Params struct {
        ProducerSubsidys []ProducerSubsidy
 
        SoftForkPoint map[uint64]uint64
-       MovStartPoint Checkpoint
 }
 
 // ActiveNetParams is the active NetParams
index f9ff064..b84dd91 100644 (file)
@@ -84,14 +84,7 @@ func NewNode(config *cfg.Config) *Node {
        }
 
        initCommonConfig(config)
-       movCore := mov.NewMovCore(config.DBBackend, config.DBDir())
-       startPoint := consensus.ActiveNetParams.MovStartPoint
-       if startPoint.Height == 0 {
-               startPoint.Hash = cfg.GenesisBlock().Hash()
-       }
-       if err := movCore.InitChainStatus(startPoint.Height, &startPoint.Hash); err != nil {
-               log.Fatalf("Failed to create Mov protocol:%v", err.Error())
-       }
+
        // Get store
        if config.DBBackend != "memdb" && config.DBBackend != "leveldb" {
                cmn.Exit(cmn.Fmt("Param db_backend [%v] is invalid, use leveldb or memdb", config.DBBackend))
@@ -103,6 +96,7 @@ func NewNode(config *cfg.Config) *Node {
        accessTokens := accesstoken.NewStore(tokenDB)
 
        dispatcher := event.NewDispatcher()
+       movCore := mov.NewMovCore(config.DBBackend, config.DBDir())
        txPool := protocol.NewTxPool(store, []protocol.DustFilterer{movCore}, dispatcher)
        chain, err := protocol.NewChain(store, txPool, []protocol.Protocoler{movCore}, dispatcher)
        if err != nil {
@@ -113,6 +107,12 @@ func NewNode(config *cfg.Config) *Node {
                panic(err)
        }
 
+       if chain.BestBlockHeight() == 0 {
+               if err := movCore.InitChainStatus(0, chain.BestBlockHash()); err != nil {
+                       log.Fatalf("Failed to create Mov protocol:%v", err.Error())
+               }
+       }
+
        var accounts *account.Manager
        var assets *asset.Registry
        var wallet *w.Wallet
@@ -170,7 +170,7 @@ func NewNode(config *cfg.Config) *Node {
                notificationMgr: notificationMgr,
        }
 
-       node.cpuMiner = blockproposer.NewBlockProposer(chain, accounts, txPool, []blockproposer.Preprocessor{movCore}, dispatcher)
+       node.cpuMiner = blockproposer.NewBlockProposer(chain, accounts, txPool, dispatcher)
        node.BaseService = *cmn.NewBaseService(nil, "Node", node)
        return node
 }
index 2b3edc2..71063cc 100644 (file)
@@ -2,7 +2,6 @@ package blockproposer
 
 import (
        "encoding/hex"
-       "sort"
        "sync"
        "time"
 
@@ -14,25 +13,18 @@ import (
        "github.com/vapor/event"
        "github.com/vapor/proposal"
        "github.com/vapor/protocol"
-       "github.com/vapor/protocol/bc/types"
 )
 
 const (
        logModule     = "blockproposer"
-       maxBlockTxNum = 3000
 )
 
-type Preprocessor interface {
-       BeforeProposalBlock(capacity int, nodeProgram []byte) ([]*types.Tx, error)
-}
-
 // BlockProposer propose several block in specified time range
 type BlockProposer struct {
        sync.Mutex
        chain           *protocol.Chain
        accountManager  *account.Manager
        txPool          *protocol.TxPool
-       preprocessors   []Preprocessor
        started         bool
        quit            chan struct{}
        eventDispatcher *event.Dispatcher
@@ -82,28 +74,7 @@ func (b *BlockProposer) generateBlocks() {
                        continue
                }
 
-               var packageTxs []*types.Tx
-               txs := b.txPool.GetTransactions()
-               sort.Sort(byTime(txs))
-               for _, txDesc := range txs {
-                       packageTxs = append(packageTxs, txDesc.Tx)
-               }
-               capacity := maxBlockTxNum - len(txs)
-               for i, p := range b.preprocessors {
-                       if capacity <= 0 {
-                               break
-                       }
-
-                       txs, err := p.BeforeProposalBlock(capacity, []byte{0x51})
-                       if err != nil {
-                               log.WithFields(log.Fields{"module": logModule, "index": i, "error": err}).Error("failed on sub protocol txs package")
-                               continue
-                       }
-                       packageTxs = append(packageTxs, txs...)
-                       capacity = capacity - len(txs)
-               }
-
-               block, err := proposal.NewBlockTemplate(b.chain, b.txPool, b.accountManager, packageTxs, nextBlockTime)
+               block, err := proposal.NewBlockTemplate(b.chain, b.txPool, b.accountManager, nextBlockTime)
                if err != nil {
                        log.WithFields(log.Fields{"module": logModule, "error": err}).Error("failed on create NewBlockTemplate")
                        continue
@@ -176,12 +147,11 @@ func (b *BlockProposer) IsProposing() bool {
 // NewBlockProposer returns a new instance of a block proposer for the provided configuration.
 // Use Start to begin the proposal process.  See the documentation for BlockProposer
 // type for more details.
-func NewBlockProposer(c *protocol.Chain, accountManager *account.Manager, txPool *protocol.TxPool, preprocessors []Preprocessor, dispatcher *event.Dispatcher) *BlockProposer {
+func NewBlockProposer(c *protocol.Chain, accountManager *account.Manager, txPool *protocol.TxPool, dispatcher *event.Dispatcher) *BlockProposer {
        return &BlockProposer{
                chain:           c,
                accountManager:  accountManager,
                txPool:          txPool,
-               preprocessors:   preprocessors,
                eventDispatcher: dispatcher,
        }
 }
index 319d019..86ed311 100644 (file)
@@ -1,6 +1,7 @@
 package proposal
 
 import (
+       "sort"
        "strconv"
        "time"
 
@@ -18,7 +19,10 @@ import (
        "github.com/vapor/protocol/vm/vmutil"
 )
 
-const logModule = "mining"
+const (
+       logModule = "mining"
+       maxBlockTxNum = 3000
+)
 
 // createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy
 // based on the passed block height to the provided address.  When the address
@@ -73,7 +77,7 @@ func createCoinbaseTx(accountManager *account.Manager, blockHeight uint64, rewar
 }
 
 // NewBlockTemplate returns a new block template that is ready to be solved
-func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager, txs []*types.Tx, timestamp uint64) (b *types.Block, err error) {
+func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager, timestamp uint64) (b *types.Block, err error) {
        view := state.NewUtxoViewpoint()
        txStatus := bc.NewTransactionStatus()
        if err := txStatus.SetStatus(0, false); err != nil {
@@ -101,6 +105,11 @@ func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager
        b.Transactions = []*types.Tx{nil}
 
        entriesTxs := []*bc.Tx{}
+       txs, err := packageSubProtocolTxs(c, txPool, accountManager)
+       if err != nil {
+               return nil, err
+       }
+
        for _, tx := range txs {
                entriesTxs = append(entriesTxs, tx.Tx)
        }
@@ -174,6 +183,35 @@ func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager
        return b, err
 }
 
+func packageSubProtocolTxs(chain *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager) ([]*types.Tx, error) {
+       var packageTxs []*types.Tx
+       txs := txPool.GetTransactions()
+       sort.Sort(byTime(txs))
+       for _, txDesc := range txs {
+               packageTxs = append(packageTxs, txDesc.Tx)
+       }
+       capacity := maxBlockTxNum - len(txs)
+       cp, err := accountManager.GetCoinbaseControlProgram()
+       if err != nil {
+               return nil, err
+       }
+
+       for i, p := range chain.SubProtocols() {
+               if capacity <= 0 {
+                       break
+               }
+
+               txs, err := p.BeforeProposalBlock(capacity, cp)
+               if err != nil {
+                       log.WithFields(log.Fields{"module": logModule, "index": i, "error": err}).Error("failed on sub protocol txs package")
+                       continue
+               }
+               packageTxs = append(packageTxs, txs...)
+               capacity = capacity - len(txs)
+       }
+       return packageTxs, nil
+}
+
 func blkGenSkipTxForErr(txPool *protocol.TxPool, txHash *bc.Hash, err error) {
        log.WithFields(log.Fields{"module": logModule, "error": err}).Error("mining block generation: skip tx due to")
        txPool.RemoveTransaction(txHash)
similarity index 92%
rename from proposal/blockproposer/sort.go
rename to proposal/sort.go
index 02a3a5e..45e80e2 100644 (file)
@@ -1,4 +1,4 @@
-package blockproposer
+package proposal
 
 import "github.com/vapor/protocol"
 
index eb19ef3..a02f1a6 100644 (file)
@@ -111,6 +111,10 @@ func (c *Chain) connectBlock(block *types.Block) (err error) {
        }
 
        for _, p := range c.subProtocols {
+               if err := c.syncProtocolStatus(p); err != nil {
+                       return errors.Wrap(err, p.Name(), "sync sub protocol status")
+               }
+
                if err := p.ApplyBlock(block); err != nil {
                        return errors.Wrap(err, p.Name(), "sub protocol connect block")
                }
@@ -171,6 +175,10 @@ func (c *Chain) reorganizeChain(blockHeader *types.BlockHeader) error {
                }
 
                for _, p := range c.subProtocols {
+                       if err := c.syncProtocolStatus(p); err != nil {
+                               return errors.Wrap(err, p.Name(), "sync sub protocol status")
+                       }
+
                        if err := p.DetachBlock(b); err != nil {
                                return errors.Wrap(err, p.Name(), "sub protocol detach block")
                        }
index 2730358..8dfd659 100644 (file)
@@ -21,6 +21,7 @@ const (
 
 type Protocoler interface {
        Name() string
+       BeforeProposalBlock(capacity int, nodeProgram []byte) ([]*types.Tx, error)
        ChainStatus() (uint64, *bc.Hash, error)
        ValidateBlock(block *types.Block, verifyResults []*bc.TxVerifyResult) error
        ValidateTxs(txs []*types.Tx, verifyResults []*bc.TxVerifyResult) error
@@ -165,6 +166,10 @@ func (c *Chain) InMainChain(hash bc.Hash) bool {
        return *blockHash == hash
 }
 
+func (c *Chain) SubProtocols() []Protocoler {
+       return c.subProtocols
+}
+
 // trace back to the tail of the chain from the given block header
 func (c *Chain) traceLongestChainTail(blockHeader *types.BlockHeader) (*types.BlockHeader, error) {
        longestTail, workQueue := blockHeader, []*types.BlockHeader{blockHeader}