github.com/beyonderyue/gochain@v2.2.26+incompatible/whisper/whisperv5/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 whisperv5 18 19 import ( 20 "fmt" 21 "sync" 22 "time" 23 24 "github.com/gochain-io/gochain/common" 25 "github.com/gochain-io/gochain/log" 26 "github.com/gochain-io/gochain/p2p" 27 "github.com/gochain-io/gochain/rlp" 28 ) 29 30 // peer represents a whisper protocol peer connection. 31 type Peer struct { 32 host *Whisper 33 peer *p2p.Peer 34 ws p2p.MsgReadWriter 35 trusted bool 36 37 knownMu sync.RWMutex 38 known map[common.Hash]struct{} // Messages already known by the peer to avoid wasting bandwidth 39 40 quit chan struct{} 41 } 42 43 // newPeer creates a new whisper peer object, but does not run the handshake itself. 44 func newPeer(host *Whisper, remote *p2p.Peer, rw p2p.MsgReadWriter) *Peer { 45 return &Peer{ 46 host: host, 47 peer: remote, 48 ws: rw, 49 trusted: false, 50 known: make(map[common.Hash]struct{}), 51 quit: make(chan struct{}), 52 } 53 } 54 55 // start initiates the peer updater, periodically broadcasting the whisper packets 56 // into the network. 57 func (p *Peer) start() { 58 go p.update() 59 log.Trace("start", "peer", p.ID()) 60 } 61 62 // stop terminates the peer updater, stopping message forwarding to it. 63 func (p *Peer) stop() { 64 close(p.quit) 65 log.Trace("stop", "peer", p.ID()) 66 } 67 68 // handshake sends the protocol initiation status message to the remote peer and 69 // verifies the remote status too. 70 func (p *Peer) handshake() error { 71 // Send the handshake status message asynchronously 72 errc := make(chan error, 1) 73 go func() { 74 errc <- p2p.Send(p.ws, statusCode, ProtocolVersion) 75 }() 76 // Fetch the remote status packet and verify protocol match 77 packet, err := p.ws.ReadMsg() 78 if err != nil { 79 return err 80 } 81 if packet.Code != statusCode { 82 return fmt.Errorf("peer [%x] sent packet %x before status packet", p.ID(), packet.Code) 83 } 84 s := rlp.NewStream(packet.Payload, uint64(packet.Size)) 85 peerVersion, err := s.Uint() 86 if err != nil { 87 return fmt.Errorf("peer [%x] sent bad status message: %v", p.ID(), err) 88 } 89 if peerVersion != ProtocolVersion { 90 return fmt.Errorf("peer [%x]: protocol version mismatch %d != %d", p.ID(), peerVersion, ProtocolVersion) 91 } 92 // Wait until out own status is consumed too 93 if err := <-errc; err != nil { 94 return fmt.Errorf("peer [%x] failed to send status packet: %v", p.ID(), err) 95 } 96 return nil 97 } 98 99 // update executes periodic operations on the peer, including message transmission 100 // and expiration. 101 func (p *Peer) update() { 102 // Start the tickers for the updates 103 expire := time.NewTicker(expirationCycle) 104 transmit := time.NewTicker(transmissionCycle) 105 106 // Loop and transmit until termination is requested 107 for { 108 select { 109 case <-expire.C: 110 p.expire() 111 112 case <-transmit.C: 113 if err := p.broadcast(); err != nil { 114 log.Trace("broadcast failed", "reason", err, "peer", p.ID()) 115 return 116 } 117 118 case <-p.quit: 119 return 120 } 121 } 122 } 123 124 // mark marks an envelope known to the peer so that it won't be sent back. 125 func (peer *Peer) mark(envelope *Envelope) { 126 h := envelope.Hash() 127 peer.knownMu.Lock() 128 peer.known[h] = struct{}{} 129 peer.knownMu.Unlock() 130 } 131 132 // marked checks if an envelope is already known to the remote peer. 133 func (peer *Peer) marked(envelope *Envelope) bool { 134 h := envelope.Hash() 135 peer.knownMu.RLock() 136 _, ok := peer.known[h] 137 peer.knownMu.RUnlock() 138 return ok 139 } 140 141 // expire iterates over all the known envelopes in the host and removes all 142 // expired (unknown) ones from the known list. 143 func (peer *Peer) expire() { 144 unmark := make(map[common.Hash]struct{}) 145 peer.knownMu.Lock() 146 defer peer.knownMu.Unlock() 147 for h := range peer.known { 148 if !peer.host.isEnvelopeCached(h) { 149 unmark[h] = struct{}{} 150 } 151 } 152 // Dump all known but no longer cached 153 for hash := range unmark { 154 delete(peer.known, hash) 155 } 156 } 157 158 // broadcast iterates over the collection of envelopes and transmits yet unknown 159 // ones over the network. 160 func (p *Peer) broadcast() error { 161 var cnt int 162 envelopes := p.host.Envelopes() 163 for _, envelope := range envelopes { 164 if !p.marked(envelope) { 165 err := p2p.Send(p.ws, messagesCode, envelope) 166 if err != nil { 167 return err 168 } else { 169 p.mark(envelope) 170 cnt++ 171 } 172 } 173 } 174 if cnt > 0 { 175 log.Trace("broadcast", "num. messages", cnt) 176 } 177 return nil 178 } 179 180 func (p *Peer) ID() []byte { 181 id := p.peer.ID() 182 return id[:] 183 }