peer.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. package whisperv6
  17. import (
  18. "fmt"
  19. "math"
  20. "sync"
  21. "time"
  22. mapset "github.com/deckarep/golang-set"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/log"
  25. "github.com/ethereum/go-ethereum/p2p"
  26. "github.com/ethereum/go-ethereum/rlp"
  27. )
  28. // Peer represents a whisper protocol peer connection.
  29. type Peer struct {
  30. host *Whisper
  31. peer *p2p.Peer
  32. ws p2p.MsgReadWriter
  33. trusted bool
  34. powRequirement float64
  35. bloomMu sync.Mutex
  36. bloomFilter []byte
  37. fullNode bool
  38. known mapset.Set // Messages already known by the peer to avoid wasting bandwidth
  39. quit chan struct{}
  40. wg sync.WaitGroup
  41. }
  42. // newPeer creates a new whisper peer object, but does not run the handshake itself.
  43. func newPeer(host *Whisper, remote *p2p.Peer, rw p2p.MsgReadWriter) *Peer {
  44. return &Peer{
  45. host: host,
  46. peer: remote,
  47. ws: rw,
  48. trusted: false,
  49. powRequirement: 0.0,
  50. known: mapset.NewSet(),
  51. quit: make(chan struct{}),
  52. bloomFilter: MakeFullNodeBloom(),
  53. fullNode: true,
  54. }
  55. }
  56. // start initiates the peer updater, periodically broadcasting the whisper packets
  57. // into the network.
  58. func (peer *Peer) start() {
  59. peer.wg.Add(1)
  60. go peer.update()
  61. log.Trace("start", "peer", peer.ID())
  62. }
  63. // stop terminates the peer updater, stopping message forwarding to it.
  64. func (peer *Peer) stop() {
  65. close(peer.quit)
  66. peer.wg.Wait()
  67. log.Trace("stop", "peer", peer.ID())
  68. }
  69. // handshake sends the protocol initiation status message to the remote peer and
  70. // verifies the remote status too.
  71. func (peer *Peer) handshake() error {
  72. // Send the handshake status message asynchronously
  73. errc := make(chan error, 1)
  74. isLightNode := peer.host.LightClientMode()
  75. isRestrictedLightNodeConnection := peer.host.LightClientModeConnectionRestricted()
  76. peer.wg.Add(1)
  77. go func() {
  78. defer peer.wg.Done()
  79. pow := peer.host.MinPow()
  80. powConverted := math.Float64bits(pow)
  81. bloom := peer.host.BloomFilter()
  82. errc <- p2p.SendItems(peer.ws, statusCode, ProtocolVersion, powConverted, bloom, isLightNode)
  83. }()
  84. // Fetch the remote status packet and verify protocol match
  85. packet, err := peer.ws.ReadMsg()
  86. if err != nil {
  87. return err
  88. }
  89. if packet.Code != statusCode {
  90. return fmt.Errorf("peer [%x] sent packet %x before status packet", peer.ID(), packet.Code)
  91. }
  92. s := rlp.NewStream(packet.Payload, uint64(packet.Size))
  93. _, err = s.List()
  94. if err != nil {
  95. return fmt.Errorf("peer [%x] sent bad status message: %v", peer.ID(), err)
  96. }
  97. peerVersion, err := s.Uint()
  98. if err != nil {
  99. return fmt.Errorf("peer [%x] sent bad status message (unable to decode version): %v", peer.ID(), err)
  100. }
  101. if peerVersion != ProtocolVersion {
  102. return fmt.Errorf("peer [%x]: protocol version mismatch %d != %d", peer.ID(), peerVersion, ProtocolVersion)
  103. }
  104. // only version is mandatory, subsequent parameters are optional
  105. powRaw, err := s.Uint()
  106. if err == nil {
  107. pow := math.Float64frombits(powRaw)
  108. if math.IsInf(pow, 0) || math.IsNaN(pow) || pow < 0.0 {
  109. return fmt.Errorf("peer [%x] sent bad status message: invalid pow", peer.ID())
  110. }
  111. peer.powRequirement = pow
  112. var bloom []byte
  113. err = s.Decode(&bloom)
  114. if err == nil {
  115. sz := len(bloom)
  116. if sz != BloomFilterSize && sz != 0 {
  117. return fmt.Errorf("peer [%x] sent bad status message: wrong bloom filter size %d", peer.ID(), sz)
  118. }
  119. peer.setBloomFilter(bloom)
  120. }
  121. }
  122. isRemotePeerLightNode, _ := s.Bool()
  123. if isRemotePeerLightNode && isLightNode && isRestrictedLightNodeConnection {
  124. return fmt.Errorf("peer [%x] is useless: two light client communication restricted", peer.ID())
  125. }
  126. if err := <-errc; err != nil {
  127. return fmt.Errorf("peer [%x] failed to send status packet: %v", peer.ID(), err)
  128. }
  129. return nil
  130. }
  131. // update executes periodic operations on the peer, including message transmission
  132. // and expiration.
  133. func (peer *Peer) update() {
  134. defer peer.wg.Done()
  135. // Start the tickers for the updates
  136. expire := time.NewTicker(expirationCycle)
  137. defer expire.Stop()
  138. transmit := time.NewTicker(transmissionCycle)
  139. defer transmit.Stop()
  140. // Loop and transmit until termination is requested
  141. for {
  142. select {
  143. case <-expire.C:
  144. peer.expire()
  145. case <-transmit.C:
  146. if err := peer.broadcast(); err != nil {
  147. log.Trace("broadcast failed", "reason", err, "peer", peer.ID())
  148. return
  149. }
  150. case <-peer.quit:
  151. return
  152. }
  153. }
  154. }
  155. // mark marks an envelope known to the peer so that it won't be sent back.
  156. func (peer *Peer) mark(envelope *Envelope) {
  157. peer.known.Add(envelope.Hash())
  158. }
  159. // marked checks if an envelope is already known to the remote peer.
  160. func (peer *Peer) marked(envelope *Envelope) bool {
  161. return peer.known.Contains(envelope.Hash())
  162. }
  163. // expire iterates over all the known envelopes in the host and removes all
  164. // expired (unknown) ones from the known list.
  165. func (peer *Peer) expire() {
  166. unmark := make(map[common.Hash]struct{})
  167. peer.known.Each(func(v interface{}) bool {
  168. if !peer.host.isEnvelopeCached(v.(common.Hash)) {
  169. unmark[v.(common.Hash)] = struct{}{}
  170. }
  171. return true
  172. })
  173. // Dump all known but no longer cached
  174. for hash := range unmark {
  175. peer.known.Remove(hash)
  176. }
  177. }
  178. // broadcast iterates over the collection of envelopes and transmits yet unknown
  179. // ones over the network.
  180. func (peer *Peer) broadcast() error {
  181. envelopes := peer.host.Envelopes()
  182. bundle := make([]*Envelope, 0, len(envelopes))
  183. for _, envelope := range envelopes {
  184. if !peer.marked(envelope) && envelope.PoW() >= peer.powRequirement && peer.bloomMatch(envelope) {
  185. bundle = append(bundle, envelope)
  186. }
  187. }
  188. if len(bundle) > 0 {
  189. // transmit the batch of envelopes
  190. if err := p2p.Send(peer.ws, messagesCode, bundle); err != nil {
  191. return err
  192. }
  193. // mark envelopes only if they were successfully sent
  194. for _, e := range bundle {
  195. peer.mark(e)
  196. }
  197. log.Trace("broadcast", "num. messages", len(bundle))
  198. }
  199. return nil
  200. }
  201. // ID returns a peer's id
  202. func (peer *Peer) ID() []byte {
  203. id := peer.peer.ID()
  204. return id[:]
  205. }
  206. func (peer *Peer) notifyAboutPowRequirementChange(pow float64) error {
  207. i := math.Float64bits(pow)
  208. return p2p.Send(peer.ws, powRequirementCode, i)
  209. }
  210. func (peer *Peer) notifyAboutBloomFilterChange(bloom []byte) error {
  211. return p2p.Send(peer.ws, bloomFilterExCode, bloom)
  212. }
  213. func (peer *Peer) bloomMatch(env *Envelope) bool {
  214. peer.bloomMu.Lock()
  215. defer peer.bloomMu.Unlock()
  216. return peer.fullNode || BloomFilterMatch(peer.bloomFilter, env.Bloom())
  217. }
  218. func (peer *Peer) setBloomFilter(bloom []byte) {
  219. peer.bloomMu.Lock()
  220. defer peer.bloomMu.Unlock()
  221. peer.bloomFilter = bloom
  222. peer.fullNode = isFullNode(bloom)
  223. if peer.fullNode && peer.bloomFilter == nil {
  224. peer.bloomFilter = MakeFullNodeBloom()
  225. }
  226. }
  227. func MakeFullNodeBloom() []byte {
  228. bloom := make([]byte, BloomFilterSize)
  229. for i := 0; i < BloomFilterSize; i++ {
  230. bloom[i] = 0xFF
  231. }
  232. return bloom
  233. }