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