github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/p2p/testing/peerpool.go (about)

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