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