github.com/aergoio/aergo@v1.3.1/consensus/impl/impl.go (about)

     1  /**
     2   *  @file
     3   *  @copyright defined in aergo/LICENSE.txt
     4   */
     5  
     6  package impl
     7  
     8  import (
     9  	"github.com/aergoio/aergo/chain"
    10  	"github.com/aergoio/aergo/config"
    11  	"github.com/aergoio/aergo/consensus"
    12  	"github.com/aergoio/aergo/consensus/impl/dpos"
    13  	"github.com/aergoio/aergo/consensus/impl/raftv2"
    14  	"github.com/aergoio/aergo/consensus/impl/sbp"
    15  	"github.com/aergoio/aergo/p2p"
    16  	"github.com/aergoio/aergo/p2p/p2pcommon"
    17  	"github.com/aergoio/aergo/pkg/component"
    18  	"github.com/aergoio/aergo/rpc"
    19  	"github.com/aergoio/aergo/types"
    20  	"strings"
    21  )
    22  
    23  // New returns consensus.Consensus based on the configuration parameters.
    24  func New(cfg *config.Config, hub *component.ComponentHub, cs *chain.ChainService, p2psvc *p2p.P2P, rpcSvc *rpc.RPC) (consensus.Consensus, error) {
    25  	var (
    26  		c   consensus.Consensus
    27  		err error
    28  
    29  		blockInterval int64
    30  	)
    31  
    32  	if chain.IsPublic() {
    33  		blockInterval = 1
    34  	} else {
    35  		blockInterval = cfg.Consensus.BlockInterval
    36  	}
    37  
    38  	consensus.InitBlockInterval(blockInterval)
    39  
    40  	if c, err = newConsensus(cfg, hub, cs, p2psvc.GetPeerAccessor()); err == nil {
    41  		// Link mutual references.
    42  		cs.SetChainConsensus(c)
    43  		rpcSvc.SetConsensusAccessor(c)
    44  		p2psvc.SetConsensusAccessor(c)
    45  	}
    46  
    47  	return c, err
    48  }
    49  
    50  func newConsensus(cfg *config.Config, hub *component.ComponentHub,
    51  	cs *chain.ChainService, pa p2pcommon.PeerAccessor) (consensus.Consensus, error) {
    52  	cdb := cs.CDB()
    53  	sdb := cs.SDB()
    54  
    55  	impl := map[string]consensus.Constructor{
    56  		dpos.GetName():   dpos.GetConstructor(cfg, hub, cdb, sdb),              // DPoS
    57  		sbp.GetName():    sbp.GetConstructor(cfg, hub, cdb, sdb),               // Simple BP
    58  		raftv2.GetName(): raftv2.GetConstructor(cfg, hub, cs.WalDB(), sdb, pa), // Raft BP
    59  	}
    60  
    61  	consensus.SetCurConsensus(cdb.GetGenesisInfo().ConsensusType())
    62  	return impl[cdb.GetGenesisInfo().ConsensusType()]()
    63  }
    64  
    65  type GenesisValidator func(genesis *types.Genesis) error
    66  
    67  func ValidateGenesis(genesis *types.Genesis) error {
    68  	name := strings.ToLower(genesis.ConsensusType())
    69  
    70  	validators := map[string]GenesisValidator{
    71  		dpos.GetName():   dpos.ValidateGenesis,   // DPoS
    72  		sbp.GetName():    sbp.ValidateGenesis,    // Simple BP
    73  		raftv2.GetName(): raftv2.ValidateGenesis, // Raft BP
    74  	}
    75  
    76  	return validators[name](genesis)
    77  }