messages.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. // Copyright 2018 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 stream
  17. import (
  18. "errors"
  19. "fmt"
  20. "sync"
  21. "time"
  22. "github.com/ethereum/go-ethereum/metrics"
  23. "github.com/ethereum/go-ethereum/swarm/log"
  24. bv "github.com/ethereum/go-ethereum/swarm/network/bitvector"
  25. "github.com/ethereum/go-ethereum/swarm/storage"
  26. )
  27. // Stream defines a unique stream identifier.
  28. type Stream struct {
  29. // Name is used for Client and Server functions identification.
  30. Name string
  31. // Key is the name of specific stream data.
  32. Key string
  33. // Live defines whether the stream delivers only new data
  34. // for the specific stream.
  35. Live bool
  36. }
  37. func NewStream(name string, key string, live bool) Stream {
  38. return Stream{
  39. Name: name,
  40. Key: key,
  41. Live: live,
  42. }
  43. }
  44. // String return a stream id based on all Stream fields.
  45. func (s Stream) String() string {
  46. t := "h"
  47. if s.Live {
  48. t = "l"
  49. }
  50. return fmt.Sprintf("%s|%s|%s", s.Name, s.Key, t)
  51. }
  52. // SubcribeMsg is the protocol msg for requesting a stream(section)
  53. type SubscribeMsg struct {
  54. Stream Stream
  55. History *Range `rlp:"nil"`
  56. Priority uint8 // delivered on priority channel
  57. }
  58. // RequestSubscriptionMsg is the protocol msg for a node to request subscription to a
  59. // specific stream
  60. type RequestSubscriptionMsg struct {
  61. Stream Stream
  62. History *Range `rlp:"nil"`
  63. Priority uint8 // delivered on priority channel
  64. }
  65. func (p *Peer) handleRequestSubscription(req *RequestSubscriptionMsg) (err error) {
  66. log.Debug(fmt.Sprintf("handleRequestSubscription: streamer %s to subscribe to %s with stream %s", p.streamer.addr.ID(), p.ID(), req.Stream))
  67. return p.streamer.Subscribe(p.ID(), req.Stream, req.History, req.Priority)
  68. }
  69. func (p *Peer) handleSubscribeMsg(req *SubscribeMsg) (err error) {
  70. metrics.GetOrRegisterCounter("peer.handlesubscribemsg", nil).Inc(1)
  71. defer func() {
  72. if err != nil {
  73. if e := p.Send(SubscribeErrorMsg{
  74. Error: err.Error(),
  75. }); e != nil {
  76. log.Error("send stream subscribe error message", "err", err)
  77. }
  78. }
  79. }()
  80. log.Debug("received subscription", "from", p.streamer.addr.ID(), "peer", p.ID(), "stream", req.Stream, "history", req.History)
  81. f, err := p.streamer.GetServerFunc(req.Stream.Name)
  82. if err != nil {
  83. return err
  84. }
  85. s, err := f(p, req.Stream.Key, req.Stream.Live)
  86. if err != nil {
  87. return err
  88. }
  89. os, err := p.setServer(req.Stream, s, req.Priority)
  90. if err != nil {
  91. return err
  92. }
  93. var from uint64
  94. var to uint64
  95. if !req.Stream.Live && req.History != nil {
  96. from = req.History.From
  97. to = req.History.To
  98. }
  99. go func() {
  100. if err := p.SendOfferedHashes(os, from, to); err != nil {
  101. log.Warn("SendOfferedHashes dropping peer", "err", err)
  102. p.Drop(err)
  103. }
  104. }()
  105. if req.Stream.Live && req.History != nil {
  106. // subscribe to the history stream
  107. s, err := f(p, req.Stream.Key, false)
  108. if err != nil {
  109. return err
  110. }
  111. os, err := p.setServer(getHistoryStream(req.Stream), s, getHistoryPriority(req.Priority))
  112. if err != nil {
  113. return err
  114. }
  115. go func() {
  116. if err := p.SendOfferedHashes(os, req.History.From, req.History.To); err != nil {
  117. log.Warn("SendOfferedHashes dropping peer", "err", err)
  118. p.Drop(err)
  119. }
  120. }()
  121. }
  122. return nil
  123. }
  124. type SubscribeErrorMsg struct {
  125. Error string
  126. }
  127. func (p *Peer) handleSubscribeErrorMsg(req *SubscribeErrorMsg) (err error) {
  128. return fmt.Errorf("subscribe to peer %s: %v", p.ID(), req.Error)
  129. }
  130. type UnsubscribeMsg struct {
  131. Stream Stream
  132. }
  133. func (p *Peer) handleUnsubscribeMsg(req *UnsubscribeMsg) error {
  134. return p.removeServer(req.Stream)
  135. }
  136. type QuitMsg struct {
  137. Stream Stream
  138. }
  139. func (p *Peer) handleQuitMsg(req *QuitMsg) error {
  140. return p.removeClient(req.Stream)
  141. }
  142. // OfferedHashesMsg is the protocol msg for offering to hand over a
  143. // stream section
  144. type OfferedHashesMsg struct {
  145. Stream Stream // name of Stream
  146. From, To uint64 // peer and db-specific entry count
  147. Hashes []byte // stream of hashes (128)
  148. *HandoverProof // HandoverProof
  149. }
  150. // String pretty prints OfferedHashesMsg
  151. func (m OfferedHashesMsg) String() string {
  152. return fmt.Sprintf("Stream '%v' [%v-%v] (%v)", m.Stream, m.From, m.To, len(m.Hashes)/HashSize)
  153. }
  154. // handleOfferedHashesMsg protocol msg handler calls the incoming streamer interface
  155. // Filter method
  156. func (p *Peer) handleOfferedHashesMsg(req *OfferedHashesMsg) error {
  157. metrics.GetOrRegisterCounter("peer.handleofferedhashes", nil).Inc(1)
  158. c, _, err := p.getOrSetClient(req.Stream, req.From, req.To)
  159. if err != nil {
  160. return err
  161. }
  162. hashes := req.Hashes
  163. want, err := bv.New(len(hashes) / HashSize)
  164. if err != nil {
  165. return fmt.Errorf("error initiaising bitvector of length %v: %v", len(hashes)/HashSize, err)
  166. }
  167. wg := sync.WaitGroup{}
  168. for i := 0; i < len(hashes); i += HashSize {
  169. hash := hashes[i : i+HashSize]
  170. if wait := c.NeedData(hash); wait != nil {
  171. want.Set(i/HashSize, true)
  172. wg.Add(1)
  173. // create request and wait until the chunk data arrives and is stored
  174. go func(w func()) {
  175. w()
  176. wg.Done()
  177. }(wait)
  178. }
  179. }
  180. // done := make(chan bool)
  181. // go func() {
  182. // wg.Wait()
  183. // close(done)
  184. // }()
  185. // go func() {
  186. // select {
  187. // case <-done:
  188. // s.next <- s.batchDone(p, req, hashes)
  189. // case <-time.After(1 * time.Second):
  190. // p.Drop(errors.New("timeout waiting for batch to be delivered"))
  191. // }
  192. // }()
  193. go func() {
  194. wg.Wait()
  195. select {
  196. case c.next <- c.batchDone(p, req, hashes):
  197. case <-c.quit:
  198. }
  199. }()
  200. // only send wantedKeysMsg if all missing chunks of the previous batch arrived
  201. // except
  202. if c.stream.Live {
  203. c.sessionAt = req.From
  204. }
  205. from, to := c.nextBatch(req.To + 1)
  206. log.Trace("received offered batch", "peer", p.ID(), "stream", req.Stream, "from", req.From, "to", req.To)
  207. if from == to {
  208. return nil
  209. }
  210. msg := &WantedHashesMsg{
  211. Stream: req.Stream,
  212. Want: want.Bytes(),
  213. From: from,
  214. To: to,
  215. }
  216. go func() {
  217. select {
  218. case <-time.After(120 * time.Second):
  219. log.Warn("handleOfferedHashesMsg timeout, so dropping peer")
  220. p.Drop(errors.New("handle offered hashes timeout"))
  221. return
  222. case err := <-c.next:
  223. if err != nil {
  224. log.Warn("c.next dropping peer", "err", err)
  225. p.Drop(err)
  226. return
  227. }
  228. case <-c.quit:
  229. return
  230. }
  231. log.Trace("sending want batch", "peer", p.ID(), "stream", msg.Stream, "from", msg.From, "to", msg.To)
  232. err := p.SendPriority(msg, c.priority)
  233. if err != nil {
  234. log.Warn("SendPriority err, so dropping peer", "err", err)
  235. p.Drop(err)
  236. }
  237. }()
  238. return nil
  239. }
  240. // WantedHashesMsg is the protocol msg data for signaling which hashes
  241. // offered in OfferedHashesMsg downstream peer actually wants sent over
  242. type WantedHashesMsg struct {
  243. Stream Stream
  244. Want []byte // bitvector indicating which keys of the batch needed
  245. From, To uint64 // next interval offset - empty if not to be continued
  246. }
  247. // String pretty prints WantedHashesMsg
  248. func (m WantedHashesMsg) String() string {
  249. return fmt.Sprintf("Stream '%v', Want: %x, Next: [%v-%v]", m.Stream, m.Want, m.From, m.To)
  250. }
  251. // handleWantedHashesMsg protocol msg handler
  252. // * sends the next batch of unsynced keys
  253. // * sends the actual data chunks as per WantedHashesMsg
  254. func (p *Peer) handleWantedHashesMsg(req *WantedHashesMsg) error {
  255. metrics.GetOrRegisterCounter("peer.handlewantedhashesmsg", nil).Inc(1)
  256. log.Trace("received wanted batch", "peer", p.ID(), "stream", req.Stream, "from", req.From, "to", req.To)
  257. s, err := p.getServer(req.Stream)
  258. if err != nil {
  259. return err
  260. }
  261. hashes := s.currentBatch
  262. // launch in go routine since GetBatch blocks until new hashes arrive
  263. go func() {
  264. if err := p.SendOfferedHashes(s, req.From, req.To); err != nil {
  265. log.Warn("SendOfferedHashes dropping peer", "err", err)
  266. p.Drop(err)
  267. }
  268. }()
  269. // go p.SendOfferedHashes(s, req.From, req.To)
  270. l := len(hashes) / HashSize
  271. log.Trace("wanted batch length", "peer", p.ID(), "stream", req.Stream, "from", req.From, "to", req.To, "lenhashes", len(hashes), "l", l)
  272. want, err := bv.NewFromBytes(req.Want, l)
  273. if err != nil {
  274. return fmt.Errorf("error initiaising bitvector of length %v: %v", l, err)
  275. }
  276. for i := 0; i < l; i++ {
  277. if want.Get(i) {
  278. metrics.GetOrRegisterCounter("peer.handlewantedhashesmsg.actualget", nil).Inc(1)
  279. hash := hashes[i*HashSize : (i+1)*HashSize]
  280. data, err := s.GetData(hash)
  281. if err != nil {
  282. return fmt.Errorf("handleWantedHashesMsg get data %x: %v", hash, err)
  283. }
  284. chunk := storage.NewChunk(hash, nil)
  285. chunk.SData = data
  286. if length := len(chunk.SData); length < 9 {
  287. log.Error("Chunk.SData to sync is too short", "len(chunk.SData)", length, "address", chunk.Addr)
  288. }
  289. if err := p.Deliver(chunk, s.priority); err != nil {
  290. return err
  291. }
  292. }
  293. }
  294. return nil
  295. }
  296. // Handover represents a statement that the upstream peer hands over the stream section
  297. type Handover struct {
  298. Stream Stream // name of stream
  299. Start, End uint64 // index of hashes
  300. Root []byte // Root hash for indexed segment inclusion proofs
  301. }
  302. // HandoverProof represents a signed statement that the upstream peer handed over the stream section
  303. type HandoverProof struct {
  304. Sig []byte // Sign(Hash(Serialisation(Handover)))
  305. *Handover
  306. }
  307. // Takeover represents a statement that downstream peer took over (stored all data)
  308. // handed over
  309. type Takeover Handover
  310. // TakeoverProof represents a signed statement that the downstream peer took over
  311. // the stream section
  312. type TakeoverProof struct {
  313. Sig []byte // Sign(Hash(Serialisation(Takeover)))
  314. *Takeover
  315. }
  316. // TakeoverProofMsg is the protocol msg sent by downstream peer
  317. type TakeoverProofMsg TakeoverProof
  318. // String pretty prints TakeoverProofMsg
  319. func (m TakeoverProofMsg) String() string {
  320. return fmt.Sprintf("Stream: '%v' [%v-%v], Root: %x, Sig: %x", m.Stream, m.Start, m.End, m.Root, m.Sig)
  321. }
  322. func (p *Peer) handleTakeoverProofMsg(req *TakeoverProofMsg) error {
  323. _, err := p.getServer(req.Stream)
  324. // store the strongest takeoverproof for the stream in streamer
  325. return err
  326. }