peer.go 6.9 KB

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