github.com/intfoundation/intchain@v0.0.0-20220727031208-4316ad31ca73/cmd/utils/intchain_p2p_server.go (about)

     1  package utils
     2  
     3  import (
     4  	"github.com/intfoundation/intchain/common"
     5  	"github.com/intfoundation/intchain/log"
     6  	"github.com/intfoundation/intchain/node"
     7  	"github.com/intfoundation/intchain/p2p"
     8  	"gopkg.in/urfave/cli.v1"
     9  )
    10  
    11  type IntChainP2PServer struct {
    12  	serverConfig p2p.Config
    13  	server       *p2p.Server
    14  }
    15  
    16  func NewP2PServer(ctx *cli.Context) *IntChainP2PServer {
    17  
    18  	// Load Default P2P config
    19  	config := &node.Config{
    20  		GeneralDataDir: MakeDataDir(ctx),
    21  		DataDir:        MakeDataDir(ctx), // Just for pass the check, P2P always use GeneralDataDir
    22  		P2P:            node.DefaultConfig.P2P,
    23  	}
    24  
    25  	// Setup the config from context
    26  	SetP2PConfig(ctx, &config.P2P)
    27  
    28  	// Initialize the intp2p server. This creates the node key and
    29  	// discovery databases.
    30  	serverConfig := config.P2P
    31  	serverConfig.PrivateKey = config.NodeKey()
    32  	serverConfig.Name = config.NodeName()
    33  	serverConfig.EnableMsgEvents = true
    34  
    35  	if serverConfig.StaticNodes == nil {
    36  		serverConfig.StaticNodes = config.StaticNodes()
    37  	}
    38  	if serverConfig.TrustedNodes == nil {
    39  		serverConfig.TrustedNodes = config.TrustedNodes()
    40  	}
    41  	if serverConfig.NodeDatabase == "" {
    42  		serverConfig.NodeDatabase = config.NodeDB()
    43  	}
    44  	serverConfig.LocalValidators = make([]p2p.P2PValidator, 0)
    45  	serverConfig.Validators = make(map[p2p.P2PValidator]*p2p.P2PValidatorNodeInfo)
    46  
    47  	running := &p2p.Server{Config: serverConfig}
    48  	log.Info("Create peer-to-peer node", "instance", serverConfig.Name)
    49  
    50  	return &IntChainP2PServer{
    51  		serverConfig: serverConfig,
    52  		server:       running,
    53  	}
    54  }
    55  
    56  func (srv *IntChainP2PServer) Server() *p2p.Server {
    57  	return srv.server
    58  }
    59  
    60  func (srv *IntChainP2PServer) Stop() {
    61  	srv.server.Stop()
    62  }
    63  
    64  func (srv *IntChainP2PServer) BroadcastNewChildChainMsg(childId string) {
    65  	srv.server.BroadcastMsg(p2p.BroadcastNewChildChainMsg, childId)
    66  }
    67  
    68  func (srv *IntChainP2PServer) AddLocalValidator(chainId string, address common.Address) {
    69  	srv.server.AddLocalValidator(chainId, address)
    70  }
    71  
    72  func (srv *IntChainP2PServer) RemoveLocalValidator(chainId string, address common.Address) {
    73  	srv.server.RemoveLocalValidator(chainId, address)
    74  }