github.com/theQRL/go-zond@v0.1.1/p2p/enode/iter.go (about)

     1  // Copyright 2019 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 enode
    18  
    19  import (
    20  	"sync"
    21  	"time"
    22  )
    23  
    24  // Iterator represents a sequence of nodes. The Next method moves to the next node in the
    25  // sequence. It returns false when the sequence has ended or the iterator is closed. Close
    26  // may be called concurrently with Next and Node, and interrupts Next if it is blocked.
    27  type Iterator interface {
    28  	Next() bool  // moves to next node
    29  	Node() *Node // returns current node
    30  	Close()      // ends the iterator
    31  }
    32  
    33  // ReadNodes reads at most n nodes from the given iterator. The return value contains no
    34  // duplicates and no nil values. To prevent looping indefinitely for small repeating node
    35  // sequences, this function calls Next at most n times.
    36  func ReadNodes(it Iterator, n int) []*Node {
    37  	seen := make(map[ID]*Node, n)
    38  	for i := 0; i < n && it.Next(); i++ {
    39  		// Remove duplicates, keeping the node with higher seq.
    40  		node := it.Node()
    41  		prevNode, ok := seen[node.ID()]
    42  		if ok && prevNode.Seq() > node.Seq() {
    43  			continue
    44  		}
    45  		seen[node.ID()] = node
    46  	}
    47  	result := make([]*Node, 0, len(seen))
    48  	for _, node := range seen {
    49  		result = append(result, node)
    50  	}
    51  	return result
    52  }
    53  
    54  // IterNodes makes an iterator which runs through the given nodes once.
    55  func IterNodes(nodes []*Node) Iterator {
    56  	return &sliceIter{nodes: nodes, index: -1}
    57  }
    58  
    59  // CycleNodes makes an iterator which cycles through the given nodes indefinitely.
    60  func CycleNodes(nodes []*Node) Iterator {
    61  	return &sliceIter{nodes: nodes, index: -1, cycle: true}
    62  }
    63  
    64  type sliceIter struct {
    65  	mu    sync.Mutex
    66  	nodes []*Node
    67  	index int
    68  	cycle bool
    69  }
    70  
    71  func (it *sliceIter) Next() bool {
    72  	it.mu.Lock()
    73  	defer it.mu.Unlock()
    74  
    75  	if len(it.nodes) == 0 {
    76  		return false
    77  	}
    78  	it.index++
    79  	if it.index == len(it.nodes) {
    80  		if it.cycle {
    81  			it.index = 0
    82  		} else {
    83  			it.nodes = nil
    84  			return false
    85  		}
    86  	}
    87  	return true
    88  }
    89  
    90  func (it *sliceIter) Node() *Node {
    91  	it.mu.Lock()
    92  	defer it.mu.Unlock()
    93  	if len(it.nodes) == 0 {
    94  		return nil
    95  	}
    96  	return it.nodes[it.index]
    97  }
    98  
    99  func (it *sliceIter) Close() {
   100  	it.mu.Lock()
   101  	defer it.mu.Unlock()
   102  
   103  	it.nodes = nil
   104  }
   105  
   106  // Filter wraps an iterator such that Next only returns nodes for which
   107  // the 'check' function returns true.
   108  func Filter(it Iterator, check func(*Node) bool) Iterator {
   109  	return &filterIter{it, check}
   110  }
   111  
   112  type filterIter struct {
   113  	Iterator
   114  	check func(*Node) bool
   115  }
   116  
   117  func (f *filterIter) Next() bool {
   118  	for f.Iterator.Next() {
   119  		if f.check(f.Node()) {
   120  			return true
   121  		}
   122  	}
   123  	return false
   124  }
   125  
   126  // FairMix aggregates multiple node iterators. The mixer itself is an iterator which ends
   127  // only when Close is called. Source iterators added via AddSource are removed from the
   128  // mix when they end.
   129  //
   130  // The distribution of nodes returned by Next is approximately fair, i.e. FairMix
   131  // attempts to draw from all sources equally often. However, if a certain source is slow
   132  // and doesn't return a node within the configured timeout, a node from any other source
   133  // will be returned.
   134  //
   135  // It's safe to call AddSource and Close concurrently with Next.
   136  type FairMix struct {
   137  	wg      sync.WaitGroup
   138  	fromAny chan *Node
   139  	timeout time.Duration
   140  	cur     *Node
   141  
   142  	mu      sync.Mutex
   143  	closed  chan struct{}
   144  	sources []*mixSource
   145  	last    int
   146  }
   147  
   148  type mixSource struct {
   149  	it      Iterator
   150  	next    chan *Node
   151  	timeout time.Duration
   152  }
   153  
   154  // NewFairMix creates a mixer.
   155  //
   156  // The timeout specifies how long the mixer will wait for the next fairly-chosen source
   157  // before giving up and taking a node from any other source. A good way to set the timeout
   158  // is deciding how long you'd want to wait for a node on average. Passing a negative
   159  // timeout makes the mixer completely fair.
   160  func NewFairMix(timeout time.Duration) *FairMix {
   161  	m := &FairMix{
   162  		fromAny: make(chan *Node),
   163  		closed:  make(chan struct{}),
   164  		timeout: timeout,
   165  	}
   166  	return m
   167  }
   168  
   169  // AddSource adds a source of nodes.
   170  func (m *FairMix) AddSource(it Iterator) {
   171  	m.mu.Lock()
   172  	defer m.mu.Unlock()
   173  
   174  	if m.closed == nil {
   175  		return
   176  	}
   177  	m.wg.Add(1)
   178  	source := &mixSource{it, make(chan *Node), m.timeout}
   179  	m.sources = append(m.sources, source)
   180  	go m.runSource(m.closed, source)
   181  }
   182  
   183  // Close shuts down the mixer and all current sources.
   184  // Calling this is required to release resources associated with the mixer.
   185  func (m *FairMix) Close() {
   186  	m.mu.Lock()
   187  	defer m.mu.Unlock()
   188  
   189  	if m.closed == nil {
   190  		return
   191  	}
   192  	for _, s := range m.sources {
   193  		s.it.Close()
   194  	}
   195  	close(m.closed)
   196  	m.wg.Wait()
   197  	close(m.fromAny)
   198  	m.sources = nil
   199  	m.closed = nil
   200  }
   201  
   202  // Next returns a node from a random source.
   203  func (m *FairMix) Next() bool {
   204  	m.cur = nil
   205  
   206  	for {
   207  		source := m.pickSource()
   208  		if source == nil {
   209  			return m.nextFromAny()
   210  		}
   211  
   212  		var timeout <-chan time.Time
   213  		if source.timeout >= 0 {
   214  			timer := time.NewTimer(source.timeout)
   215  			timeout = timer.C
   216  			defer timer.Stop()
   217  		}
   218  
   219  		select {
   220  		case n, ok := <-source.next:
   221  			if ok {
   222  				// Here, the timeout is reset to the configured value
   223  				// because the source delivered a node.
   224  				source.timeout = m.timeout
   225  				m.cur = n
   226  				return true
   227  			}
   228  			// This source has ended.
   229  			m.deleteSource(source)
   230  		case <-timeout:
   231  			// The selected source did not deliver a node within the timeout, so the
   232  			// timeout duration is halved for next time. This is supposed to improve
   233  			// latency with stuck sources.
   234  			source.timeout /= 2
   235  			return m.nextFromAny()
   236  		}
   237  	}
   238  }
   239  
   240  // Node returns the current node.
   241  func (m *FairMix) Node() *Node {
   242  	return m.cur
   243  }
   244  
   245  // nextFromAny is used when there are no sources or when the 'fair' choice
   246  // doesn't turn up a node quickly enough.
   247  func (m *FairMix) nextFromAny() bool {
   248  	n, ok := <-m.fromAny
   249  	if ok {
   250  		m.cur = n
   251  	}
   252  	return ok
   253  }
   254  
   255  // pickSource chooses the next source to read from, cycling through them in order.
   256  func (m *FairMix) pickSource() *mixSource {
   257  	m.mu.Lock()
   258  	defer m.mu.Unlock()
   259  
   260  	if len(m.sources) == 0 {
   261  		return nil
   262  	}
   263  	m.last = (m.last + 1) % len(m.sources)
   264  	return m.sources[m.last]
   265  }
   266  
   267  // deleteSource deletes a source.
   268  func (m *FairMix) deleteSource(s *mixSource) {
   269  	m.mu.Lock()
   270  	defer m.mu.Unlock()
   271  
   272  	for i := range m.sources {
   273  		if m.sources[i] == s {
   274  			copy(m.sources[i:], m.sources[i+1:])
   275  			m.sources[len(m.sources)-1] = nil
   276  			m.sources = m.sources[:len(m.sources)-1]
   277  			break
   278  		}
   279  	}
   280  }
   281  
   282  // runSource reads a single source in a loop.
   283  func (m *FairMix) runSource(closed chan struct{}, s *mixSource) {
   284  	defer m.wg.Done()
   285  	defer close(s.next)
   286  	for s.it.Next() {
   287  		n := s.it.Node()
   288  		select {
   289  		case s.next <- n:
   290  		case m.fromAny <- n:
   291  		case <-closed:
   292  			return
   293  		}
   294  	}
   295  }