github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/whisper/whisperv6/peer.go (about)

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