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