github.com/goldbock/go-ethereum@v1.9.7/p2p/testing/peerpool.go (about)

     1  // Copyright 2018 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/ethereum/go-ethereum/log"
    24  	"github.com/ethereum/go-ethereum/p2p/enode"
    25  )
    26  
    27  type TestPeer interface {
    28  	ID() enode.ID
    29  	Drop()
    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[enode.ID]TestPeer
    36  }
    37  
    38  func NewTestPeerPool() *TestPeerPool {
    39  	return &TestPeerPool{peers: make(map[enode.ID]TestPeer)}
    40  }
    41  
    42  func (p *TestPeerPool) Add(peer TestPeer) {
    43  	p.lock.Lock()
    44  	defer p.lock.Unlock()
    45  	log.Trace(fmt.Sprintf("pp add peer  %v", peer.ID()))
    46  	p.peers[peer.ID()] = peer
    47  
    48  }
    49  
    50  func (p *TestPeerPool) Remove(peer TestPeer) {
    51  	p.lock.Lock()
    52  	defer p.lock.Unlock()
    53  	delete(p.peers, peer.ID())
    54  }
    55  
    56  func (p *TestPeerPool) Has(id enode.ID) bool {
    57  	p.lock.Lock()
    58  	defer p.lock.Unlock()
    59  	_, ok := p.peers[id]
    60  	return ok
    61  }
    62  
    63  func (p *TestPeerPool) Get(id enode.ID) TestPeer {
    64  	p.lock.Lock()
    65  	defer p.lock.Unlock()
    66  	return p.peers[id]
    67  }