github.com/sixexorg/magnetic-ring@v0.0.0-20191119090307-31705a21e419/p2pserver/net/netserver/netserver.go (about) 1 package netserver 2 3 import ( 4 "crypto/ecdsa" 5 "errors" 6 "math/rand" 7 "net" 8 "strings" 9 "sync" 10 "time" 11 12 "github.com/sixexorg/magnetic-ring/config" 13 "github.com/sixexorg/magnetic-ring/log" 14 ledger "github.com/sixexorg/magnetic-ring/store/mainchain/storages" 15 16 comm "github.com/sixexorg/magnetic-ring/common" 17 "github.com/sixexorg/magnetic-ring/p2pserver/common" 18 "github.com/sixexorg/magnetic-ring/p2pserver/discover" 19 msgpack "github.com/sixexorg/magnetic-ring/p2pserver/message" 20 "github.com/sixexorg/magnetic-ring/p2pserver/net/protocol" 21 "github.com/sixexorg/magnetic-ring/p2pserver/peer" 22 "fmt" 23 ) 24 25 type P2PSer interface { 26 SentDisconnectToBootNode(remoteid uint64, bstellar bool) 27 BANode() bool 28 } 29 30 //NewNetServer return the net object in p2p 31 func NewNetServer(p2pser P2PSer) p2p.P2P { 32 n := &NetServer{ 33 SyncChan: make(chan *common.MsgPayload, common.CHAN_CAPABILITY), 34 ConsChan: make(chan *common.MsgPayload, common.CHAN_CAPABILITY), 35 } 36 n.p2pser = p2pser 37 38 n.PeerAddrMap.PeerSyncAddress = make(map[string]*peer.Peer) 39 n.PeerAddrMap.PeerConsAddress = make(map[string]*peer.Peer) 40 41 n.init() 42 return n 43 } 44 45 //NetServer represent all the actions in net layer 46 type NetServer struct { 47 base peer.PeerCom 48 synclistener net.Listener 49 conslistener net.Listener 50 SyncChan chan *common.MsgPayload 51 ConsChan chan *common.MsgPayload 52 ConnectingNodes 53 PeerAddrMap 54 Np *peer.NbrPeers 55 connectLock sync.Mutex 56 inConnRecord InConnectionRecord 57 outConnRecord OutConnectionRecord 58 OwnAddress string //network`s own address(ip : sync port),which get from version check 59 // 60 nodeKey *ecdsa.PrivateKey 61 ntable *discover.Table 62 bootnodes []*discover.Node 63 p2pser P2PSer 64 } 65 66 //InConnectionRecord include all addr connected 67 type InConnectionRecord struct { 68 sync.RWMutex 69 InConnectingAddrs []string 70 } 71 72 //OutConnectionRecord include all addr accepted 73 type OutConnectionRecord struct { 74 sync.RWMutex 75 OutConnectingAddrs []string 76 } 77 78 //ConnectingNodes include all addr in connecting state 79 type ConnectingNodes struct { 80 sync.RWMutex 81 ConnectingAddrs []string 82 } 83 84 //PeerAddrMap include all addr-peer list 85 type PeerAddrMap struct { 86 sync.RWMutex 87 PeerSyncAddress map[string]*peer.Peer 88 PeerConsAddress map[string]*peer.Peer 89 } 90 91 //init initializes attribute of network server 92 func (this *NetServer) init() error { 93 this.base.SetVersion(common.PROTOCOL_VERSION) 94 95 // if config.DefConfig.Consensus.EnableConsensus { 96 // this.base.SetServices(uint64(common.VERIFY_NODE)) 97 // } else { 98 // this.base.SetServices(uint64(common.SERVICE_NODE)) 99 // } 100 this.base.SetServices(uint64(common.SERVICE_NODE)) 101 102 if config.GlobalConfig.P2PCfg.NodePort == 0 { 103 log.Error("[p2p]link port invalid") 104 return errors.New("[p2p]invalid link port") 105 } 106 107 this.base.SetSyncPort(uint16(config.GlobalConfig.P2PCfg.NodePort)) 108 109 if config.GlobalConfig.P2PCfg.DualPortSupport { 110 if config.GlobalConfig.P2PCfg.NodeConsensusPort == 0 { 111 log.Error("[p2p]consensus port invalid") 112 return errors.New("[p2p]invalid consensus port") 113 } 114 115 this.base.SetConsPort(uint16(config.GlobalConfig.P2PCfg.NodeConsensusPort)) 116 } else { 117 this.base.SetConsPort(0) 118 } 119 120 this.base.SetRelay(true) 121 122 rand.Seed(time.Now().UnixNano()) 123 id := rand.Uint64() 124 125 this.base.SetID(id) 126 127 log.Info("[p2p]init peer ", "ID", this.base.GetID()) 128 this.Np = &peer.NbrPeers{} 129 this.Np.Init() 130 131 return nil 132 } 133 134 //InitListen start listening on the config port 135 func (this *NetServer) Start() { 136 this.startListening() 137 } 138 139 //GetVersion return self peer`s version 140 func (this *NetServer) GetVersion() uint32 { 141 return this.base.GetVersion() 142 } 143 144 //GetId return peer`s id 145 func (this *NetServer) GetID() uint64 { 146 return this.base.GetID() 147 } 148 149 // SetHeight sets the local's height 150 func (this *NetServer) SetHeight(height uint64) { 151 this.base.SetHeight(height) 152 } 153 154 // GetHeight return peer's heigh 155 func (this *NetServer) GetHeight() uint64 { 156 return this.base.GetHeight() 157 } 158 159 // SetHeight sets the local's height 160 func (this *NetServer) SetOwnOrgHeight(height uint64, id comm.Address) { 161 this.base.SetOwnOrgHeight(height, id) 162 } 163 164 // GetHeight return peer's heigh 165 func (this *NetServer) GetOwnOrgHeight(id comm.Address) uint64 { 166 return this.base.GetOwnOrgHeight(id) 167 } 168 169 // PeerAddOrg handle main peer add org ownnode 170 func (this *NetServer) PeerAddOrg(id comm.Address) { 171 this.base.PeerAddOrg(id) 172 } 173 174 // PeerDelOrg handle main peer del org ownnode 175 func (this *NetServer) PeerDelOrg(id comm.Address) { 176 this.base.PeerDelOrg(id) 177 } 178 179 // PeerGetOrg main peer's orgs ownnode 180 func (this *NetServer) PeerGetOrg() []comm.Address { 181 return this.base.PeerGetOrg() 182 } 183 184 func (this *NetServer) PeerGetRealOrg() []comm.Address { 185 return this.base.PeerGetRealOrg() 186 } 187 188 // PeerGetOrg main peer's orgs ownnode 189 func (this *NetServer) RemoteDelOrg(id comm.Address) []uint64 { 190 return this.GetNp().DelNbrOrg(id) 191 } 192 193 // PeerGetOrg main peer's orgs ownnode 194 func (this *NetServer) BHaveOrgs() bool { 195 return this.base.BHaveOrgs() 196 } 197 198 func (this *NetServer) BHaveOrgsExceptId(id comm.Address) bool { 199 return this.base.BHaveOrgsExceptId(id) 200 } 201 202 func (this *NetServer) BHaveOrgsId(id comm.Address) bool { 203 return this.base.BHaveOrgsId(id) 204 } 205 206 //GetTime return the last contact time of self peer 207 func (this *NetServer) GetTime() int64 { 208 t := time.Now() 209 return t.UnixNano() 210 } 211 212 //GetServices return the service state of self peer 213 func (this *NetServer) GetServices() uint64 { 214 return this.base.GetServices() 215 } 216 217 //GetSyncPort return the sync port 218 func (this *NetServer) GetSyncPort() uint16 { 219 return this.base.GetSyncPort() 220 } 221 222 //GetConsPort return the cons port 223 func (this *NetServer) GetConsPort() uint16 { 224 return this.base.GetConsPort() 225 } 226 227 //GetHttpInfoPort return the port support info via http 228 func (this *NetServer) GetHttpInfoPort() uint16 { 229 return this.base.GetHttpInfoPort() 230 } 231 232 //GetRelay return whether net module can relay msg 233 func (this *NetServer) GetRelay() bool { 234 return this.base.GetRelay() 235 } 236 237 // GetPeer returns a peer with the peer id 238 func (this *NetServer) GetPeer(id uint64) *peer.Peer { 239 return this.Np.GetPeer(id) 240 } 241 242 //return nbr peers collection 243 func (this *NetServer) GetNp() *peer.NbrPeers { 244 return this.Np 245 } 246 247 //GetNeighborAddrs return all the nbr peer`s addr 248 func (this *NetServer) GetNeighborAddrs() []common.PeerAddr { 249 return this.Np.GetNeighborAddrs() 250 } 251 252 //GetConnectionCnt return the total number of valid connections 253 func (this *NetServer) GetConnectionCnt() uint32 { 254 return this.Np.GetNbrNodeCnt() 255 } 256 257 //AddNbrNode add peer to nbr peer list 258 func (this *NetServer) AddNbrNode(remotePeer *peer.Peer) { 259 this.Np.AddNbrNode(remotePeer) 260 } 261 262 //DelNbrNode delete nbr peer by id 263 func (this *NetServer) DelNbrNode(id uint64) (*peer.Peer, bool) { 264 return this.Np.DelNbrNode(id) 265 } 266 267 //GetNeighbors return all nbr peer 268 func (this *NetServer) GetNeighbors() []*peer.Peer { 269 return this.Np.GetNeighbors() 270 } 271 272 //NodeEstablished return whether a peer is establish with self according to id 273 func (this *NetServer) NodeEstablished(id uint64) bool { 274 return this.Np.NodeEstablished(id) 275 } 276 277 //Xmit called by actor, broadcast msg 278 func (this *NetServer) Xmit(msg common.Message, isCons bool) { 279 fmt.Println("NetServerXmit----------->>>>>>>>>>>", msg.CmdType(), time.Now()) 280 log.Info("NetServerXmit----------->>>>>>>>>>>", "cmdtype", msg.CmdType(), "time:",time.Now()) 281 this.Np.Broadcast(msg, isCons) 282 } 283 284 //GetMsgChan return sync or consensus channel when msgrouter need msg input 285 func (this *NetServer) GetMsgChan(isConsensus bool) chan *common.MsgPayload { 286 if isConsensus { 287 return this.ConsChan 288 } else { 289 return this.SyncChan 290 } 291 } 292 293 //Tx send data buf to peer 294 func (this *NetServer) Send(p *peer.Peer, msg common.Message, isConsensus bool) error { 295 if p != nil { 296 if config.GlobalConfig.P2PCfg.DualPortSupport == false { 297 return p.Send(msg, false) 298 } 299 return p.Send(msg, isConsensus) 300 } 301 log.Warn("[p2p]send to a invalid peer") 302 return errors.New("[p2p]send to a invalid peer") 303 } 304 305 //IsPeerEstablished return the establise state of given peer`s id 306 func (this *NetServer) IsPeerEstablished(p *peer.Peer) bool { 307 if p != nil { 308 return this.Np.NodeEstablished(p.GetID()) 309 } 310 return false 311 } 312 313 //Connect used to connect net address under sync or cons mode 314 func (this *NetServer) Connect(addr string, isConsensus bool, node *discover.Node, bANode bool, orgids ...comm.Address) error { 315 if this.IsAddrInOutConnRecord(addr) { 316 log.Debug("[p2p]", "Address", addr, "Consensus", isConsensus) 317 return nil 318 } 319 if this.IsOwnAddress(addr) { 320 return nil 321 } 322 if !this.AddrValid(addr) { 323 return nil 324 } 325 326 if len(orgids) <= 0 && bANode == false { 327 this.connectLock.Lock() 328 connCount := uint(this.GetOutConnRecordLen()) 329 if connCount >= config.GlobalConfig.P2PCfg.MaxConnOutBound { 330 log.Warn("[p2p]Connect: out ", "connections", connCount, "reach the max limit", config.GlobalConfig.P2PCfg.MaxConnOutBound) 331 this.connectLock.Unlock() 332 return errors.New("[p2p]connect: out connections reach the max limit") 333 } 334 this.connectLock.Unlock() 335 } 336 337 if this.IsNbrPeerAddr(addr, isConsensus) { 338 return nil 339 } 340 this.connectLock.Lock() 341 if added := this.AddOutConnectingList(addr); added == false { 342 log.Debug("[p2p]node exist in connecting list", "addr", addr) 343 } 344 this.connectLock.Unlock() 345 346 isTls := config.GlobalConfig.P2PCfg.IsTLS 347 // fmt.Println(" ***** 888888888 888888 ***** isTls:",isTls) 348 var rlpconn *conn 349 var conn net.Conn 350 var err error 351 var remotePeer *peer.Peer 352 if isTls { 353 conn, err = TLSDial(addr) 354 if err != nil { 355 this.RemoveFromConnectingList(addr) 356 log.Debug("[p2p]", "connect", addr, "failed", err.Error()) 357 return err 358 } 359 } else { 360 conn, err = nonTLSDial(addr) 361 if err != nil { 362 this.RemoveFromConnectingList(addr) 363 log.Debug("[p2p]", "connect", addr, "failed", err.Error()) 364 return err 365 } 366 } 367 368 addr = conn.RemoteAddr().String() 369 log.Debug("[p2p]", "peer", conn.LocalAddr().String(), "connect with", conn.RemoteAddr().String(), "with", conn.RemoteAddr().Network()) 370 371 emptyaddr := comm.Address{} 372 if len(orgids) > 0 { 373 emptyaddr = orgids[0] 374 } 375 temrlpconn, _, _, errrlp := this.SetupConn(conn, node, &emptyaddr, bANode) 376 if errrlp != nil { 377 return errrlp 378 } 379 rlpconn = temrlpconn 380 381 this.AddOutConnRecord(addr) 382 remotePeer = peer.NewPeer() 383 this.AddPeerSyncAddress(addr, remotePeer) 384 remotePeer.SyncLink.SetAddr(addr) 385 remotePeer.SyncLink.SetConn(conn) 386 remotePeer.SyncLink.SetRLPConn(rlpconn) 387 remotePeer.AttachSyncChan(this.SyncChan) 388 go remotePeer.SyncLink.Rx() 389 remotePeer.SetSyncState(common.HAND) 390 391 version := msgpack.NewVersion(this, isConsensus, uint32(ledger.GetLedgerStore().GetCurrentBlockHeight())) 392 err = remotePeer.Send(version, isConsensus) 393 if err != nil { 394 if !isConsensus { 395 this.RemoveFromOutConnRecord(addr) 396 } 397 log.Warn("err", "err", err) 398 return err 399 } 400 return nil 401 } 402 403 //Halt stop all net layer logic 404 func (this *NetServer) Halt() { 405 peers := this.Np.GetNeighbors() 406 for _, p := range peers { 407 p.CloseSync() 408 p.CloseCons() 409 } 410 if this.synclistener != nil { 411 this.synclistener.Close() 412 } 413 if this.conslistener != nil { 414 this.conslistener.Close() 415 } 416 } 417 418 //Halt the ordinary peer 419 func (this *NetServer) HaltOrdinaryPeerID(id uint64) { 420 peer := this.GetPeer(id) 421 if peer == nil { 422 return 423 } 424 if peer.BHaveOrgs() { 425 return 426 } 427 peer.CloseSync() 428 peer.CloseCons() 429 430 } 431 432 //Halt the org peer 433 func (this *NetServer) HaltOrgPeerID(peerid uint64, orgid comm.Address) { 434 peer := this.GetPeer(peerid) 435 if peer == nil { 436 return 437 } 438 if peer.BHaveOrgID(orgid) { 439 peer.CloseSync() 440 peer.CloseCons() 441 } 442 } 443 444 //establishing the connection to remote peers and listening for inbound peers 445 func (this *NetServer) startListening() error { 446 var err error 447 448 syncPort := this.base.GetSyncPort() 449 //consPort := this.base.GetConsPort() 450 //fmt.Println(" ********** syncPort:",syncPort,"consPort",consPort) 451 452 if syncPort == 0 { 453 log.Error("[p2p]sync port invalid") 454 return errors.New("[p2p]sync port invalid") 455 } 456 457 err = this.startSyncListening(syncPort) 458 if err != nil { 459 log.Error("[p2p]start sync listening fail") 460 return err 461 } 462 463 return nil 464 } 465 466 // startSyncListening starts a sync listener on the port for the inbound peer 467 func (this *NetServer) startSyncListening(port uint16) error { 468 var err error 469 this.synclistener, err = createListener(port) 470 if err != nil { 471 log.Error("[p2p]failed to create sync listener") 472 return errors.New("[p2p]failed to create sync listener") 473 } 474 475 go this.startSyncAccept(this.synclistener) 476 log.Info("[p2p]start listen on sync ", "port", port) 477 return nil 478 } 479 480 //startSyncAccept accepts the sync connection from the inbound peer 481 func (this *NetServer) startSyncAccept(listener net.Listener) { 482 for { 483 conn, err := listener.Accept() 484 485 if err != nil { 486 log.Error("[p2p]error accepting ", "err", err.Error()) 487 return 488 } 489 490 log.Debug("[p2p]remote sync node connect with ", "RemoteAdd", conn.RemoteAddr(), "LocalAddr", conn.LocalAddr()) 491 if !this.AddrValid(conn.RemoteAddr().String()) { 492 log.Warn("[p2p]remote not in reserved list, close it ", "Addr", conn.RemoteAddr()) 493 conn.Close() 494 continue 495 } 496 497 if this.IsAddrInInConnRecord(conn.RemoteAddr().String()) { 498 conn.Close() 499 continue 500 } 501 502 rlpconn, bownorg, banode, errrlp := this.SetupConn(conn, nil, nil, false) 503 if errrlp != nil { 504 continue 505 } 506 if bownorg == false && banode == false { 507 syncAddrCount := uint(this.GetInConnRecordLen()) 508 if syncAddrCount >= config.GlobalConfig.P2PCfg.MaxConnInBound { 509 log.Warn("[p2p]SyncAccept: total connections", "syncAddrCount", syncAddrCount, "reach the max limit", config.GlobalConfig.P2PCfg.MaxConnInBound) 510 conn.Close() 511 continue 512 } 513 514 remoteIp, err := common.ParseIPAddr(conn.RemoteAddr().String()) 515 if err != nil { 516 log.Warn("[p2p]parse ip ", "error ", err.Error()) 517 conn.Close() 518 continue 519 } 520 connNum := this.GetIpCountInInConnRecord(remoteIp) 521 if connNum >= config.GlobalConfig.P2PCfg.MaxConnInBoundForSingleIP { 522 log.Warn("[p2p]SyncAccept: connections", "connNum", connNum, 523 "with ip", remoteIp, "has reach the max limit", config.GlobalConfig.P2PCfg.MaxConnInBoundForSingleIP) 524 conn.Close() 525 continue 526 } 527 } 528 529 remotePeer := peer.NewPeer() 530 addr := conn.RemoteAddr().String() 531 this.AddInConnRecord(addr) 532 533 this.AddPeerSyncAddress(addr, remotePeer) 534 535 remotePeer.SyncLink.SetAddr(addr) 536 remotePeer.SyncLink.SetConn(conn) 537 remotePeer.SyncLink.SetRLPConn(rlpconn) 538 539 remotePeer.AttachSyncChan(this.SyncChan) 540 go remotePeer.SyncLink.Rx() 541 } 542 } 543 544 //record the peer which is going to be dialed and sent version message but not in establish state 545 func (this *NetServer) AddOutConnectingList(addr string) (added bool) { 546 this.ConnectingNodes.Lock() 547 defer this.ConnectingNodes.Unlock() 548 for _, a := range this.ConnectingAddrs { 549 if strings.Compare(a, addr) == 0 { 550 return false 551 } 552 } 553 log.Trace("[p2p]add to out connecting list", "addr", addr) 554 this.ConnectingAddrs = append(this.ConnectingAddrs, addr) 555 return true 556 } 557 558 //Remove the peer from connecting list if the connection is established 559 func (this *NetServer) RemoveFromConnectingList(addr string) { 560 this.ConnectingNodes.Lock() 561 defer this.ConnectingNodes.Unlock() 562 addrs := this.ConnectingAddrs[:0] 563 for _, a := range this.ConnectingAddrs { 564 if a != addr { 565 addrs = append(addrs, a) 566 } 567 } 568 log.Trace("[p2p]remove from out connecting list", "addr", addr) 569 this.ConnectingAddrs = addrs 570 } 571 572 //record the peer which is going to be dialed and sent version message but not in establish state 573 func (this *NetServer) GetOutConnectingListLen() (count uint) { 574 this.ConnectingNodes.RLock() 575 defer this.ConnectingNodes.RUnlock() 576 return uint(len(this.ConnectingAddrs)) 577 } 578 579 //check peer from connecting list 580 func (this *NetServer) IsAddrFromConnecting(addr string) bool { 581 this.ConnectingNodes.Lock() 582 defer this.ConnectingNodes.Unlock() 583 for _, a := range this.ConnectingAddrs { 584 if strings.Compare(a, addr) == 0 { 585 return true 586 } 587 } 588 return false 589 } 590 591 //find exist peer from addr map 592 func (this *NetServer) GetPeerFromAddr(addr string) *peer.Peer { 593 var p *peer.Peer 594 this.PeerAddrMap.RLock() 595 defer this.PeerAddrMap.RUnlock() 596 597 p, ok := this.PeerSyncAddress[addr] 598 if ok { 599 return p 600 } 601 p, ok = this.PeerConsAddress[addr] 602 if ok { 603 return p 604 } 605 return nil 606 } 607 608 //IsNbrPeerAddr return result whether the address is under connecting 609 func (this *NetServer) IsNbrPeerAddr(addr string, isConsensus bool) bool { 610 var addrNew string 611 this.Np.RLock() 612 defer this.Np.RUnlock() 613 for _, p := range this.Np.List { 614 if p.GetSyncState() == common.HAND || p.GetSyncState() == common.HAND_SHAKE || 615 p.GetSyncState() == common.ESTABLISH { 616 if isConsensus { 617 addrNew = p.ConsLink.GetAddr() 618 } else { 619 addrNew = p.SyncLink.GetAddr() 620 } 621 if strings.Compare(addrNew, addr) == 0 { 622 return true 623 } 624 } 625 } 626 return false 627 } 628 629 //AddPeerSyncAddress add sync addr to peer-addr map 630 func (this *NetServer) AddPeerSyncAddress(addr string, p *peer.Peer) { 631 this.PeerAddrMap.Lock() 632 defer this.PeerAddrMap.Unlock() 633 log.Debug("[p2p]AddPeerSyncAddress", "addr", addr) 634 this.PeerSyncAddress[addr] = p 635 } 636 637 //AddPeerConsAddress add cons addr to peer-addr map 638 func (this *NetServer) AddPeerConsAddress(addr string, p *peer.Peer) { 639 this.PeerAddrMap.Lock() 640 defer this.PeerAddrMap.Unlock() 641 log.Debug("[p2p]AddPeerConsAddress", "addr", addr) 642 this.PeerConsAddress[addr] = p 643 } 644 645 //RemovePeerSyncAddress remove sync addr from peer-addr map 646 func (this *NetServer) RemovePeerSyncAddress(addr string) { 647 this.PeerAddrMap.Lock() 648 defer this.PeerAddrMap.Unlock() 649 if _, ok := this.PeerSyncAddress[addr]; ok { 650 delete(this.PeerSyncAddress, addr) 651 log.Debug("[p2p]delete Sync Address", "addr", addr) 652 } 653 } 654 655 //RemovePeerConsAddress remove cons addr from peer-addr map 656 func (this *NetServer) RemovePeerConsAddress(addr string) { 657 this.PeerAddrMap.Lock() 658 defer this.PeerAddrMap.Unlock() 659 if _, ok := this.PeerConsAddress[addr]; ok { 660 delete(this.PeerConsAddress, addr) 661 log.Debug("[p2p]delete Cons Address", "addr", addr) 662 } 663 } 664 665 //GetPeerSyncAddressCount return length of cons addr from peer-addr map 666 func (this *NetServer) GetPeerSyncAddressCount() (count uint) { 667 this.PeerAddrMap.RLock() 668 defer this.PeerAddrMap.RUnlock() 669 return uint(len(this.PeerSyncAddress)) 670 } 671 672 //AddInConnRecord add in connection to inConnRecord 673 func (this *NetServer) AddInConnRecord(addr string) { 674 this.inConnRecord.Lock() 675 defer this.inConnRecord.Unlock() 676 for _, a := range this.inConnRecord.InConnectingAddrs { 677 if strings.Compare(a, addr) == 0 { 678 return 679 } 680 } 681 this.inConnRecord.InConnectingAddrs = append(this.inConnRecord.InConnectingAddrs, addr) 682 log.Debug("[p2p]add in record", "addr", addr) 683 } 684 685 //IsAddrInInConnRecord return result whether addr is in inConnRecordList 686 func (this *NetServer) IsAddrInInConnRecord(addr string) bool { 687 this.inConnRecord.RLock() 688 defer this.inConnRecord.RUnlock() 689 for _, a := range this.inConnRecord.InConnectingAddrs { 690 if strings.Compare(a, addr) == 0 { 691 return true 692 } 693 } 694 return false 695 } 696 697 //IsIPInInConnRecord return result whether the IP is in inConnRecordList 698 func (this *NetServer) IsIPInInConnRecord(ip string) bool { 699 this.inConnRecord.RLock() 700 defer this.inConnRecord.RUnlock() 701 var ipRecord string 702 for _, addr := range this.inConnRecord.InConnectingAddrs { 703 ipRecord, _ = common.ParseIPAddr(addr) 704 if 0 == strings.Compare(ipRecord, ip) { 705 return true 706 } 707 } 708 return false 709 } 710 711 //RemoveInConnRecord remove in connection from inConnRecordList 712 func (this *NetServer) RemoveFromInConnRecord(addr string) { 713 this.inConnRecord.Lock() 714 defer this.inConnRecord.Unlock() 715 addrs := []string{} 716 for _, a := range this.inConnRecord.InConnectingAddrs { 717 if strings.Compare(a, addr) != 0 { 718 addrs = append(addrs, a) 719 } 720 } 721 log.Debug("[p2p]remove in record", "addr", addr) 722 this.inConnRecord.InConnectingAddrs = addrs 723 } 724 725 //GetInConnRecordLen return length of inConnRecordList 726 func (this *NetServer) GetInConnRecordLen() int { 727 this.inConnRecord.RLock() 728 defer this.inConnRecord.RUnlock() 729 return len(this.inConnRecord.InConnectingAddrs) 730 } 731 732 //GetIpCountInInConnRecord return count of in connections with single ip 733 func (this *NetServer) GetIpCountInInConnRecord(ip string) uint { 734 this.inConnRecord.RLock() 735 defer this.inConnRecord.RUnlock() 736 var count uint 737 var ipRecord string 738 for _, addr := range this.inConnRecord.InConnectingAddrs { 739 ipRecord, _ = common.ParseIPAddr(addr) 740 if 0 == strings.Compare(ipRecord, ip) { 741 count++ 742 } 743 } 744 return count 745 } 746 747 //AddOutConnRecord add out connection to outConnRecord 748 func (this *NetServer) AddOutConnRecord(addr string) { 749 this.outConnRecord.Lock() 750 defer this.outConnRecord.Unlock() 751 for _, a := range this.outConnRecord.OutConnectingAddrs { 752 if strings.Compare(a, addr) == 0 { 753 return 754 } 755 } 756 this.outConnRecord.OutConnectingAddrs = append(this.outConnRecord.OutConnectingAddrs, addr) 757 log.Debug("[p2p]add out record", "addr", addr) 758 } 759 760 //IsAddrInOutConnRecord return result whether addr is in outConnRecord 761 func (this *NetServer) IsAddrInOutConnRecord(addr string) bool { 762 this.outConnRecord.RLock() 763 defer this.outConnRecord.RUnlock() 764 for _, a := range this.outConnRecord.OutConnectingAddrs { 765 if strings.Compare(a, addr) == 0 { 766 return true 767 } 768 } 769 return false 770 } 771 772 //RemoveOutConnRecord remove out connection from outConnRecord 773 func (this *NetServer) RemoveFromOutConnRecord(addr string) { 774 this.outConnRecord.Lock() 775 defer this.outConnRecord.Unlock() 776 addrs := []string{} 777 for _, a := range this.outConnRecord.OutConnectingAddrs { 778 if strings.Compare(a, addr) != 0 { 779 addrs = append(addrs, a) 780 } 781 } 782 log.Debug("[p2p]remove out record", "addr", addr) 783 this.outConnRecord.OutConnectingAddrs = addrs 784 } 785 786 //GetOutConnRecordLen return length of outConnRecord 787 func (this *NetServer) GetOutConnRecordLen() int { 788 this.outConnRecord.RLock() 789 defer this.outConnRecord.RUnlock() 790 return len(this.outConnRecord.OutConnectingAddrs) 791 } 792 793 //AddrValid whether the addr could be connect or accept 794 func (this *NetServer) AddrValid(addr string) bool { 795 if config.GlobalConfig.P2PCfg.ReservedPeersOnly && len(config.GlobalConfig.P2PCfg.ReservedCfg.ReservedPeers) > 0 { 796 for _, ip := range config.GlobalConfig.P2PCfg.ReservedCfg.ReservedPeers { 797 if strings.HasPrefix(addr, ip) { 798 log.Info("[p2p]found reserved peer", "addr", addr) 799 return true 800 } 801 } 802 return false 803 } 804 return true 805 } 806 807 //check own network address 808 func (this *NetServer) IsOwnAddress(addr string) bool { 809 if addr == this.OwnAddress { 810 return true 811 } 812 return false 813 } 814 815 //Set own network address 816 func (this *NetServer) SetOwnAddress(addr string) { 817 if addr != this.OwnAddress { 818 log.Info("[p2p]set own ", "addr", addr) 819 this.OwnAddress = addr 820 } 821 822 } 823 824 func (this *NetServer) SetPrivateKey(nodeKey *ecdsa.PrivateKey, table *discover.Table) { 825 this.nodeKey = nodeKey 826 this.ntable = table 827 //fmt.Println(" ***************** NetServer SetPrivateKey ") 828 //this.ntable.Self().PrintNode() 829 } 830 831 func (this *NetServer) SetBootNodes(nodes []*discover.Node) { 832 this.bootnodes = nodes 833 } 834 835 func (this *NetServer) GetNode() *discover.Node { 836 return this.ntable.Self() 837 } 838 839 func (this *NetServer) SyncHandleSentDisconnectToBootNode(remoteid uint64, bstellar bool) { 840 this.p2pser.SentDisconnectToBootNode(remoteid, bstellar) 841 } 842 843 func (this *NetServer) SyncHandleBANode() bool { 844 return this.p2pser.BANode() 845 } 846 847 // 848 func (this *NetServer) SetupConn(fd net.Conn, dialDest *discover.Node, 849 orgid *comm.Address, bANode bool) (*conn, bool, bool, error) { 850 // Prevent leftover pending conns from entering the handshake. 851 // srv.lock.Lock() 852 // running := srv.running 853 // srv.lock.Unlock() 854 855 c := &conn{fd: fd, transport: newRLPX(fd)} 856 857 // if !running { 858 // c.close(errServerStopped) 859 // return 860 // } 861 // Run the encryption handshake. 862 var remodeOrgID comm.Address 863 var err error 864 bownorg := false 865 bOppsANode := false 866 867 if c.id, remodeOrgID, bOppsANode, err = c.doEncHandshake(this.nodeKey, dialDest, orgid, bANode); err != nil { 868 //fmt.Println("Failed RLPx handshake", "addr", c.fd.RemoteAddr(), "conn", "err", err) 869 c.Close(err) 870 return nil, bownorg, bOppsANode, err 871 } 872 for _, ownorg := range this.PeerGetOrg() { 873 if remodeOrgID == ownorg { 874 bownorg = true 875 //fmt.Println(" ********** the same org ok ok ok ok ok ok ok ok ... ") 876 } 877 } 878 //if bOppsANode { 879 // fmt.Println(" ********** the opps is ANode ok ok ok ok ok ok ok ok ... ") 880 //} 881 882 //fmt.Println(" ******* c.id:",c.id,",dialDest:",dialDest,",remodeOrgID:",remodeOrgID,",bOppsANode:",bOppsANode) 883 // clog := log.New("id", c.id, "addr", c.fd.RemoteAddr(), "conn", c.flags) 884 // For dialed connections, check that the remote public key matches. 885 if dialDest != nil && c.id != dialDest.ID { 886 c.Close(common.DiscUnexpectedIdentity) 887 //fmt.Println("Dialed identity mismatch", "want", c, dialDest.ID) 888 return nil, bownorg, bOppsANode, errors.New("[p2p] c.id != dialDest.ID error") 889 } 890 // if err := srv.checkpoint(c, srv.posthandshake); err != nil { 891 // fmt.Println("Rejected peer before protocol handshake", "err", err) 892 // c.close(err) 893 // return 894 // } 895 // Run the protocol handshake 896 phs, err := c.doProtoHandshake(&protoHandshake{Version: baseProtocolVersion, 897 ID: discover.PubkeyID(&this.nodeKey.PublicKey)}) 898 if err != nil { 899 //fmt.Println("Failed proto handshake", "err", err) 900 c.Close(err) 901 return nil, bownorg, bOppsANode, err 902 } 903 //fmt.Println(" ****** phs.ID:",phs.ID) 904 if phs.ID != c.id { 905 //fmt.Println("Wrong devp2p handshake identity", "err", phs.ID) 906 c.Close(common.DiscUnexpectedIdentity) 907 return nil, bownorg, bOppsANode, errors.New("[p2p] phs.ID != c.id error") 908 } 909 return c, bownorg, bOppsANode, nil 910 }