github.com/needkane/go-ethereum@v1.7.4-0.20180131070256-c212876ea2b7/whisper/whisperv6/peer.go (about)

     1  // Copyright 2016 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 whisperv6
    18  
    19  import (
    20  	"fmt"
    21  	"math"
    22  	"time"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/log"
    26  	"github.com/ethereum/go-ethereum/p2p"
    27  	"github.com/ethereum/go-ethereum/rlp"
    28  	set "gopkg.in/fatih/set.v0"
    29  )
    30  
    31  // Peer represents a whisper protocol peer connection.
    32  type Peer struct {
    33  	host *Whisper
    34  	peer *p2p.Peer
    35  	ws   p2p.MsgReadWriter
    36  
    37  	trusted        bool
    38  	powRequirement float64
    39  	bloomFilter    []byte // may contain nil in case of full node
    40  
    41  	known *set.Set // Messages already known by the peer to avoid wasting bandwidth
    42  
    43  	quit chan struct{}
    44  }
    45  
    46  // newPeer creates a new whisper peer object, but does not run the handshake itself.
    47  func newPeer(host *Whisper, remote *p2p.Peer, rw p2p.MsgReadWriter) *Peer {
    48  	return &Peer{
    49  		host:           host,
    50  		peer:           remote,
    51  		ws:             rw,
    52  		trusted:        false,
    53  		powRequirement: 0.0,
    54  		known:          set.New(),
    55  		quit:           make(chan struct{}),
    56  	}
    57  }
    58  
    59  // start initiates the peer updater, periodically broadcasting the whisper packets
    60  // into the network.
    61  func (peer *Peer) start() {
    62  	go peer.update()
    63  	log.Trace("start", "peer", peer.ID())
    64  }
    65  
    66  // stop terminates the peer updater, stopping message forwarding to it.
    67  func (peer *Peer) stop() {
    68  	close(peer.quit)
    69  	log.Trace("stop", "peer", peer.ID())
    70  }
    71  
    72  // handshake sends the protocol initiation status message to the remote peer and
    73  // verifies the remote status too.
    74  func (peer *Peer) handshake() error {
    75  	// Send the handshake status message asynchronously
    76  	errc := make(chan error, 1)
    77  	go func() {
    78  		pow := peer.host.MinPow()
    79  		powConverted := math.Float64bits(pow)
    80  		bloom := peer.host.BloomFilter()
    81  		errc <- p2p.SendItems(peer.ws, statusCode, ProtocolVersion, powConverted, bloom)
    82  	}()
    83  
    84  	// Fetch the remote status packet and verify protocol match
    85  	packet, err := peer.ws.ReadMsg()
    86  	if err != nil {
    87  		return err
    88  	}
    89  	if packet.Code != statusCode {
    90  		return fmt.Errorf("peer [%x] sent packet %x before status packet", peer.ID(), packet.Code)
    91  	}
    92  	s := rlp.NewStream(packet.Payload, uint64(packet.Size))
    93  	_, err = s.List()
    94  	if err != nil {
    95  		return fmt.Errorf("peer [%x] sent bad status message: %v", peer.ID(), err)
    96  	}
    97  	peerVersion, err := s.Uint()
    98  	if err != nil {
    99  		return fmt.Errorf("peer [%x] sent bad status message (unable to decode version): %v", peer.ID(), err)
   100  	}
   101  	if peerVersion != ProtocolVersion {
   102  		return fmt.Errorf("peer [%x]: protocol version mismatch %d != %d", peer.ID(), peerVersion, ProtocolVersion)
   103  	}
   104  
   105  	// only version is mandatory, subsequent parameters are optional
   106  	powRaw, err := s.Uint()
   107  	if err == nil {
   108  		pow := math.Float64frombits(powRaw)
   109  		if math.IsInf(pow, 0) || math.IsNaN(pow) || pow < 0.0 {
   110  			return fmt.Errorf("peer [%x] sent bad status message: invalid pow", peer.ID())
   111  		}
   112  		peer.powRequirement = pow
   113  
   114  		var bloom []byte
   115  		err = s.Decode(&bloom)
   116  		if err == nil {
   117  			sz := len(bloom)
   118  			if sz != bloomFilterSize && sz != 0 {
   119  				return fmt.Errorf("peer [%x] sent bad status message: wrong bloom filter size %d", peer.ID(), sz)
   120  			}
   121  			if isFullNode(bloom) {
   122  				peer.bloomFilter = nil
   123  			} else {
   124  				peer.bloomFilter = bloom
   125  			}
   126  		}
   127  	}
   128  
   129  	if err := <-errc; err != nil {
   130  		return fmt.Errorf("peer [%x] failed to send status packet: %v", peer.ID(), err)
   131  	}
   132  	return nil
   133  }
   134  
   135  // update executes periodic operations on the peer, including message transmission
   136  // and expiration.
   137  func (peer *Peer) update() {
   138  	// Start the tickers for the updates
   139  	expire := time.NewTicker(expirationCycle)
   140  	transmit := time.NewTicker(transmissionCycle)
   141  
   142  	// Loop and transmit until termination is requested
   143  	for {
   144  		select {
   145  		case <-expire.C:
   146  			peer.expire()
   147  
   148  		case <-transmit.C:
   149  			if err := peer.broadcast(); err != nil {
   150  				log.Trace("broadcast failed", "reason", err, "peer", peer.ID())
   151  				return
   152  			}
   153  
   154  		case <-peer.quit:
   155  			return
   156  		}
   157  	}
   158  }
   159  
   160  // mark marks an envelope known to the peer so that it won't be sent back.
   161  func (peer *Peer) mark(envelope *Envelope) {
   162  	peer.known.Add(envelope.Hash())
   163  }
   164  
   165  // marked checks if an envelope is already known to the remote peer.
   166  func (peer *Peer) marked(envelope *Envelope) bool {
   167  	return peer.known.Has(envelope.Hash())
   168  }
   169  
   170  // expire iterates over all the known envelopes in the host and removes all
   171  // expired (unknown) ones from the known list.
   172  func (peer *Peer) expire() {
   173  	unmark := make(map[common.Hash]struct{})
   174  	peer.known.Each(func(v interface{}) bool {
   175  		if !peer.host.isEnvelopeCached(v.(common.Hash)) {
   176  			unmark[v.(common.Hash)] = struct{}{}
   177  		}
   178  		return true
   179  	})
   180  	// Dump all known but no longer cached
   181  	for hash := range unmark {
   182  		peer.known.Remove(hash)
   183  	}
   184  }
   185  
   186  // broadcast iterates over the collection of envelopes and transmits yet unknown
   187  // ones over the network.
   188  func (peer *Peer) broadcast() error {
   189  	envelopes := peer.host.Envelopes()
   190  	bundle := make([]*Envelope, 0, len(envelopes))
   191  	for _, envelope := range envelopes {
   192  		if !peer.marked(envelope) && envelope.PoW() >= peer.powRequirement && peer.bloomMatch(envelope) {
   193  			bundle = append(bundle, envelope)
   194  		}
   195  	}
   196  
   197  	if len(bundle) > 0 {
   198  		// transmit the batch of envelopes
   199  		if err := p2p.Send(peer.ws, messagesCode, bundle); err != nil {
   200  			return err
   201  		}
   202  
   203  		// mark envelopes only if they were successfully sent
   204  		for _, e := range bundle {
   205  			peer.mark(e)
   206  		}
   207  
   208  		log.Trace("broadcast", "num. messages", len(bundle))
   209  	}
   210  	return nil
   211  }
   212  
   213  // ID returns a peer's id
   214  func (peer *Peer) ID() []byte {
   215  	id := peer.peer.ID()
   216  	return id[:]
   217  }
   218  
   219  func (peer *Peer) notifyAboutPowRequirementChange(pow float64) error {
   220  	i := math.Float64bits(pow)
   221  	return p2p.Send(peer.ws, powRequirementCode, i)
   222  }
   223  
   224  func (peer *Peer) notifyAboutBloomFilterChange(bloom []byte) error {
   225  	return p2p.Send(peer.ws, bloomFilterExCode, bloom)
   226  }
   227  
   228  func (peer *Peer) bloomMatch(env *Envelope) bool {
   229  	if peer.bloomFilter == nil {
   230  		// no filter - full node, accepts all envelops
   231  		return true
   232  	}
   233  
   234  	return bloomFilterMatch(peer.bloomFilter, env.Bloom())
   235  }