github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/network/p2p/testing/peerpool.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package testing
    18  
    19  import (
    20  	"fmt"
    21  	"sync"
    22  
    23  	"github.com/neatlab/neatio/chain/log"
    24  	"github.com/neatlab/neatio/network/p2p/discover"
    25  )
    26  
    27  type TestPeer interface {
    28  	ID() discover.NodeID
    29  	Drop(error)
    30  }
    31  
    32  // TestPeerPool is an example peerPool to demonstrate registration of peer connections
    33  type TestPeerPool struct {
    34  	lock  sync.Mutex
    35  	peers map[discover.NodeID]TestPeer
    36  }
    37  
    38  func NewTestPeerPool() *TestPeerPool {
    39  	return &TestPeerPool{peers: make(map[discover.NodeID]TestPeer)}
    40  }
    41  
    42  func (self *TestPeerPool) Add(p TestPeer) {
    43  	self.lock.Lock()
    44  	defer self.lock.Unlock()
    45  	log.Trace(fmt.Sprintf("pp add peer  %v", p.ID()))
    46  	self.peers[p.ID()] = p
    47  
    48  }
    49  
    50  func (self *TestPeerPool) Remove(p TestPeer) {
    51  	self.lock.Lock()
    52  	defer self.lock.Unlock()
    53  	delete(self.peers, p.ID())
    54  }
    55  
    56  func (self *TestPeerPool) Has(id discover.NodeID) bool {
    57  	self.lock.Lock()
    58  	defer self.lock.Unlock()
    59  	_, ok := self.peers[id]
    60  	return ok
    61  }
    62  
    63  func (self *TestPeerPool) Get(id discover.NodeID) TestPeer {
    64  	self.lock.Lock()
    65  	defer self.lock.Unlock()
    66  	return self.peers[id]
    67  }