messages.go 11 KB

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