github.com/sixexorg/magnetic-ring@v0.0.0-20191119090307-31705a21e419/p2pserver/p2pserver_business.go (about)

     1  package p2pserver
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"sync"
     7  	"time"
     8  
     9  	"github.com/sixexorg/magnetic-ring/bactor"
    10  
    11  	comm "github.com/sixexorg/magnetic-ring/common"
    12  	"github.com/sixexorg/magnetic-ring/config"
    13  	orgtypes "github.com/sixexorg/magnetic-ring/core/orgchain/types"
    14  	"github.com/sixexorg/magnetic-ring/log"
    15  	"github.com/sixexorg/magnetic-ring/p2pserver/common"
    16  	msgpack "github.com/sixexorg/magnetic-ring/p2pserver/message"
    17  	"github.com/sixexorg/magnetic-ring/p2pserver/peer"
    18  
    19  	// table
    20  	"github.com/sixexorg/magnetic-ring/p2pserver/discover"
    21  	// org
    22  	"github.com/sixexorg/magnetic-ring/p2pserver/sync/org"
    23  )
    24  
    25  const (
    26  	CHECKCONN_NUM          = 60 // Check the connection at 60 seconds
    27  	ANODE_GETSTELLAR_TIMES = 10
    28  )
    29  
    30  // org info
    31  type OrgMan struct {
    32  	sync.RWMutex
    33  	OrgSync map[comm.Address]*org.OrgBlockSyncMgr
    34  }
    35  
    36  func NewAddOrg() *OrgMan {
    37  	ser := new(OrgMan)
    38  	ser.OrgSync = make(map[comm.Address]*org.OrgBlockSyncMgr)
    39  
    40  	return ser
    41  }
    42  
    43  func (this *OrgMan) Reset() {
    44  	this.OrgSync = make(map[comm.Address]*org.OrgBlockSyncMgr)
    45  }
    46  
    47  // add org; from acror
    48  func (this *P2PServer) AddOrg(orgID comm.Address) {
    49  	return
    50  	this.orgman.Lock()
    51  	defer this.orgman.Unlock()
    52  	log.Info("====>>>>P2PServer AddOrg", "orgID", orgID.ToString())
    53  
    54  	if _, ok := this.orgman.OrgSync[orgID]; ok {
    55  		return
    56  	}
    57  	if common.StellarNodeID != orgID {
    58  		if len(this.orgman.OrgSync) > common.ORG_CONNECT_NUM {
    59  			fmt.Println(" **** error org connection has reached the limit orgID:", orgID)
    60  			return
    61  		}
    62  	}
    63  	//fmt.Println("==========>>>>>>>>>>>>>>>P2PServer AddOr:", orgID.ToString())
    64  	if this.orgConPeer(orgID) == false {
    65  		// sleep 1s to slowdown
    66  		time.Sleep(time.Second)
    67  		go this.AddOrg(orgID)
    68  		log.Warn("P2PServer AddOrg orgConPeer false", "orgID", orgID.ToString())
    69  		return
    70  	}
    71  	log.Info("P2PServer AddOrg get orgids success", "orgID", orgID.ToString())
    72  
    73  	this.network.PeerAddOrg(orgID)
    74  	orgsync := org.NewOrgBlockSyncMgr(this, orgID)
    75  	if common.StellarNodeID != orgID {
    76  		go orgsync.Start()
    77  	}
    78  	this.orgman.OrgSync[orgID] = orgsync
    79  	// add org and StellarNode need call PingTo
    80  	np := this.network.GetNp()
    81  	np.RLock()
    82  	peers := make([]*peer.Peer, 0)
    83  	for _, p := range np.List {
    84  		if p.GetSyncState() == common.ESTABLISH {
    85  			peers = append(peers, p)
    86  		}
    87  	}
    88  	np.RUnlock()
    89  	go this.PingTo(peers, false, orgID)
    90  	//go this.orgConTimer(orgID)
    91  
    92  	// }
    93  	fmt.Println("๐ŸŒ  ๐Ÿ“จ  add league ", orgID.ToString())
    94  }
    95  
    96  // Timing is sent to the bootnode at regular intervals, and the bootnode is updated.
    97  // The stellar node is also a special circle.
    98  func (this *P2PServer) orgConTimer(orgID comm.Address) {
    99  	t := time.NewTicker(60 * time.Second)
   100  	defer t.Stop()
   101  
   102  	for {
   103  		select {
   104  		case <-t.C:
   105  			this.orgman.Lock()
   106  			_, ok := this.orgman.OrgSync[orgID]
   107  			this.orgman.Unlock()
   108  
   109  			if ok {
   110  				errNode, errs := this.ntab.SendBootNodeOrg(this.bootnodes, orgID, this.network.GetID(), true)
   111  				log.Info("[P2PServer] orgConTimer", "orgID", orgID, ",errNode", errNode, ",errs", errs)
   112  			} else {
   113  				return
   114  			}
   115  		}
   116  	}
   117  }
   118  
   119  // 1. Implement sending circle information to bootnode
   120  // 2. Get the information in the circle
   121  // 3. Filter the connected nodes and their own nodes
   122  // 4. Connect the node
   123  func (this *P2PServer) orgConPeer(orgID comm.Address) bool {
   124  	log.Info("====>>>>P2PServer orgConPeer", "orgID", orgID.ToString())
   125  	this.sendOrgToBN(orgID)
   126  	//fmt.Println(" ***** 333333 ****** ")
   127  	mapid := this.getOrgsFormBN(orgID)
   128  	//fmt.Println("$$$$$$$$$$$$$$$$$===========>>>>>>>>>>>>", orgID.ToString(), len(mapid))
   129  	if len(mapid) > 0 {
   130  		this.orgConnect(orgID, mapid, false)
   131  		return true
   132  	}
   133  	return false
   134  }
   135  
   136  func (this *P2PServer) sendOrgToBN(orgID comm.Address) {
   137  	errNode, errs := this.ntab.SendBootNodeOrg(this.bootnodes, orgID, this.network.GetID(), true)
   138  	log.Info("[P2PServer] sendOrgToBN", "orgID:", orgID.ToString(), ",errNode:", errNode, ",errs:", errs)
   139  }
   140  
   141  func (this *P2PServer) getOrgsFormBN(orgID comm.Address) map[discover.NodeID]*discover.Node {
   142  	mapid := this.ntab.GetOrgNodesFromBN(this.bootnodes, orgID)
   143  	log.Debug(" ********* getOrgsFormBN mapid:", "mapid", mapid)
   144  	return mapid
   145  }
   146  
   147  func (this *P2PServer) orgConnect(orgID comm.Address, mapid map[discover.NodeID]*discover.Node, banode bool) {
   148  	// connectnodes := make([]*discover.Node,0)
   149  	np := this.network.GetNp()
   150  	np.Lock()
   151  	for _, p := range np.List {
   152  		if p.GetSyncState() == common.ESTABLISH {
   153  			if _, ok := mapid[p.GetNode().ID]; ok {
   154  				delete(mapid, p.GetNode().ID)
   155  			}
   156  		}
   157  	}
   158  	np.Unlock()
   159  
   160  	delete(mapid, this.ntab.Self().ID)
   161  	//fmt.Println(" *********** mapid:", len(mapid), ",mapid:", mapid)
   162  
   163  	for _, connectnode := range mapid {
   164  		addr := &net.TCPAddr{IP: connectnode.IP, Port: int(connectnode.TCP)}
   165  		this.network.Connect(addr.String(), false, connectnode, banode, orgID)
   166  	}
   167  	// fmt.Println(" ******* getRandList len(seedNodes):",len(seedNodes),"nodes:",seedNodes)
   168  }
   169  
   170  // del org; from acror
   171  func (this *P2PServer) DelOrg(orgID comm.Address) {
   172  	this.orgman.Lock()
   173  	defer this.orgman.Unlock()
   174  
   175  	// Update the status of the circle in this peer when the node deletes the circle.
   176  	this.network.PeerDelOrg(orgID)
   177  
   178  	if orgsync, ok := this.orgman.OrgSync[orgID]; ok {
   179  		orgsync.Close()
   180  		delete(this.orgman.OrgSync, orgID)
   181  		log.Info(" [P2PServer] DelOrg", "orgID", orgID)
   182  		go this.orgDelTimer(orgID)
   183  		// When the node deletes a circle, the circle information of the remote node is also deleted.
   184  		this.delOrgFromNP(orgID)
   185  
   186  	} else {
   187  		fmt.Println(" P2PServer DelOrg ่ฎฐๅฝ•ไธ‹่ฟ™ไธชๅผ‚ๅธธ็š„ไธœ่ฅฟ ")
   188  	}
   189  }
   190  
   191  // Whenever you delete the circle information of the remote node,
   192  // you need to send a disconnect message like bootnode.
   193  func (this *P2PServer) delOrgFromNP(orgID comm.Address) {
   194  	peerids := this.network.RemoteDelOrg(orgID)
   195  	log.Info(" ****** P2PServer delOrgFromNP", "peerids", peerids)
   196  	if len(peerids) > 0 {
   197  		// Note: Because the star node does not maintain connection information,
   198  		// So you only need to send the connection information that the far end becomes a non-stellar node.
   199  		// I become a non-stellar node and send it directly out of the star node.
   200  		if orgID != common.StellarNodeID {
   201  			for _, peerid := range peerids {
   202  				this.SentDisconnectToBootNode(peerid, false)
   203  			}
   204  		}
   205  	}
   206  }
   207  
   208  // When the node exits the circle, it must report to the bootnode.
   209  func (this *P2PServer) orgDelTimer(orgID comm.Address) {
   210  	errNode, errs := this.ntab.SendBootNodeOrg(this.bootnodes, orgID, this.network.GetID(), false)
   211  	log.Info("[P2PServer] orgDelTimer ", "orgID", orgID, ",errNode", errNode, ",errs", errs)
   212  }
   213  
   214  // The real join operation is done in sync
   215  func (this *P2PServer) OrgAddNode(id uint64, orgID comm.Address) {
   216  	this.orgman.Lock()
   217  	defer this.orgman.Unlock()
   218  
   219  	if orgsync, ok := this.orgman.OrgSync[orgID]; ok {
   220  		orgsync.OnAddNode(id)
   221  	} else {
   222  		fmt.Println(" P2PServer OrgAddNode ")
   223  	}
   224  }
   225  
   226  // The real delete operation is done in sync
   227  func (this *P2PServer) OrgDelNode(id uint64, orgID comm.Address) {
   228  	this.orgman.Lock()
   229  	defer this.orgman.Unlock()
   230  
   231  	if orgsync, ok := this.orgman.OrgSync[orgID]; ok {
   232  		// fmt.Println(" ****** P2PServer OrgDelNode id:",id,",orgID:",orgID)
   233  		orgsync.OnDelNode(id)
   234  	}
   235  	/* else { //
   236  		fmt.Println(" P2PServer OrgDelNode  ")
   237  	}*/
   238  }
   239  
   240  func (this *P2PServer) OrgHeaderReceive(fromID uint64, headers []*orgtypes.Header, orgID comm.Address) {
   241  	this.orgman.Lock()
   242  	defer this.orgman.Unlock()
   243  
   244  	if orgsync, ok := this.orgman.OrgSync[orgID]; ok {
   245  		orgsync.OnHeaderReceive(fromID, headers)
   246  	} else {
   247  		fmt.Println(" P2PServer OrgHeaderReceive  ")
   248  	}
   249  }
   250  
   251  func (this *P2PServer) OrgBlockReceive(fromID uint64, blockSize uint32, block *orgtypes.Block, orgID comm.Address) {
   252  	this.orgman.Lock()
   253  	defer this.orgman.Unlock()
   254  
   255  	if orgsync, ok := this.orgman.OrgSync[orgID]; ok {
   256  		orgsync.OnBlockReceive(fromID, blockSize, block)
   257  	} else {
   258  		fmt.Println(" P2PServer OrgBlockReceive  ")
   259  	}
   260  }
   261  
   262  // table connect callback
   263  func (this *P2PServer) TabCallPeerConnectInfo() (uint64, []uint64) {
   264  	result := make([]uint64, 0)
   265  	// This node should not send connection information for orgs without a org.
   266  	// BHaveOrgsExceptId the orgs without StellarNode
   267  	if !this.network.BHaveOrgsExceptId(common.StellarNodeID) {
   268  		return this.GetID(), result
   269  	}
   270  
   271  	np := this.network.GetNp()
   272  	np.RLock()
   273  	for _, tn := range np.List {
   274  		// connected and have orgs without stellar info
   275  		if tn.GetSyncState() == common.ESTABLISH && tn.BHaveOrgsExceptId(common.StellarNodeID) {
   276  			result = append(result, tn.GetID())
   277  		}
   278  	}
   279  	np.RUnlock()
   280  
   281  	fmt.Println(" *8888888* P2PServer TabCallConnect ", "this.GetID()", this.GetID(), ",result", result)
   282  	return this.GetID(), result
   283  }
   284  
   285  // table org callback whithout stellar info
   286  func (this *P2PServer) TabCallPeerOrgInfo() (uint64, []comm.Address) {
   287  	//fmt.Println(" *8888888* P2PServer TabCallOrg", "this.GetID()", this.GetID(), "PeerGetOrg", this.network.PeerGetOrg())
   288  	orgs := make([]comm.Address, 0)
   289  	for _, orgid := range this.network.PeerGetOrg() {
   290  		if orgid != common.StellarNodeID { // del stellar
   291  			orgs = append(orgs, orgid)
   292  		}
   293  	}
   294  	return this.GetID(), orgs
   295  }
   296  
   297  // connect callback
   298  func (this *P2PServer) TabCallSendConnectOrg(destnode *discover.Node, orgid comm.Address) {
   299  	addr := &net.TCPAddr{IP: destnode.IP, Port: int(destnode.TCP)}
   300  	go this.network.Connect(addr.String(), false, destnode, false)
   301  }
   302  
   303  // stellarnode add,merge with org
   304  func (this *P2PServer) StellarNodeAdd() {
   305  	log.Info(" ***** [P2PServer] StellarNodeAdd start ...")
   306  	//
   307  	this.nodeStar.AddStar()
   308  	log.Info("====>>>>P2PServer StellarNodeAdd", "StellarNodeID", common.StellarNodeID.ToString())
   309  	this.AddOrg(common.StellarNodeID)
   310  }
   311  
   312  // stellarnode del,merge with org
   313  func (this *P2PServer) StellarNodeDel() {
   314  	log.Info(" ***** [P2PServer] StellarNodeDel start ...")
   315  	//
   316  	this.nodeStar.DelStar()
   317  	this.DelOrg(common.StellarNodeID)
   318  }
   319  
   320  // RemoteAddStellarNode remote add Stellar info
   321  func (this *P2PServer) RemoteAddStellarNode(id uint64) {
   322  	log.Info(" ***** [P2PServer] RemoteAddStellarNode start ...")
   323  	// This should send connection information like bootnode
   324  	// Now bn does not maintain the connection information of the stellar node, so there is no need to send node information to bn
   325  	// this.SentConnectToBootNode(id)
   326  	// Update NP information is the same as org logic in sync_handler.go
   327  }
   328  
   329  // RemoteDelStellarNode remote del Stellar info
   330  func (this *P2PServer) RemoteDelStellarNode(id uint64) {
   331  	log.Info(" ***** [P2PServer] RemoteDelStellarNode start ...")
   332  	// Update NP information; org's del logic is done in org_block_sync.go;
   333  	// This should send disconnection information like bootnode
   334  	this.SentDisconnectToBootNode(id, true)
   335  
   336  }
   337  
   338  // org connect to bootnode
   339  func (this *P2PServer) SentConnectToBootNode(remoteid uint64) {
   340  	go func() {
   341  		errNode, errs := this.ntab.SendBootNodeConnect(this.bootnodes, this.network.GetID(), remoteid, true, false)
   342  		log.Info("[P2PServer] SentConnectToBootNode", "errNode", this.bootnodes,
   343  			"ownid", this.network.GetID(), "remoteid", remoteid, "errNode", errNode, "errs", errs)
   344  	}()
   345  }
   346  
   347  // org disconnect to bootnode
   348  func (this *P2PServer) SentDisconnectToBootNode(remoteid uint64, bstellar bool) {
   349  	go func() {
   350  		errNode, errs := this.ntab.SendBootNodeConnect(this.bootnodes, this.network.GetID(), remoteid, false, bstellar)
   351  		log.Info("[P2PServer] SentDisconnectToBootNode", "errNode", this.bootnodes,
   352  			"ownid", this.network.GetID(), "remoteid", remoteid, "errNode", errNode, "errs", errs)
   353  	}()
   354  }
   355  
   356  
   357  func (this *P2PServer) AddANode(orgid comm.Address) bool {
   358  	// add anode
   359  	this.nodeA.AddOrgOfA(orgid)
   360  
   361  	fmt.Println("๐ŸŒ  add node โญ•", orgid.ToString())
   362  	// add org
   363  	this.AddOrg(orgid)
   364  	// get StellarNode
   365  	/*	mapid := this.getOrgsFormBN(common.StellarNodeID)
   366  		for j := 0; len(mapid) <= 0 && j < ANODE_GETSTELLAR_TIMES; j++ {
   367  			log.Warn("P2PServer AddANode getOrgsFormBN StellarNodeID is null", "times", j)
   368  			time.Sleep(time.Second)
   369  			fmt.Println("๐ŸŒ  add node โญ•  getOrgsFormBN", j)
   370  			mapid = this.getOrgsFormBN(common.StellarNodeID)
   371  
   372  		}*/
   373  
   374  	//temp by rennbon 2019-01-26
   375  	np := this.network.GetNp()
   376  	mapid := make(map[discover.NodeID]*discover.Node)
   377  	for _, v := range np.List {
   378  		mapid[v.GetNode().ID] = v.GetNode()
   379  	}
   380  	//temp end
   381  
   382  	if len(mapid) <= 0 {
   383  		return false
   384  	}
   385  	fmt.Println("๐ŸŒ  add node โญ•  mapid len:", len(mapid))
   386  	stellarnodes := make(map[discover.NodeID]*discover.Node)
   387  	stellarnodeid := make(map[discover.NodeID]bool)
   388  	i := 0
   389  	for nodeid, node := range mapid {
   390  		stellarnodes[nodeid] = node
   391  		stellarnodeid[nodeid] = true
   392  		i++
   393  		/*if i >= common.ANODE_CONNECT_STELLARNODE_NUM {
   394  			break
   395  		}*/
   396  	}
   397  	/*for k, v := range stellarnodeid {
   398  		fmt.Println("๐ŸŒ  add node โญ•  ", k.String(), v)
   399  	}*/
   400  	// This is connected to the star node, so let the other party know that it is the A node.
   401  	// connet to StellarNode
   402  	this.orgConnect(orgid, stellarnodes, true)
   403  	// The A node knows which stellar nodes are connected, but the stellar nodes don't know which A nodes are connected.
   404  	// Here to maintain a link, the message dialogue between the A node and the star node
   405  	go this.anodeGetPeerID(stellarnodeid)
   406  
   407  	//fmt.Println("๐ŸŒ  add node โญ•  ๏ธ", orgid.ToString(), " โœ…")
   408  	return true
   409  
   410  }
   411  
   412  func (this *P2PServer) anodeGetPeerID(stellarnodeid map[discover.NodeID]bool) {
   413  	peernodeidm := make(map[uint64]discover.NodeID)
   414  	//fmt.Println("๐ŸŒ  ๐Ÿ“   anode add peer map len from๏ผš", len(stellarnodeid))
   415  	for i := 0; i < 5; i++ {
   416  		remainnodeid, addpeerid := this.anodeCheck(stellarnodeid)
   417  		//fmt.Printf("๐ŸŒ  ๐Ÿ“  addpeerid len:%d ;remainnodeid len:%d \n", len(addpeerid), len(remainnodeid))
   418  		if len(addpeerid) > 0 {
   419  			for peerid, nodeid := range addpeerid {
   420  				peernodeidm[peerid] = nodeid
   421  			}
   422  		}
   423  		if len(remainnodeid) <= 0 {
   424  			break
   425  		}
   426  		stellarnodeid = remainnodeid
   427  		time.Sleep(time.Second)
   428  	}
   429  	//fmt.Println("๐ŸŒ  ๐Ÿ“   anode add peer map len real๏ผš", len(peernodeidm))
   430  	this.nodeA.AddPeers(peernodeidm)
   431  }
   432  
   433  func (this *P2PServer) anodeCheck(stellarnodeid map[discover.NodeID]bool) (map[discover.NodeID]bool, map[uint64]discover.NodeID) {
   434  	delnodeid := make([]discover.NodeID, 0)
   435  	addpeerid := make(map[uint64]discover.NodeID)
   436  
   437  	np := this.network.GetNp()
   438  	np.RLock()
   439  	for _, p := range np.List {
   440  		//fmt.Printf("โ˜ข๏ธ  key:%d ,value:%s\n", k, p.GetNode().ID.String())
   441  		if _, ok := stellarnodeid[p.GetNode().ID]; ok {
   442  			delnodeid = append(delnodeid, p.GetNode().ID)
   443  			addpeerid[p.GetID()] = p.GetNode().ID
   444  		}
   445  	}
   446  	np.RUnlock()
   447  	for _, nodeid := range delnodeid {
   448  		delete(stellarnodeid, nodeid)
   449  	}
   450  	return stellarnodeid, addpeerid
   451  }
   452  
   453  func (this *P2PServer) HandlerANodeConn(idm map[discover.NodeID]bool) {
   454  	return
   455  	count := common.ANODE_CONNECT_STELLARNODE_NUM - len(idm)
   456  	if count <= 0 {
   457  		return
   458  	}
   459  
   460  	// get StellarNode
   461  	fmt.Println(" ***** 111111 ****** ")
   462  	mapid := this.getOrgsFormBN(common.StellarNodeID)
   463  	stellarnodes := make(map[discover.NodeID]*discover.Node)
   464  	stellarnodeid := make(map[discover.NodeID]bool)
   465  	i := 0
   466  	for nodeid, node := range mapid {
   467  		if _, ok := idm[nodeid]; !ok {
   468  			stellarnodes[nodeid] = node
   469  			stellarnodeid[nodeid] = true
   470  			i++
   471  			if i >= count {
   472  				break
   473  			}
   474  		}
   475  	}
   476  
   477  	// This is connected to the star node, so let the other party know that it is the A node.
   478  	// connet to StellarNode
   479  	// TODO: The first parameter is first set to empty here.
   480  	this.orgConnect(comm.Address{}, stellarnodes, true)
   481  	go this.anodeGetPeerID(stellarnodeid)
   482  }
   483  
   484  func (this *P2PServer) DelANode(orgid comm.Address) {
   485  	this.nodeA.DelOrgOfA(orgid)
   486  	this.DelOrg(orgid)
   487  }
   488  
   489  func (this *P2PServer) BANode() bool {
   490  	return this.nodeA.BANode()
   491  }
   492  
   493  func (this *P2PServer) StarConnedNodeAInfo(id uint64) {
   494  	this.nodeStar.AddPeers(id)
   495  }
   496  
   497  func (this *P2PServer) HandlerPingPongSpc(msg *common.PingPongSpcHandler) {
   498  	if msg.BNodeASrc {
   499  		this.nodeA.OnReceive(msg.PeerID, msg.BOtherSideReq)
   500  	} else { // TODO: ่ฟ™ไธช่ฆๅœจๆ’ๆ˜Ÿ่Š‚็‚น้‡Œ้ขๅŽปๅค„็†
   501  		this.nodeStar.OnReceive(msg.PeerID, msg.BOtherSideReq)
   502  	}
   503  }
   504  
   505  // Timing to check connection information and strategy for handling disconnections
   506  func (this *P2PServer) checkConn() {
   507  	t := time.NewTicker(time.Second * CHECKCONN_NUM)
   508  	defer t.Stop()
   509  
   510  	for {
   511  		select {
   512  		case <-t.C:
   513  			this.analysConn()
   514  		case <-this.quitCheckConn:
   515  			return
   516  		}
   517  	}
   518  }
   519  
   520  type disAnalyOrgInfo struct {
   521  	connect   map[uint64]bool
   522  	predelnum int //
   523  }
   524  
   525  func (this *P2PServer) analysConn() {
   526  	peersCount, orgPeerM, stellarNodeM, ordinaryNodeM := this.getRemoteConnOrg()
   527  	// Compare if the connection is exceeded
   528  	totalconn := config.GlobalConfig.P2PCfg.MaxConnInBound + config.GlobalConfig.P2PCfg.MaxConnOutBound
   529  	if uint(peersCount) <= totalconn { // The number of connections has not exceeded the limit
   530  		return
   531  	}
   532  	// Record the log, indicating that the connection exceeds the upper limit
   533  	log.Info("P2PServer analysConn the connection of the node has exceeded the upper limit", "peersCount", peersCount)
   534  	// Obtain the information of the A node maintained by the stellar node
   535  	// and the information of the stellar node maintained by the A node.
   536  	spcConnM := this.getSpecConn()
   537  
   538  	// Filter some connections
   539  	orgPeerM = this.filterConnection(orgPeerM, stellarNodeM, spcConnM)
   540  
   541  	// Analysis of disconnection strategy
   542  	this.analysDisconn(orgPeerM, ordinaryNodeM, peersCount-int(totalconn))
   543  }
   544  
   545  func (this *P2PServer) getSpecConn() map[uint64]bool {
   546  	specConn := make(map[uint64]bool)
   547  	for _, peerid := range this.nodeA.GetPeers() {
   548  		specConn[peerid] = true
   549  	}
   550  
   551  	for _, peerid := range this.nodeStar.GetPeers() {
   552  		specConn[peerid] = true
   553  	}
   554  	return specConn
   555  }
   556  
   557  func (this *P2PServer) getRemoteConnOrg() (int, map[comm.Address]*disAnalyOrgInfo, map[uint64]bool, map[uint64]bool) {
   558  	peersCount := 0 // The total number of nodes
   559  	//Pro node circle information maintained by this node
   560  	orgpeerm := make(map[comm.Address]*disAnalyOrgInfo)
   561  	//Pro node star node information maintained by this node
   562  	stellarnodem := make(map[uint64]bool)
   563  	//Pro node general node information maintained by this node
   564  	ordinarynodem := make(map[uint64]bool)
   565  
   566  	np := this.network.GetNp()
   567  	np.RLock()
   568  	for _, p := range np.List {
   569  		if p.GetSyncState() != common.ESTABLISH {
   570  			continue
   571  		}
   572  		peersCount++
   573  		orgs := p.GetRemoteOrgs()
   574  		if len(orgs) <= 0 {
   575  			ordinarynodem[p.GetID()] = true
   576  			continue
   577  		}
   578  
   579  		for _, orgid := range orgs {
   580  			if orgid == common.StellarNodeID {
   581  				stellarnodem[p.GetID()] = true
   582  				continue
   583  			}
   584  
   585  			if _, ok := orgpeerm[orgid]; !ok {
   586  				orgpeerm[orgid] = &disAnalyOrgInfo{
   587  					connect: make(map[uint64]bool),
   588  				}
   589  			}
   590  			orgpeerm[orgid].connect[p.GetID()] = true
   591  		}
   592  	}
   593  	np.RUnlock()
   594  	return peersCount, orgpeerm, stellarnodem, ordinarynodem
   595  }
   596  
   597  // 1. If the number of connections in the circle is less than or equal to 10, then the disconnection of this node is not checked.
   598  // 2. If the connected node of the circle is also a star node or a special connection, then the disconnection of the node is not checked.
   599  func (this *P2PServer) filterConnection(orgpeerm map[comm.Address]*disAnalyOrgInfo,
   600  	stellarnodem, spcConnM map[uint64]bool) map[comm.Address]*disAnalyOrgInfo {
   601  
   602  	delorgs := make([]comm.Address, 0)
   603  	for orgid, orginfo := range orgpeerm {
   604  		// No to ten connections are not deleted
   605  		if len(orginfo.connect) <= common.ORG_CONNECT_ORG_NUM {
   606  			delorgs = append(delorgs, orgid)
   607  			continue
   608  		}
   609  		// num
   610  		orginfo.predelnum = len(orginfo.connect) - common.ORG_CONNECT_ORG_NUM
   611  
   612  		delpeers := make([]uint64, 0)
   613  		for peerid, _ := range orginfo.connect {
   614  			if _, ok := stellarnodem[peerid]; ok {
   615  				delpeers = append(delpeers, peerid)
   616  			}
   617  			if _, ok := spcConnM[peerid]; ok {
   618  				delpeers = append(delpeers, peerid)
   619  			}
   620  		}
   621  		for _, peerid := range delpeers {
   622  			delete(orgpeerm[orgid].connect, peerid)
   623  		}
   624  		if len(orgpeerm[orgid].connect) <= 0 {
   625  			delorgs = append(delorgs, orgid)
   626  		}
   627  		delpeers = make([]uint64, 0)
   628  	}
   629  	for _, orgid := range delorgs {
   630  		delete(orgpeerm, orgid)
   631  	}
   632  	return orgpeerm
   633  }
   634  
   635  func (this *P2PServer) analysDisconn(orgpeerm map[comm.Address]*disAnalyOrgInfo,
   636  	ordinarynodem map[uint64]bool, predelcount int) {
   637  
   638  	// handler org
   639  	disConnPeerM := make(map[comm.Address]*disAnalyOrgInfo)
   640  	delOrgCount := 0
   641  	for {
   642  		temorgpeerm, disconninfo, orgid := this.analysOrg(orgpeerm)
   643  		count := len(disconninfo.connect)
   644  		if count > disconninfo.predelnum {
   645  			count = disconninfo.predelnum
   646  		}
   647  		if count > 0 {
   648  			delOrgCount = delOrgCount + count
   649  			i := 0
   650  			disanalyinfo := new(disAnalyOrgInfo)
   651  			disanalyinfo.connect = make(map[uint64]bool)
   652  			for id, _ := range disconninfo.connect {
   653  				disanalyinfo.connect[id] = true
   654  				i++
   655  				if i >= count {
   656  					break
   657  				}
   658  			}
   659  			disConnPeerM[orgid] = disanalyinfo
   660  		}
   661  
   662  		if len(temorgpeerm) <= 0 {
   663  			break
   664  		}
   665  		orgpeerm = temorgpeerm
   666  	}
   667  	// send channel to del the org conns
   668  	for orgid, info := range disConnPeerM {
   669  		for peerid, _ := range info.connect {
   670  			this.network.HaltOrgPeerID(peerid, orgid)
   671  		}
   672  	}
   673  
   674  	// handler ordinarynode
   675  	// if delOrgCount >= predelcount {
   676  	// 	return
   677  	// }
   678  
   679  	if delOrgCount+2*common.ORG_CONNECT_ORG_NUM >= predelcount {
   680  		return
   681  	}
   682  
   683  	if len(ordinarynodem) <= 2*common.ORG_CONNECT_ORG_NUM {
   684  		return
   685  	}
   686  	preDelOrdinary := len(ordinarynodem) - 2*common.ORG_CONNECT_ORG_NUM
   687  	disOrdinaryConn := make(map[uint64]bool)
   688  	i := 0
   689  	for peerid, _ := range ordinarynodem {
   690  		disOrdinaryConn[peerid] = true
   691  		i++
   692  		if i >= preDelOrdinary {
   693  			break
   694  		}
   695  	}
   696  	// send channel to del the ordinaryrg conns
   697  	// disOrdinaryConn
   698  	for peerid, _ := range disOrdinaryConn {
   699  		this.network.HaltOrdinaryPeerID(peerid)
   700  	}
   701  }
   702  
   703  func (this *P2PServer) analysOrg(orgpeerm map[comm.Address]*disAnalyOrgInfo) (map[comm.Address]*disAnalyOrgInfo, *disAnalyOrgInfo, comm.Address) {
   704  	// Get random org IDs and connection information for orgs
   705  	disSrcInfo := new(disAnalyOrgInfo)
   706  	var orgid comm.Address
   707  	for id, info := range orgpeerm {
   708  		if info != nil {
   709  			disSrcInfo = info
   710  			orgid = id
   711  			break
   712  		}
   713  	}
   714  
   715  	// Delete random org
   716  	delete(orgpeerm, orgid)
   717  	if len(orgpeerm) <= 0 {
   718  		return orgpeerm, disSrcInfo, orgid
   719  	}
   720  
   721  	delpeeridm := make(map[uint64]bool)
   722  	delorgid := make(map[comm.Address]bool)
   723  	for srcpeerid, _ := range disSrcInfo.connect {
   724  		for orgid, disinfo := range orgpeerm {
   725  			if _, ok := disinfo.connect[srcpeerid]; ok {
   726  				delete(disinfo.connect, srcpeerid)
   727  				if len(disinfo.connect) <= 0 {
   728  					delorgid[orgid] = true
   729  				}
   730  				delpeeridm[srcpeerid] = true
   731  			}
   732  		}
   733  	}
   734  	for id, _ := range delpeeridm {
   735  		delete(disSrcInfo.connect, id)
   736  	}
   737  	for id, _ := range delorgid {
   738  		delete(orgpeerm, id)
   739  	}
   740  	return orgpeerm, disSrcInfo, orgid
   741  }
   742  
   743  // A node sends circle data to the star node
   744  func (this *P2PServer) AToStellarPendingData(data *common.OrgPendingData) {
   745  	log.Debug("[p2p]AToStellarPendingData block message")
   746  	//fmt.Printf("๐ŸŒ  AToStellarPendingData โญ•๏ธ  %s,blockHeight:%d, peer len %d\n", data.OrgId.ToString(), data.Block.Header.Height, len(this.nodeA.GetPeers()))
   747  	msg := msgpack.NewBlock(nil, data.Block, data.OrgId, common.SYNC_DATA_A_TO_STELLAR)
   748  
   749  	notifyp2pactor, err := bactor.GetActorPid(bactor.MAINRADARACTOR)
   750  	if err != nil {
   751  		log.Error("ANodeSendToStellarPeingData GetActorPid err", "org", data.OrgId, "err", err)
   752  		return
   753  	}
   754  	notifyp2pactor.Tell(data.Block)
   755  
   756  	//fmt.Println("msg genis start point blockhash=", data.Block.Hash(), " orgid=", data.OrgId, " distlen=", len(this.nodeA.GetPeers()))
   757  
   758  	for _, peerid := range this.nodeA.GetPeers() {
   759  		//fmt.Println("๐ŸŒ AToStellarPendingData 1", peerid)
   760  		peer := this.GetNode(peerid)
   761  		if peer == nil {
   762  			continue
   763  		}
   764  		//fmt.Println("๐ŸŒ AToStellarPendingData 2")
   765  		if peer.GetSyncState() == common.ESTABLISH && peer.GetRelay(){
   766  			err := this.Send(peer, msg, false)
   767  			if err != nil {
   768  				log.Error("p2pserer_business atostellar pending data error", "error", err)
   769  			}
   770  		}
   771  	}
   772  }
   773  
   774  // Broadcast circle data between stellar nodes
   775  func (this *P2PServer) StellarToStellarPendingData(data *common.OrgPendingData) {
   776  	log.Debug("[p2p]StellarToStellarPendingData block message")
   777  	msg := msgpack.NewBlock(nil, data.Block, data.OrgId, common.SYNC_DATA_STELLAR_TO_STELLAR)
   778  	//fmt.Println("๐ŸŒ height:", data.Block.Header.Height, ", hash:", data.Block.Header.LeagueId.ToString())
   779  	np := this.network.GetNp()
   780  	for _, p := range np.List {
   781  		if p == nil {
   782  			continue
   783  		}
   784  		if p.GetSyncState() != common.ESTABLISH || !p.BHaveOrgID(common.StellarNodeID) {
   785  			continue
   786  		}
   787  		//fmt.Println("๐ŸŒ orgBlock ๐Ÿ”† to  ๐Ÿ”† ", p.GetID())
   788  		err := this.Send(p, msg, false)
   789  		if err != nil {
   790  			fmt.Printf("send to peer error=%v\n", err)
   791  		}
   792  	}
   793  }
   794  
   795  // for test ...
   796  func (this *P2PServer) testOrg() {
   797  	// fmt.Println(" ***** P2PServer testOrg start ...")
   798  	time.Sleep(5 * time.Second)
   799  	// portstr := strconv.Itoa(int(config.GlobalConfig.P2PCfg.NodePort))
   800  
   801  	addorg, err := comm.ToAddress("ct2b5xc5uyaJrSqZ866gVvM5QtXybprb9sy")
   802  	if err == nil {
   803  		this.AddOrg(addorg)
   804  		fmt.Println(" ******* P2PServer testOrg add:", addorg)
   805  	} else {
   806  		fmt.Println(" ******* P2PServer testOrg err:", err)
   807  	}
   808  
   809  	//	test add org
   810  	// if portstr == "22001" {
   811  	// 	go func(){
   812  	// 		fmt.Println(" ******* dis dis")
   813  	// 		time.Sleep(140*time.Second)
   814  	// 		this.DelOrg(add)
   815  	// 	}()
   816  	// }
   817  
   818  	//	test add star
   819  	// if portstr == "21001" {
   820  	// 	this.pid.Tell(&common.StellarNodeConnInfo{
   821  	// 		BAdd: true,
   822  	// 	})
   823  	// }
   824  
   825  	// if portstr == "21001" {
   826  	// 	go func(){
   827  	// 		fmt.Println(" ******* dis dis")
   828  	// 		time.Sleep(40*time.Second)
   829  	// 		this.pid.Tell(&common.StellarNodeConnInfo{
   830  	// 			BAdd: false,
   831  	// 		})
   832  	// 	}()
   833  	// }
   834  
   835  	//	test add ANode
   836  	// if portstr == "22001" {
   837  	// 	this.pid.Tell(&common.ANodeConnInfo{
   838  	// 		OrgId: addorg,
   839  	// 		BAdd: true,
   840  	// 	})
   841  	// }
   842  }