github.com/bcskill/bcschain/v3@v3.4.9-beta2/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/bcskill/bcschain/v3/common"
    30  	"github.com/bcskill/bcschain/v3/log"
    31  	"github.com/bcskill/bcschain/v3/p2p"
    32  	"github.com/bcskill/bcschain/v3/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  	// Send the handshake status message asynchronously
    85  	errc := make(chan error, 1)
    86  	go func() {
    87  		pow := peer.host.MinPow()
    88  		powConverted := math.Float64bits(pow)
    89  		bloom := peer.host.BloomFilter()
    90  		errc <- p2p.SendItems(peer.ws, statusCode, ProtocolVersion, powConverted, bloom)
    91  	}()
    92  
    93  	// Fetch the remote status packet and verify protocol match
    94  	packet, err := peer.ws.ReadMsg()
    95  	if err != nil {
    96  		return err
    97  	}
    98  	if packet.Code != statusCode {
    99  		return fmt.Errorf("peer [%x] sent packet %x before status packet", peer.ID(), packet.Code)
   100  	}
   101  	s := rlp.NewStream(packet.Payload, uint64(packet.Size))
   102  	defer rlp.Discard(s)
   103  	_, err = s.List()
   104  	if err != nil {
   105  		return fmt.Errorf("peer [%x] sent bad status message: %v", peer.ID(), err)
   106  	}
   107  	peerVersion, err := s.Uint()
   108  	if err != nil {
   109  		return fmt.Errorf("peer [%x] sent bad status message (unable to decode version): %v", peer.ID(), err)
   110  	}
   111  	if peerVersion != ProtocolVersion {
   112  		return fmt.Errorf("peer [%x]: protocol version mismatch %d != %d", peer.ID(), peerVersion, ProtocolVersion)
   113  	}
   114  
   115  	// only version is mandatory, subsequent parameters are optional
   116  	powRaw, err := s.Uint()
   117  	if err == nil {
   118  		pow := math.Float64frombits(powRaw)
   119  		if math.IsInf(pow, 0) || math.IsNaN(pow) || pow < 0.0 {
   120  			return fmt.Errorf("peer [%x] sent bad status message: invalid pow", peer.ID())
   121  		}
   122  		peer.mu.Lock()
   123  		peer.powRequirement = pow
   124  		peer.mu.Unlock()
   125  
   126  		var bloom []byte
   127  		err = s.Decode(&bloom)
   128  		if err == nil {
   129  			sz := len(bloom)
   130  			if sz != bloomFilterSize && sz != 0 {
   131  				return fmt.Errorf("peer [%x] sent bad status message: wrong bloom filter size %d", peer.ID(), sz)
   132  			}
   133  			peer.setBloomFilter(bloom)
   134  		}
   135  	}
   136  
   137  	if err := <-errc; err != nil {
   138  		return fmt.Errorf("peer [%x] failed to send status packet: %v", peer.ID(), err)
   139  	}
   140  	return nil
   141  }
   142  
   143  // update executes periodic operations on the peer, including message transmission
   144  // and expiration.
   145  func (peer *Peer) update() {
   146  	// Start the tickers for the updates
   147  	expire := time.NewTicker(expirationCycle)
   148  	transmit := time.NewTicker(transmissionCycle)
   149  
   150  	// Loop and transmit until termination is requested
   151  	for {
   152  		select {
   153  		case <-expire.C:
   154  			peer.expire()
   155  
   156  		case <-transmit.C:
   157  			ctx, span := trace.StartSpan(context.Background(), "Peer.update.transmit")
   158  			if err := peer.broadcast(ctx); err != nil {
   159  				log.Trace("broadcast failed", "reason", err, "peer", peer.ID())
   160  				span.SetStatus(trace.Status{
   161  					Code:    trace.StatusCodeInternal,
   162  					Message: err.Error(),
   163  				})
   164  				span.End()
   165  				return
   166  			}
   167  			span.End()
   168  
   169  		case <-peer.quit:
   170  			return
   171  		}
   172  	}
   173  }
   174  
   175  // mark marks an envelope known to the peer so that it won't be sent back.
   176  func (peer *Peer) mark(envelope *Envelope) {
   177  	h := envelope.Hash()
   178  	peer.knownMu.Lock()
   179  	peer.known[h] = struct{}{}
   180  	peer.knownMu.Unlock()
   181  }
   182  
   183  // marked checks if an envelope is already known to the remote peer.
   184  func (peer *Peer) marked(envelope *Envelope) bool {
   185  	h := envelope.Hash()
   186  	peer.knownMu.RLock()
   187  	_, ok := peer.known[h]
   188  	peer.knownMu.RUnlock()
   189  	return ok
   190  }
   191  
   192  // expire iterates over all the known envelopes in the host and removes all
   193  // expired (unknown) ones from the known list.
   194  func (peer *Peer) expire() {
   195  	unmark := make(map[common.Hash]struct{})
   196  	peer.knownMu.Lock()
   197  	defer peer.knownMu.Unlock()
   198  	for h := range peer.known {
   199  		if !peer.host.isEnvelopeCached(h) {
   200  			unmark[h] = struct{}{}
   201  		}
   202  	}
   203  	// Dump all known but no longer cached
   204  	for hash := range unmark {
   205  		delete(peer.known, hash)
   206  	}
   207  }
   208  
   209  // broadcast iterates over the collection of envelopes and transmits yet unknown
   210  // ones over the network.
   211  func (peer *Peer) broadcast(ctx context.Context) error {
   212  	envelopes := peer.host.Envelopes()
   213  	bundle := make([]*Envelope, 0, len(envelopes))
   214  	for _, envelope := range envelopes {
   215  		peer.mu.RLock()
   216  		pow := peer.powRequirement
   217  		peer.mu.RUnlock()
   218  		if !peer.marked(envelope) && envelope.PoW() >= pow && peer.bloomMatch(envelope) {
   219  			bundle = append(bundle, envelope)
   220  		}
   221  	}
   222  
   223  	if len(bundle) > 0 {
   224  		// transmit the batch of envelopes
   225  		if err := p2p.Send(peer.ws, messagesCode, bundle); err != nil {
   226  			return err
   227  		}
   228  
   229  		// mark envelopes only if they were successfully sent
   230  		for _, e := range bundle {
   231  			peer.mark(e)
   232  		}
   233  
   234  		log.Trace("broadcast", "num. messages", len(bundle))
   235  	}
   236  	return nil
   237  }
   238  
   239  // ID returns a peer's id
   240  func (peer *Peer) ID() []byte {
   241  	id := peer.peer.ID()
   242  	return id[:]
   243  }
   244  
   245  func (peer *Peer) notifyAboutPowRequirementChange(ctx context.Context, pow float64) error {
   246  	i := math.Float64bits(pow)
   247  	return p2p.Send(peer.ws, powRequirementCode, i)
   248  }
   249  
   250  func (peer *Peer) notifyAboutBloomFilterChange(ctx context.Context, bloom []byte) error {
   251  	return p2p.Send(peer.ws, bloomFilterExCode, bloom)
   252  }
   253  
   254  func (peer *Peer) bloomMatch(env *Envelope) bool {
   255  	peer.mu.RLock()
   256  	bf := peer.bloomFilter
   257  	peer.mu.RUnlock()
   258  	return peer.fullNode || bloomFilterMatch(bf, env.Bloom())
   259  }
   260  
   261  func (peer *Peer) setBloomFilter(bloom []byte) {
   262  	peer.mu.Lock()
   263  	defer peer.mu.Unlock()
   264  	peer.bloomFilter = bloom
   265  	peer.fullNode = isFullNode(bloom)
   266  	if peer.fullNode && peer.bloomFilter == nil {
   267  		peer.bloomFilter = makeFullNodeBloom()
   268  	}
   269  }
   270  
   271  func makeFullNodeBloom() []byte {
   272  	bloom := make([]byte, bloomFilterSize)
   273  	for i := 0; i < bloomFilterSize; i++ {
   274  		bloom[i] = 0xFF
   275  	}
   276  	return bloom
   277  }