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