github.com/aquanetwork/aquachain@v1.7.8/opt/whisper/whisperv6/peer.go (about)

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